Your cart is currently empty!
Author: alien
-
Khóa học miễn phí SQL – CASE nhận dự án làm có lương
SQL – CASE
Table of content
The SQL CASE Statement
The SQL CASE statement is a conditional statement that helps us to make decisions based on a set of conditions. It evaluates the set of conditions and returns the respective values when a condition is satisfied.
The CASE statement works like a simplified IF-THEN-ELSE statement and allows for multiple conditions to be tested.
This starts with the keyword CASE followed by multiple conditionals statements. Each conditional statement consists of at least one pair of WHEN and THEN statements. Where WHEN specifies conditional statements and THEN specifies the actions to be taken.
It is often used to create a new column with values based on the value of an existing column.
Let us look at a simple scenario to understand this statement.
For e.g. when the credit limit of a customer is above ”10,000”, then the customer will be recognized as a ”High value customer when the credit limit is above ”5000”, then the customer will be recognized as a ”Mid value customer otherwise the customer will be recognized as the ”Low value customer” as shown in the table below −
Syntax
Following is the syntax of SQL CASE statement −
CASE WHEN condition1 THEN statement1, WHEN condition2 THEN statement2, WHEN condition THEN statementN ELSE result END;
Where, condition1, condition2, etc. Are the conditional statements and statement1, statement2, etc.. are the actions to be taken when the condition is true.
Once the condition is met, the CASE statement will stop verifying further and it will return the result.
-
If none of the conditions are met (TRUE), then it returns the value mentioned in the ELSE clause.
-
It returns NULL if the ELSE part is not mentioned and none of the conditions are TRUE.
Example
Assume we have created a table named CUSTOMERS which contains the personal details of customers including their name, age, address and salary etc. using the following query −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Now, insert values into this table using the INSERT statement as follows −
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 table will be created 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 In the following query, we are using multiple WHEN and THEN conditions to the CASE statement along with the ELSE clause.
If the AGE of the customer is greater than 30, it returns Gen X otherwise moves to the further WHEN and THEN conditions. If none of the conditions is matched with the CUSTOMERS table, CASE returns the ”Gen Alpha” value as mentioned in the ELSE part of the query −
SELECT NAME, AGE, CASE WHEN AGE > 30 THEN ''Gen X'' WHEN AGE > 25 THEN ''Gen Y'' WHEN AGE > 22 THEN ''Gen Z'' ELSE ''Gen Alpha'' END AS Generation FROM CUSTOMERS;
Output
The output produced is as follows −
NAME AGE Generation Ramesh 32 Gen X Khilan 25 Gen Z Kaushik 23 Gen Z Chaitali 25 Gen Z Hardik 27 Gen Y Komal 22 Gen Alpha Muffy 24 Gen Z Example
Let us take a look at another query where we want to provide a 25% increment to each customer if the amount is less than 4500 from the CUSTOMERS table previously created −
SELECT *, CASE WHEN SALARY < 4500 THEN (SALARY + SALARY * 25/100) END AS INCREMENT FROM CUSTOMERS;
Output
Here, the SQL command checks if the salary is less than 4500. If this condition is satisfied, a new column ”INCREMENT” will contain the values that is equal to salary with 25% of increment.
Since the ELSE part is not mentioned in the above query and none of the conditions are true for few CUSTOMERS, NULL is returned, which shows that they didn”t get any increment.
ID NAME AGE ADDRESS SALARY INCREMENT 1 Ramesh 32 Ahmedabad 2000.00 2500.000000 2 Khilan 25 Delhi 1500.00 1875.000000 3 Kaushik 23 Kota 2000.00 2500.000000 4 Chaitali 25 Mumbai 6500.00 NULL 5 Hardik 27 Bhopal 8500.00 NULL 6 Komal 22 Hyderabad 4500.00 NULL 7 Muffy 24 Indore 10000.00 NULL CASE Statement with ORDER BY Clause
We can use CASE statement with ORDER BY clause. The ORDER BY clause in SQL sorts the result in ascending (default) or descending order.
Example
In this query, the CASE statement is used to sort the results based on either the ”NAME” column or the ”ADDRESS” column, depending on the value of the ”NAME” column. If the ”NAME” column starts with ”K”, the results are sorted by the ”NAME” column; otherwise, the results are sorted by the ”ADDRESS” column −
SELECT * FROM CUSTOMERS ORDER BY (CASE WHEN NAME LIKE ''k%'' THEN NAME ELSE ADDRESS END);
Output
The result obtained by executing the above query is as shown below −
ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 5 Hardik 27 Bhopal 8500.00 7 Muffy 24 Indore 10000.00 3 Kaushik 23 Kota 2000.00 2 Khilan 25 Delhi 1500.00 6 Komal 22 Hyderabad 4500.00 4 Chaitali 25 Mumbai 6500.00 CASE Statement with GROUP BY Clause
We can also use the CASE statement with GROUP BY clause. The GROUP BY clause in SQL groups the rows that have same values within one or more columns where an aggregate function is applied to produce summaries.
Example
In the following query we are grouping the customers based on their salaries and calculate the sum of the salary for a specified range of customer data.
If the value in SALARY is less than or equal to 4000, the data will be grouped as ”Lowest paid”. If the value is greater than 4000 and less than or equal to 6500, it will be grouped as ”Average paid”. All other values will be grouped as ”Highest paid”. The SUM function is used to calculate the total of the SALARY for each group −
SELECT CASE WHEN SALARY <= 4000 THEN ''Lowest paid'' WHEN SALARY > 4000 AND SALARY <= 6500 THEN ''Average paid'' ELSE ''Highest paid'' END AS SALARY_STATUS, SUM(SALARY) AS Total FROM CUSTOMERS GROUP BY CASE WHEN SALARY <= 4000 THEN ''Lowest paid'' WHEN SALARY > 4000 AND SALARY <= 6500 THEN ''Average paid'' ELSE ''Highest paid'' END;
Output
Following is the output of the above query −
SALARY_STATUS Total Lowest paid 5500.00 Average paid 11000.00 Highest paid 18500.00 CASE Statement with WHERE Clause
We can use the CASE statement with the WHERE clause as well. The WHERE clause is used to filter the rows in a table based on a specified condition.
Example
In the following query, the CASE statement is used to return the different designations of the CUSTOMERS based on their AGE. The WHERE clause is used to filter the rows based on the SALARY of the CUSTOMERS −
SELECT NAME, ADDRESS, CASE WHEN AGE < 25 THEN ''Intern'' WHEN AGE >= 25 and AGE <= 27 THEN ''Associate Engineer'' ELSE ''Senior Developer'' END as Designation FROM CUSTOMERS WHERE SALARY >= 2000;
Output
Output of the above query is as follows −
NAME ADDRESS Designation Ramesh Ahmedabad Senior Developer Kaushik Kota Intern Chaitali Mumbai Associate Engineer Hardik Bhopal Associate Engineer Komal Hyderabad Intern Muffy Indore Intern CASE Statement with UPDATE
We can use CASE statement within the UPDATE statement to perform conditional updates on data in a table.
Example
In the following query we are updating the salary of all the customers based on their age.
If the age of the customer is equal to ”25”, their salary will be updated to ”17000”. If the age is equal to ”32”, it will be updated to ”25000”. For the customers with other ages, salaries will be updated to ”12000” −
UPDATE CUSTOMERS SET SALARY= CASE AGE WHEN 25 THEN 17000 WHEN 32 THEN 25000 ELSE 12000 END;
Output
We get the following result. We can observe that the changes have been done in 7 rows −
Query OK, 7 rows affected (0.02 sec) Rows matched: 7 Changed: 7 Warnings: 0
Verification
We can rectify the changes done in the CUSTOMERS table using the below query −
SELECT * FROM CUSTOMERS;
The table is displayed as follows −
ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 25000.00 2 Khilan 25 Delhi 17000.00 3 Kaushik 23 Kota 12000.00 4 Chaitali 25 Mumbai 17000.00 5 Hardik 27 Bhopal 12000.00 6 Komal 22 Hyderabad 12000.00 7 Muffy 24 Indore 12000.00 As we can see in the above table, the SALARY of all the customers has been updated corresponding to their age.
CASE Statement with INSERT
We can also insert the data into MySQL tables with the help of the CASE statement. We need to provide the INSERT INTO statement with column names and VALUES for data insertion.
Example
Here, if the age of the customer is greater than or equal to 25, then the salary will be 23000; otherwise the salary will be 14000 −
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (10, ''Viren'', 28, ''Varanasi'', CASE WHEN AGE >= 25 THEN 23000 ELSE 14000 END );
Output
We get the following result. We can observe that the change has been done in 1 row −
Query OK, 1 row affected (0.01 sec)
Verification
We can rectify the changes done in the CUSTOMERS table using the below query −
SELECT * FROM CUSTOMERS;
The table is displayed 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 10 Viren 28 Varanasi 23000.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í SQL – EXISTS Operator nhận dự án làm có lương
SQL – EXISTS Operator
The SQL EXISTS Operator
The SQL EXISTS operator is used to verify whether a particular record exists in a MySQL table. While using this operator we need to specify the record (for which you have to check the existence) using a subquery.
The EXISTS operator is used in the WHERE clause of a SELECT statement to filter records based on the existence of related records in another table.
-
It is a logical operator.
-
It returns a Boolean value TRUE or FALSE.
-
It returns TRUE if the subquery returns at least one record.
-
If the EXISTS operator returns TRUE, the outer query will get executed; otherwise not.
-
It can be used in SELECT, UPDATE, DELETE or INSERT statements.
The EXISTS operator is more efficient than other operators, such as IN, because it only needs to determine whether any rows are returned by the subquery, rather than actually returning the data.
The use of the EXISTS operator is an efficient way to filter data in many real-life scenarios, including filtering records based on the existence of related data, aggregating data based on the existence of related records, and optimizing queries.
Syntax
The basic syntax of the SQL EXISTS operator is as follows −
WHERE EXISTS (subquery);
Where, the subquery used is the SELECT statement. The EXISTS operator will evaluate to TRUE if the subquery returns at least one record in its result set; otherwise FALSE.
EXISTS Operator with SELECT Statement
The SELECT statement in SQL is used to retrieve data from one or more tables in a database. We can use the EXISTS operator with a SELECT statement to check for the existence of rows that meet a certain condition.
Example
To understand it better let us consider the CUSTOMERS table which contains the personal details of customers including their name, age, address and salary etc. as shown below −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
Now, insert values into this table using the INSERT statement as follows −
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 table will be created 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 |
Let us create another table CARS, containing the details such as id of the customer, name and price of the car, using the following query −
create table CARS( ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, PRICE INT NOT NULL, PRIMARY KEY(ID) );
Using the INSERT statement, let us insert values into this table −
insert INTO CARS VALUES (2, ''Maruti Swift'', 450000), (4, ''VOLVO'', 2250000), (7, ''Toyota'', 2400000);
The ”CARS” table obtained is as follows −
ID | NAME | PRICE |
---|---|---|
2 | Maruti Swift | 450000 |
4 | VOLVO | 2250000 |
7 | Toyota | 2400000 |
Now, we are retrieving the lists of the customers with the price of the car greater than 2,000,000 −
SELECT * FROM CUSTOMERS WHERE EXISTS ( SELECT PRICE FROM CARS WHERE CARS.ID = CUSTOMERS.ID AND PRICE > 2000000 );
Output
The result produced is as follows −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
4 | Chaitali | 25 | Mumbai | 6500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
EXISTS Operator with UPDATE Statement
We can also use the SQL EXISTS operator with an UPDATE statement. It helps us to update rows in a table based on the existence of matching rows in another table.
Example
Suppose if we want to change the name of certain customers from the CUSTOMERS and CARS tables previously created, then this can be done using UPDATE statement. Here, we are modifying the name ”Kushal” of all the customers whose id is equal to the id of the CARS table, using the EXISTS operator, as follows −
UPDATE CUSTOMERS SET NAME = ''Kushal'' WHERE EXISTS ( SELECT NAME FROM CARS WHERE CUSTOMERS.ID = CARS.ID );
Output
We get the following result. We can observe that 3 rows have been modified −
Query OK, 3 rows affected (0.01 sec) Rows matched: 3 Changed: 3 Warnings: 0
Verification
We can verify whether the changes are reflected in a table by retrieving its contents using the SELECT statement. Following is the query to display the records in the CUSTOMERS table −
SELECT * FROM CUSTOMERS;
The table is displayed as follows −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Kushal | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Kushal | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Kushal | 24 | Indore | 10000.00 |
As we can see in the above table, the NAME of ”Khilan”, ”Chaitali” and ”Muffy” has been updated to ”Kushal”.
EXISTS Operator with DELETE Statement
The EXISTS operator can also be used with a DELETE statement to delete rows based on the existence of rows returned by a subquery.
Example
In here, we are deleting the row in the CUSTOMERS table whose id is equal to the id of the CARS table having price equal to ”2250000” −
DELETE FROM CUSTOMERS WHERE EXISTS ( SELECT * FROM CARS WHERE CARS.ID = CUSTOMERS.ID AND CARS.PRICE = 2250000 );
Output
We get the following result. We can observe that 1 row has been deleted −
Query OK, 1 row affected (0.01 sec)
Verification
We can rectify the changes done in the CUSTOMERS table using the following query −
SELECT * FROM CUSTOMERS;
The table is displayed 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 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
As we can see in the above table, the row with the NAME ”Chaitali” has been deleted since the id of Chaitali in CUSTOMERS table was ”4”, which is equal to the id of the CARS table having price equal to ”2250000”.
NOT Operator with EXISTS Operator
In SQL, the NOT EXISTS operator is used to select records from one table that do not exist in another table.
Syntax
Following is the basic syntax of NOT EXISTS operator in SQL −
WHERE NOT EXISTS (subquery);
Where, the subquery used is the SELECT statement.
Example
The below query gives the names of the customers who have not bought any car −
SELECT * FROM CUSTOMERS WHERE NOT EXISTS ( SELECT * FROM CARS WHERE CUSTOMERS.ID = CARS.ID );
Output
Following output is obtained by executing the above query −
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
Usage of SQL EXISTS Operator
The EXISTS operator in SQL is widely used in real-life scenarios to filter records based on the existence of related data in another table. Some common use cases include −
-
Checking for the existence of records in a many-to-many relationship − The EXISTS operator can be used to check whether a record exists in a join table for a many-to-many relationship, for example, finding all customers who have purchased a particular product.
-
Filtering records based on the existence of related records − The EXISTS operator can be used to filter records based on the existence of related records in another table. For example, finding all orders that have associated order details.
-
Aggregating data based on the existence of related records − The EXISTS operator can be used to aggregate data based on the existence of related records. For example, finding the number of customers who have placed an order.
-
Optimizing queries − The EXISTS operator can be used to optimize queries by only returning the necessary data. For example, finding the first order for each customer without using a self-join.
These are just a few examples of how the EXISTS operator can be used in real-life scenarios. The specific use case will depend on the data and the requirements of the query.
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