CASE
CASE in SQL is a conditional statement that provides a way of performing conditional logic in SQL queries. It allows for conditional scenarios where different expressions may be evaluated and different results returned based on the outcome of these expressions. It's similar to IF-THEN-ELSE statements found in other programming languages.
Example
Output
Explanation
In the SQL SELECT statement, the CASE statement evaluates the age
column. If the age
is less than 18, it returns ‘Child’. If the age
is between 18 and 64, it returns ‘Adult’. Else, it returns ‘Senior’. These results are labeled as ‘age_group’ in the final output.
Example
Output
id | Age_Group |
---|---|
1 | Adult |
2 | Senior |
3 | Underage |
Explanation
The CASE
statement in the query assigns a value to each row based on conditions related to the age
field. If the age
is less than 18, it returns ‘Underage’. If age
is 18 or more but less than or equal to 60, it returns ‘Adult’. For any other values, it returns ‘Senior’.
Example
Output
Explanation
The CASE
statement in the SQL code evaluates each row’s Salary
column and categorizes it into ‘High’, ‘Medium’, or ‘Low’. If the Salary
is over 10000, it falls into the ‘High’ category. If it is over 5000 but not over 10000, it falls into the ‘Medium’ category. If it doesn’t meet either of those conditions, by default it falls into the ‘Low’ category. The output table presents the resultant columns after the execution of the SQL query.
Example
Output
Explanation
In the example provided, the CASE statement is used to introduce a condition into a SQL query. The condition checks each row in the column “salary”. When the value in salary is greater than 50000, ‘High’ is returned by the CASE statement; for all other values ‘Low’ is returned. This result is then labelled as “Salary_Range”.
Example
Output
Explanation
The CASE statement is used to perform conditional logic in SQL. In the provided example, it separates countries from the “Country” table into ‘Very Large’, ‘Large’, and ‘Small’ based on population. For each row in the table, it checks the condition in sequence - if the population exceeds 1 billion, it is classified ‘Very Large’, if it exceeds 100 million it is ‘Large’, otherwise, it is ‘Small’.