Your cart is currently empty!
Author: alien
-
Khóa học miễn phí MySQL – Wildcards nhận dự án làm có lương
MySQL – Wildcards
Table of content
The MySQL wildcards
The MySQL wildcards are special characters used in combination with the LIKE operator to search for text patterns in a table column. MySQL provides two wildcards: percent (%) and underscore (_).
The following table mentions the use case of the two wildcards in MySQL −
S.NO Wildcard & Description 1 The percent (%)
Matches zero or one characters”. For example, ”a%” matches strings starting with ”a” like ”android” or ”aeroplane”.
2 The underscore (_)
Matches a single character. For instance, ”_un” matches three-character strings ending with ”un” like ”gun” or ”bun”
Syntax
Following is the syntax of % and _ wildcards in MySQL −
SELECT * FROM table_name WHERE column_name LIKE wildcard;
The wildcard characters can be used in combination with each other. The following table demonstrates different ways of using ”%” and ”_” with the LIKE operator in a WHERE clause −
S.NO Statement & Description 1 WHERE SALARY LIKE ”200%”
Finds any values that start with 200.
2 WHERE SALARY LIKE ”%200%”
Finds any values that have 200 in any position.
3 WHERE SALARY LIKE ”_00%”
Finds any values that have 00 in the second and third positions.
4 WHERE SALARY LIKE ”2_%_%”
Finds any values that start with 2 and are at least 3 characters in length.
5 WHERE SALARY LIKE ”%2”
Finds any values that end with 2.
6 WHERE SALARY LIKE ”2%0”
Finds any value that starts with 2 and ends with 0.
7 WHERE SALARY LIKE ”_2%3”
Finds any values that have a 2 in the second position and end with a 3.
8 WHERE SALARY LIKE ”2___3”
Finds any values in a five-digit number that start with 2 and end with 3.
The MySQL Percent % Wildcard
The MySQL % wildcard is a symbol used in SQL queries for pattern matching. It represents any sequence of characters (including zero characters) within a string.
When used with the LIKE operator in a WHERE clause, % allows you to search for values that match a specified pattern.
Example
First, let us create a table with the name CUSTOMERS using the following query −
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25) NOT NULL, SALARY DECIMAL(18, 2), PRIMARY KEY(ID) );
Now, let us insert values into the table created above using the INSERT statement as shown below −
INSERT INTO CUSTOMERS VALUES (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ), (2, ''Khilan'', 25, ''Delhi'', 1500.00 ), (3, ''Kaushik'', 23, ''Kota'', 2000.00 ), (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ), (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ), (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ), (7, ''Muffy'', 24, ''Indore'', 10000.00 );
The CUSTOMERS table obtained is as follows −
ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 Kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 Hyderabad 4500.00 7 Muffy 24 Indore 10000.00 Here, we are retrieving all the records from the CUSTOMERS table where SALARY starts with 2000 −
SELECT * FROM CUSTOMERS WHERE SALARY LIKE ''2000%
Output
The output of the above query is as given below −
ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 3 Kaushik 23 Kota 2000.00 Example
In the following query, we are fetching all the records where ADDRESS starts with ”D” and ends with ”i” −
SELECT * FROM CUSTOMERS WHERE ADDRESS LIKE ''D%i
Output
On executing the given query, the output is displayed as follows −
ID NAME AGE ADDRESS SALARY 2 Khilan 25 Delhi 1500.00 Example
Here, we are finding all the records where ADDRESS ends with ”d” −
SELECT * FROM CUSTOMERS WHERE ADDRESS LIKE ''%d
Output
When we execute the above query, the output is obtained as follows −
ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 6 Komal 22 Hyderabad 4500.00 Example
In the following query, we are trying to fetch all the records where SALARY has ”1” in any position −
SELECT * FROM CUSTOMERS WHERE SALARY LIKE ''%1%
Output
The output produced from the above query is as follows −
ID NAME AGE ADDRESS SALARY 2 Khilan 25 Delhi 1500.00 7 Muffy 24 Indore 10000.00 The MySQL Underscore _ Wildcard
The MySQL underscore Wildcard represents a single character at the position where it is used. When combined with the LIKE operator in a WHERE clause, the underscore wildcard allows you to search for values that match a specific pattern with a single character placeholder.
Example
Here, we are retrieving all the CUSTOMERS with NAME starting with a character, followed by ”ardik” −
SELECT * FROM CUSTOMERS WHERE NAME LIKE ''_ardik
Output
Let us compile and run the query, to produce the following result −
ID NAME AGE ADDRESS SALARY 5 Hardik 27 Bhopal 8500.00 Example
Now, we are retrieving all CUSTOMERS with NAME starting with ”M”, followed by any character, followed by ”f”, followed by any character, followed by ”y” −
SELECT * FROM CUSTOMERS WHERE NAME LIKE ''M_f_y
Output
When we execute the above query, the output is obtained as follows −
ID NAME AGE ADDRESS SALARY 7 Muffy 24 Indore 10000.00 Example
In the below query, we are retrieving all the records where SALARY have ”500” in the second, third, and fourth positions −
SELECT * FROM CUSTOMERS WHERE SALARY LIKE ''_500%
Output
On executing the given query, the output is displayed as follows −
ID NAME AGE ADDRESS SALARY 2 Khilan 25 Delhi 1500.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 Hyderabad 4500.00 Example
In the following query, we are retrieving all the records where ADDRESS starts with ”M” and is at least 3 characters in length −
SELECT * FROM CUSTOMERS WHERE ADDRESS LIKE ''M_%_%
Output
The output of the above query is produced as given below −
ID NAME AGE ADDRESS SALARY 4 Chaitali 25 Mumbai 6500.00 Example
The following query retrieves all records where NAME has ”h” in the second position and ends with ”i” −
SELECT * FROM CUSTOMERS WHERE NAME LIKE ''_h%i
Output
If we compile and run the query, the result is produced as follows −
ID NAME AGE ADDRESS SALARY 4 Chaitali 25 Mumbai 6500.00
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc
Khóa học miễn phí MySQL – ROLLUP nhận dự án làm có lương
MySQL – ROLLUP
The MySQL ROLLUP Clause
The MySQL ROLLUP Clause is an extension of the GROUP BY Clause. It is used with aggregate functions in MySQL to find the grand total or a summary of a column”s values (also known as super-aggregate of a column), in an extra row within a table.
Consider a manufacturing factory that tracks monthly production data in a table. To determine the annual product production, you can use the SUM() aggregate function along with ROLLUP. However, if you need to find out the number of months where production falls below a specific threshold, ROLLUP will allow you to count such months as well using the COUNT() function.
Syntax
Following is the syntax of ROLLUP clause in MySQL −
SELECT AggregateFunction(column_name(s)), column_name(s) FROM table_name GROUP BY column_name(s) WITH ROLLUP;
Example
First, we will create a table named “PRODUCT” containing production information such as product ID, product name, product count, and manufacturing month within an organization −
CREATE TABLE PRODUCT ( PRODUCT_ID INT, PRODUCT_NAME VARCHAR(50), PRODUCT_COUNT INT, MONTH VARCHAR(20) );
Now, let us insert some data into the above-created table −
INSERT INTO PRODUCT VALUES (101, ''Comb'', 2345, ''January''), (102, ''Coffee Mugs'', 1242, ''January''), (103, ''Cutlery'', 124, ''January''), (101, ''Comb'', 3263, ''February''), (102, ''Coffee Mugs'', 10982, ''February''), (103, ''Cutlery'', 435, ''February'');
The PRODUCT table obtained is as follows −
PRODUCT_ID | PRODUCT_NAME | PRODUCT_COUNT | MONTH |
---|---|---|---|
101 | Comb | 2345 | January |
102 | Coffee Mugs | 1242 | January |
103 | Cutlery | 124 | January |
101 | Comb | 3263 | February |
102 | Coffee Mugs | 10982 | February |
103 | Cutlery | 435 | February |
Now, let us to find the sum of products manufactured each MONTH using ROLLUP as shown below −
SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP;
Output
you can observe in the output below that the individual product counts for both January and February are calculated, and the grand total of total production is displayed in the third row using ROLLUP −
SUM(PRODUCT_COUNT) | MONTH |
---|---|
14680 | February |
3711 | January |
18391 | NULL |
ROLLUP on Multiple Columns
You can also use ROLLUP on multiple columns by grouping them together using GROUP BY clause.
Example
Here, we are applying the GROUP BY clause on columns ”PRODUCT_ID” and ”PRODUCT_NAME” of the PRODUCT table −
SELECT PRODUCT_ID, COUNT(PRODUCT_ID) AS PROD_ID_COUNT, PRODUCT_NAME, COUNT(PRODUCT_NAME) AS PROD_ID_NAME FROM PRODUCT GROUP BY PRODUCT_ID, PRODUCT_NAME;
We get the following output −
PRODUCT_ID | PROD_ID_COUNT | PRODUCT_NAME | PROD_ID_NAME |
---|---|---|---|
101 | 2 | Comb | 2 |
102 | 2 | Coffee Mugs | 2 |
103 | 2 | Cutlery | 2 |
Now, calculate the summary of these two rows using ROLLUP as shown in the following query −
SELECT PRODUCT_ID, COUNT(PRODUCT_ID) AS PROD_ID_COUNT, PRODUCT_NAME, COUNT(PRODUCT_NAME) AS PROD_ID_NAME FROM PRODUCT GROUP BY PRODUCT_ID, PRODUCT_NAME WITH ROLLUP;
You can see in the output below that the summary is calculated not only at the final level but also at two levels. For every product name, a column summary is displayed −
PRODUCT_ID | PROD_ID_COUNT | PRODUCT_NAME | PROD_ID_NAME |
---|---|---|---|
101 | 2 | Comb | 2 |
101 | 2 | NULL | 2 |
102 | 2 | Coffee Mugs | 2 |
102 | 2 | NULL | 2 |
103 | 2 | Cutlery | 2 |
103 | 2 | NULL | 2 |
NULL | 6 | NULL | 6 |
Rollup Using Client Program
We can also perform rollup Using Client Program.
Syntax
To calculate grand total of a column through a PHP program use ROLLUP with aggregate function, we need to execute the “SELECT” statement using the mysqli function query() as follows −
$sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; $mysqli->query($sql);
To calculate grand total of a column through a JavaScript program use ROLLUP with aggregate function, we need to execute the “SELECT” statement using the query() function of mysql2 library as follows −
sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; con.query(sql);
To calculate grand total of a column through a Java program use ROLLUP with aggregate function, we need to execute the “SELECT” statement using the JDBC function executeQuery() as follows −
String sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; statement.executeQuery(sql);
To calculate grand total of a column through a Python program use ROLLUP with aggregate function, we need to execute the “SELECT” statement using the execute() function of the MySQL Connector/Python as follows −
rollup_query = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP" cursorObj.execute(rollup_query)
Example
Following are the programs −
$dbhost = ''localhost $dbuser = ''root $dbpass = ''password $db = ''TUTORIALS $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf(''Connected successfully.
''); $sql = "CREATE TABLE PRODUCT ( PRODUCT_ID INT, PRODUCT_NAME VARCHAR(50), PRODUCT_COUNT INT, MONTH VARCHAR(20) )"; if($mysqli->query($sql)){ printf("Product table created successfully....!"); } //now let''s insert some records into the table $sql = "INSERT INTO PRODUCT VALUES(101, ''Comb'', 2345, ''January'')"; if($mysqli->query($sql)){ printf("First record inserted successfully...!n"); } $sql = "INSERT INTO PRODUCT VALUES(102, ''Coffee Mugs'', 1242, ''January'')"; if($mysqli->query($sql)){ printf("Second record inserted successfully...!n"); } $sql = "INSERT INTO PRODUCT VALUES(103, ''Cutlery'', 124, ''January'')"; if($mysqli->query($sql)){ printf("Third record inserted successfully...!n"); } $sql = "INSERT INTO PRODUCT VALUES(101, ''Comb'', 3263, ''February'')"; if($mysqli->query($sql)){ printf("Fourth record inserted successfully...!n"); } //display the table records $sql = "SELECT * FROM PRODUCT"; if($result = $mysqli->query($sql)){ printf("Table records: n"); while($row = mysqli_fetch_array($result)){ printf("PRODUCT_ID: %d, PRODUCT_NAME: %s, PRODUCT_COUNT: %d, MONTH: %s", $row[''PRODUCT_ID''], $row[''PRODUCT_NAME''], $row[''PRODUCT_COUNT''], $row[''MONTH'']); printf("n"); }} //let''s find the sum of product $sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; if($result = $mysqli->query($sql)){ printf("Sum of product: n"); while($row = mysqli_fetch_array($result)){ printf("Sum of product: %d, MONTH: %s", $row[''SUM(PRODUCT_COUNT)''], $row[''MONTH'']); printf("n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();
Output
The output obtained is as shown below −
Product table created successfully....! First record inserted successfully...! Second record inserted successfully...! Third record inserted successfully...! Fourth record inserted successfully...! Table records: PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 2345, MONTH: January PRODUCT_ID: 102, PRODUCT_NAME: Coffee Mugs, PRODUCT_COUNT: 1242, MONTH: January PRODUCT_ID: 103, PRODUCT_NAME: Cutlery, PRODUCT_COUNT: 124, MONTH: January PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 3263, MONTH: February Sum of product: Sum of product: 3263, MONTH: February Sum of product: 3711, MONTH: January Sum of product: 6974, MONTH:
var mysql = require(''mysql2''); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); // Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); // Create a new database sql = "Create Database TUTORIALS"; con.query(sql); sql = "USE TUTORIALS"; con.query(sql); sql = "CREATE TABLE PRODUCT (PRODUCT_ID INT,PRODUCT_NAME VARCHAR(50),PRODUCT_COUNT INT,MONTH VARCHAR(20));" con.query(sql); sql = "INSERT INTO PRODUCT VALUES(101, ''Comb'', 2345, ''January''),(102, ''Coffee Mugs'', 1242, ''January''),(103, ''Cutlery'', 124, ''January''),(101, ''Comb'', 3263, ''February''),(102, ''Coffee Mugs'', 10982, ''February''),(103, ''Cutlery'', 435, ''February'');" con.query(sql); sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; con.query(sql, function(err, result){ if (err) throw err console.log(result); }); });
Output
The output obtained is as shown below −
Connected! -------------------------- [ { ''SUM(PRODUCT_COUNT)'': ''14680'', MONTH: ''February'' }, { ''SUM(PRODUCT_COUNT)'': ''3711'', MONTH: ''January'' }, { ''SUM(PRODUCT_COUNT)'': ''18391'', MONTH: null } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RollUp { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); //create a table with name Product String sql = "CREATE TABLE PRODUCT ( PRODUCT_ID INT, PRODUCT_NAME VARCHAR(50), PRODUCT_COUNT INT, MONTH VARCHAR(20) )"; st.execute(sql); System.out.println("Product table created successfully....!"); //let''s insert some records into it... String sql1 = "INSERT INTO PRODUCT VALUES(101, ''Comb'', 2345, ''January''), (102, ''Coffee Mugs'', 1242, ''January''), (103, ''Cutlery'', 124, ''January''), (101, ''Comb'', 3263, ''February'')"; st.execute(sql1); System.out.println("Records inserted successfully...!"); //print table records String sql2 = "SELECT * FROM PRODUCT"; rs = st.executeQuery(sql2); System.out.println("Table records: "); while(rs.next()) { String PRODUCT_ID = rs.getString("PRODUCT_ID"); String PRODUCT_NAME = rs.getString("PRODUCT_NAME"); String PRODUCT_COUNT = rs.getString("PRODUCT_COUNT"); String MONTH = rs.getString("MONTH"); System.out.println("PRODUCT_ID: " + PRODUCT_ID + ", PRODUCT_NAME: " + PRODUCT_NAME + ", PRODUCT_COUNT: " + PRODUCT_COUNT + ", MONTH: " + MONTH); } //let''s calculate the sum of product with RollUp String sql3 = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; rs = st.executeQuery(sql3); System.out.println("Sum of product: "); while(rs.next()) { String sum = rs.getString("SUM(PRODUCT_COUNT)"); String MONTH = rs.getString("MONTH"); System.out.println("Sum: " + sum + ", MONTH: " + MONTH); } }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
Product table created successfully....! Records inserted successfully...! Table records: PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 2345, MONTH: January PRODUCT_ID: 102, PRODUCT_NAME: Coffee Mugs, PRODUCT_COUNT: 1242, MONTH: January PRODUCT_ID: 103, PRODUCT_NAME: Cutlery, PRODUCT_COUNT: 124, MONTH: January PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 3263, MONTH: February Sum of product: Sum: 3263, MONTH: February Sum: 3711, MONTH: January Sum: 6974, MONTH: null
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host=''localhost'', user=''root'', password=''password'', database=''tut'' ) # Creating a cursor object cursorObj = connection.cursor() # providing rollup query rollup_query = """SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP""" cursorObj.execute(rollup_query) # Fetching and printing the results results = cursorObj.fetchall() print("Rollup Results:") for row in results: print(f"Product Count: {row[0]}, MONTH: {row[1]}") # Closing the cursor and connection cursorObj.close() connection.close()
Output
The output obtained is as shown below −
Rollup Results: Product Count: 14680, MONTH: February Product Count: 3711, MONTH: January Product Count: 18391, MONTH: None
Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc