Control statements form the heart of most languages since they control the execution of other sets of statements. These are also found in SQL and should be exploited for uses such as query filtering and query optimization by carefully selecting tuples that match our requirements.
In this article, we explore the Case-Switch statement in SQL. The CASE statement is SQL’s way of handling if/then logic.
There can be two valid ways of going about the case-switch statements.
The first takes a variable called case_value and matches it with some statement_list.
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] …
The second considers a search_condition instead of variable equality and executes the statement_list accordingly.
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] …
Below is a selection from the “Customer” table in the sample database:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
-- 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');
Adding Multiple Conditions to a CASE statement
By adding multiple conditions in SQL
SELECT CustomerName, Age,
WHEN Age> 22 THEN 'The Age is greater than 22'
WHEN Age = 21 THEN 'The Age is 21'
ELSE 'The Age is over 30'
END AS QuantityText
CASE Statement With ORDER BY Clause
Let’s take the Customer Table which contains CustomerID, CustomerName, LastName, Country, Age, and Phone. We can check the data of the Customer table by using the following query in SQL:
By using Order by Clause in SQL
SELECT CustomerName, Country
WHEN Country IS 'India' THEN Country
Some important points about CASE statements
- There should always be a SELECT in the case statement.
- END ELSE is an optional component but WHEN THEN these cases must be included in the CASE statement.
- We can make any conditional statement using any conditional operator (like WHERE ) between WHEN and THEN. This includes stringing together multiple conditional statements using AND and OR.
- We can include multiple WHEN statements and an ELSE statement to counter with unaddressed conditions.
Unlock the Power of Placement Preparation!
Feeling lost in OS, DBMS, CN, SQL, and DSA chaos? Our Complete Interview Preparation
Course is the ultimate guide to conquer placements. Trusted by over 100,000+ geeks, this course is your roadmap to interview triumph.
Ready to dive in? Explore our Free Demo Content and join our Complete Interview Preparation