GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — SQL - CASE Statement
Selected Reading
SQL - CASE Statement
The SQL CASE StatementThe SQL CASE statement is used to apply conditional logic in queries. It acts like an IF-THEN-ELSE statement, which checks conditions and returns a value based on the first match.
SyntaxFollowing is the syntax of SQL CASE statement: CASE WHEN condition1 THEN result1, WHEN condition2 THEN result2, WHEN condition THEN resultN ELSE result END; Where,
Once a condition is true, the CASE statement stops checking the remaining conditions and returns the matching result.
Example: Categorizing by AgeAssume 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:
In the following example, we use the CASE statement to check the customer's age and return a specific label. If the age is greater than 30, we return 'Gen X'. If that condition is not met, the next WHEN conditions are evaluated in order. If none of the conditions match, the ELSE clause returns 'Gen Alpha': 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; The output produced is as follows:
Example: Conditional Salary IncrementIn this example, we increase the salary by 25% for customers earning less than 4500. The CASE statement checks this condition and stores the updated value in the INCREMENT column. Since there is no ELSE clause, customers who do not meet the condition get NULL in the INCREMENT column: SELECT *, CASE WHEN SALARY < 4500 THEN (SALARY + SALARY * 25/100) END AS INCREMENT FROM CUSTOMERS; The table produced is as shown below:
Simple CASE StatementA Simple CASE statement checks one value and compares it to several possible values. It returns a result based on the first match it finds. This is useful when you need to compare the same column or expression to multiple specific values. ExampleIn this query, we compare the AGE column directly with specific values and return the corresponding title: SELECT NAME, AGE, CASE AGE WHEN 22 THEN 'Trainee' WHEN 23 THEN 'Junior Engineer' WHEN 25 THEN 'Software Engineer' ELSE 'Senior Staff' END AS Title FROM CUSTOMERS; We get the output as shown below:
Searched CASE StatementA Searched CASE statement checks each condition separately, and each condition can use its own boolean expression. This lets you test ranges, compare values with operators, or check multiple columns in the same WHEN clause.
ExampleHere, we use different range conditions to categorize customers by salary: SELECT NAME, SALARY, CASE WHEN SALARY < 3000 THEN 'Low Income' WHEN SALARY BETWEEN 3000 AND 7000 THEN 'Middle Income' WHEN SALARY > 7000 THEN 'High Income' END AS Income_Level FROM CUSTOMERS; Following is the output obtained:
SQL CASE in SELECT ClauseA CASE statement in the SELECT clause is used to create new columns or change how data appears in query results, without modifying the actual data in the table.
ExampleIn this query, we display a custom label for each customer's age group directly in the result set: SELECT NAME, AGE, CASE WHEN AGE < 25 THEN 'Youth' WHEN AGE BETWEEN 25 AND 30 THEN 'Adult' ELSE 'Senior' END AS Age_Group FROM CUSTOMERS; Following is the output obtained:
SQL CASE with ORDER BY ClauseThe ORDER BY clause in SQL sorts the result in ascending (default) or descending order. You can use a CASE statement inside ORDER BY to apply conditional sorting rules. Normally, ORDER BY sorts rows based on one or more columns, but with CASE you can define custom sort values for each row depending on specific conditions. This allows more control over the sort order. ExampleIn this query, the CASE statement sorts rows based on either the NAME or ADDRESS column, depending on the value in NAME. If NAME starts with 'K', the sorting is done by NAME; otherwise, it is done by ADDRESS: SELECT * FROM CUSTOMERS
ORDER BY
(CASE
WHEN NAME LIKE 'k%' THEN NAME
ELSE ADDRESS
END);
The result obtained by executing the above query is as shown below:
SQL CASE with GROUP BY ClauseYou can use a CASE statement inside the GROUP BY clause to define conditional grouping rules. This allows you to group rows into custom categories based on specific conditions instead of grouping only by the original column values. ExampleIn this query we group customers into three salary ranges: Lowest paid (≤ 4000), Average paid (> 4000 and ≤ 6500), and Highest paid (all others), and use SUM to calculate the total 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;
Following is the output of the above query:
SQL CASE with WHERE ClauseThe SQL WHERE clause is used to filter rows based on a specified condition. While you cannot directly use a CASE statement to control which rows are returned (because CASE returns values rather than boolean conditions), you can use CASE inside the WHERE clause with logical operators to build conditional filtering rules. This approach allows you to apply different filter criteria based on specific conditions in the data. ExampleIn 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 of the above query is as follows:
SQL CASE with UPDATE StatementYou can use a CASE statement inside an UPDATE query to update rows conditionally. This allows you to assign different values to a column based on specified conditions, all within a single statement. ExampleIn 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; 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 VerificationWe can rectify the changes done in the CUSTOMERS table using the below query: SELECT * FROM CUSTOMERS; The table is displayed as follows:
As we can see in the above table, the SALARY of all the customers has been updated corresponding to their age. SQL CASE with INSERT StatementA CASE statement can be used in an INSERT query to set column values conditionally when adding new rows. This allows you to assign values dynamically based on specific conditions during insertion. ExampleHere, 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
);
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) VerificationWe can rectify the changes done in the CUSTOMERS table using the below query: SELECT * FROM CUSTOMERS; The table is displayed as follows:
Nested CASE StatementsA Nested CASE statement is a CASE expression inside another CASE expression. This is used when the result of one CASE needs further evaluation based on additional conditions.
ExampleHere, the first CASE determines the income category, and the second CASE (nested) assigns a bonus percentage based on that category: SELECT NAME, SALARY,
CASE
WHEN SALARY < 5000 THEN
CASE
WHEN SALARY < 3000 THEN 'Bonus 20%'
ELSE 'Bonus 10%'
END
ELSE 'No Bonus'
END AS Bonus_Plan
FROM CUSTOMERS;
The table produced is as shown below:
Differences Between CASE and IF-ELSEBoth CASE statements and IF-ELSE logic are used for conditional processing in SQL, but they differ in how they are written and where they can be used:
Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |