Tutorial Playlist
46 Lessons1. SQL Tutorial
2. The Essential Guide To Understanding SQL In DBMS
3. SQL Commands
4. SQL Data Types
5. SQL Aliases
6. SQL INSERT INTO With Examples
7. Master SQL Update
8. SQL Delete Statement: A Complete Overview with Examples
9. SQL WHERE Clause
10. SQL AND Operator
11. SQL NOT Operator: A Comprehensive Guide
12. SQL Like
13. SQL Between Operator: A Complete Overview with Examples
14. Difference Between SQL and MySQL: Get to Know Your DBMS
15. MySQL Workbench
16. A Comprehensive Guide to MySQL Workbench Installation and Configuration
17. Mastering SQL: Your Comprehensive Guide to Becoming an SQL Developer
18. SQL CREATE TABLE With Examples
19. How To Add Columns In SQL: A Step-By-Step Guide
20. Drop Column in SQL: Everything You Need to Know
21. Index in SQL
22. Constraints in SQL: A Complete Guide with Examples
23. Schema in SQL
24. Entity Relationship Diagram (ERD) - A Complete Overview
25. Foreign Key in SQL with Examples
26. An Ultimate Guide to Understand all About Composite Keys in SQL
27. Normalization in SQL
28. Better Data Management: The Efficiency of TRUNCATE in SQL
29. Difference Between DELETE and TRUNCATE in SQL
30. SQL ORDER BY
31. SQL Not Equal Operator
32. SQL Intersect Operator: A Comprehensive Guide
33. SQL Union: Explained with Examples
34. SQL Case Statement Explained with Examples
Now Reading
35. Unleashing the CONCAT Function In SQL: String Manipulation Made Easy
36. Understanding and Mastering COALESCE in SQL
37. NVL in SQL
38. Understanding SQL Date Formats and Functions
39. DateDiff in SQL: A Complete Guide in 2024
40. SQL Wildcards
41. SQL DISTINCT: A Comprehensive Guide
42. LIMIT in SQL: A Comprehensive Tutorial
43. SQL Aggregate Functions
44. GROUP BY in SQL
45. SQL HAVING
46. EXISTS in SQL
Structured Query Language, or SQL, is the main language used to communicate with databases in the field of database management. The SQL CASE statement, one of its many potent capabilities, gives SQL queries the ability to execute conditional logic. The syntax, use cases, and practical applications of the SQL CASE statement will all be covered in detail in this article.
As a conditional expression, the SQL CASE statement enables developers to carry out various operations in response to predefined circumstances. It works similarly to other programming languages' IF...ELSE statement. The SQL CASE statement has the following fundamental syntax:
SELECT column1, column2,... ,
CASE
WHEN condition THEN result
END AS alias_name
FROM table;
The CASE statement in this form assesses each condition one after the other. The matching result is returned if a condition evaluates to true. If none of the requirements are satisfied, the default outcome, if any, is given back.
Let’s break down the SQL Case statement syntax:
SELECT column1, column2,... ,
CASE
WHEN condition THEN result
END AS alias_name
FROM table;
The following are the parameters or parts of the CASE SQL statement:
Here is a sample from the sample database's ‘Customer’ table:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
The Output:
It is true that the SQL CASE statement, which is usually used in conjunction with SELECT queries to alter result sets, may also be used to filter data according to certain requirements in the WHERE clause. This feature gives developers a strong tool to create more complex and customized queries.
The SQL CASE statement functions similarly within the WHERE clause. However, it filters rows according to conditions instead of altering the obtained data.
To filter rows using a SQL CASE statement in the WHERE clause based on a specific condition, let's say we want to retrieve customers from India and Australia only, we can use the following code:
SELECT *
FROM Customer
WHERE Country IN (
SELECT CASE
WHEN Country = 'India' THEN 'India'
WHEN Country = 'Australia' THEN 'Australia'
ELSE ''
END
);
This query will select all rows from the 'Customer’ table where the country is either 'India' or 'Australia'. It utilizes a CASE statement within the WHERE clause to filter rows based on the specified conditions.
To filter rows using a SQL CASE statement in the WHERE clause based on multiple values, let's say we want to retrieve customers from India, Australia, and Sri Lanka, we can use the following code:
SELECT *
FROM Customer
WHERE Country IN (
SELECT CASE
WHEN Country = 'India' THEN 'India'
WHEN Country = 'Australia' THEN 'Australia'
WHEN Country = 'Sri Lanka' THEN 'Sri Lanka'
ELSE ''
END
);
This query will select all rows from the ‘Customer’ table where the country is 'India', 'Australia', or 'Sri Lanka'. It utilizes a CASE statement within the WHERE clause to filter rows based on the specified conditions with multiple values.
Developers can successfully manage complex cases by allowing for more sophisticated decision-making within queries, by adding numerous conditions to an SQL CASE statement. The adaptability and usefulness of a CASE statement are increased when numerous conditions are included in it. Examples of these uses include classifying data according to different criteria and creating conditional logic with multiple branches.
An SQL CASE statement with multiple conditions follows the same general structure as one with a single condition. Every condition is assessed one after the other, and when one evaluates to true, the associated result is given back. Here’s the syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
To filter rows using a SQL CASE statement in the WHERE clause with multiple conditions, let's say we want to retrieve customers aged 21 or younger from India and customers aged 22 or older from Australia. We can use the following code to obtain the result:
SELECT *
FROM Customer
WHERE CASE
WHEN Country = 'India' AND Age <= 21 THEN 1
WHEN Country = 'Australia' AND Age >= 22 THEN 1
ELSE 0
END = 1;
This query will select all rows from the ‘Customer’ table where the specified conditions are met: customers aged 21 or younger from India and customers aged 22 or older from Australia. It utilizes a CASE statement within the WHERE clause to filter rows based on multiple conditions.
Another common scenario is combining conditions within a single branch of the CASE statement. To filter rows using a SQL CASE statement in the WHERE clause by combining conditions, let's say we want to retrieve customers aged 21 or younger from India To obtain our result, we can use the following code:
SELECT *
FROM Customer
WHERE CASE
WHEN (Country = 'India' AND Age <= 21) OR (Country = 'Australia' AND Age >= 22) THEN 1
ELSE 0
END = 1;
This query will select all rows from the ‘Customer’ table where the specified conditions are met: customers aged 21 or younger from India and customers aged 22 or older from Australia. It utilizes a CASE statement within the WHERE clause to filter rows by combining multiple conditions.
Let's say, you have a dataset of customer transactions and you wish to divide up your clientele into groups according to the frequency and total amount of their purchases. To do this, you can use a SQL CASE statement with several conditions:
SELECT customer_id,
CASE
WHEN total_purchases < 100 AND purchase_frequency < 5 THEN 'Low-Spending, Infrequent'
WHEN total_purchases >= 100 AND purchase_frequency < 5 THEN 'High-Spending, Infrequent'
WHEN total_purchases < 100 AND purchase_frequency >= 5 THEN 'Low-Spending, Frequent'
WHEN total_purchases >= 100 AND purchase_frequency >= 5 THEN 'High-Spending, Frequent'
ELSE 'Other'
END AS customer_segment
FROM customers;
Output:
customer_id | customer_segment |
1 | Low-Spending, Infrequent |
2 | High-Spending, Infrequent |
3 | Low-Spending, Frequent |
4 | High-Spending, Frequent |
Customers are grouped in this scenario according to their overall purchase amount and the frequency of those purchases, which offers important insights into their purchasing habits.
Consider the ‘Customer’ Table, which includes the following fields: Phone, Age, Country, Last Name, CustomerID, and CustomerName. The SQL query that follows can be used to examine the data in the ‘Customer’ table:
Query:
SELECT CustomerName, Country
FROM Customer
ORDER BY
(CASE
WHEN Country IS 'India' THEN Country
ELSE Age
END);
Output:
With the help of the flexible SQL CASE statement, developers may incorporate conditional logic into SQL queries. Developers can build more effective and expressive SQL code by comprehending the syntax and many use cases of the SQL CASE statement, which can be applied to filtering or data manipulation. This article has offered a thorough tutorial for understanding the SQL CASE statement by integrating real-world examples. Begin utilizing its potential in your SQL queries right now!
FREQUENTLY ASKED QUESTIONS
1. What is the CASE statement in SQL for string?
Ans: The CASE statement in SQL for strings allows you to perform conditional logic based on string values. It evaluates a series of conditions and returns a result depending on which condition is true.
2. How do I run a query in a CASE statement in SQL?
Ans: To run a query using a CASE statement in SQL, you include the CASE statement within your SELECT query, specifying the conditions and corresponding results you want.
3. Can we write multiple conditions in a CASE statement in SQL?
Ans: Yes, you can write multiple conditions in a CASE statement in SQL by chaining together multiple WHEN clauses. Each WHEN clause represents a separate condition to evaluate.
4. How many types of CASE statements are there in SQL?
Ans: There are two types of CASE statements in SQL: simple CASE and searched CASE. Simple CASE compares an expression to a set of simple values, while searched CASE evaluates a set of Boolean conditions.
5. Can we use null in CASE statement SQL?
Ans: Yes, you can use NULL in a CASE statement in SQL. You can specify NULL as a condition or as a result value in a CASE statement.
6. How do you write two CASE statements in SQL?
Ans: To write two CASE statements in SQL, you include them within your SELECT query, each with its own set of conditions and results.
7. Is a CASE statement a SELECT query?
Ans: No, a CASE statement is not a SELECT query by itself. It is a conditional expression that can be used within a SELECT query to determine the value of a column or expression based on specified conditions.
8. Can you use it in a CASE statement?
Ans: Yes, you can use a CASE statement within another CASE statement in SQL, allowing for nested conditional logic if needed.
9. What are the limitations of CASE statements in SQL?
Ans: The limitations of CASE statements in SQL include their inability to perform complex procedural logic, such as loops or variable assignments. Additionally, CASE statements can become unwieldy and difficult to read if they contain too many conditions.
10. Can we use aggregate functions in CASE statements in SQL?
Ans: Yes, you can use aggregate functions within CASE statements in SQL. This allows you to perform conditional aggregation based on specified conditions. For example, you can use SUM, COUNT, AVG, etc., within a CASE statement to aggregate data conditionally.
Rohan Vats
Software Engineering Manager
Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...