The Wayback Machine - https://web.archive.org/web/20250306102537/https://www.geeksforgeeks.org/sql-case-statement/
Open In App

SQL CASE Statement

Last Updated : 10 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The CASE statement in SQL is a versatile conditional expression that enables us to incorporate conditional logic directly within our queries. It allows you to return specific results based on certain conditions, enabling dynamic query outputs. Whether you need to create new columns, modify existing ones, or customize the output of your queries, the CASE statement can handle it all.

In this article, we’ll learn the SQL CASE statement in detail, with clear examples and use cases that show how to leverage this feature to improve your SQL queries.

CASE Statement in SQL

  • The CASE statement in SQL is a conditional expression that allows you to perform conditional logic within a query.
  • It is commonly used to create new columns based on conditional logic, provide custom values, or control query outputs based on certain conditions.
  • If no condition is true then the ELSE part will be executed. If there is no ELSE part then it returns NULL.

Syntax:

To use CASE Statement in SQL, use the following syntax:

CASE case_value
WHEN condition THEN result1
WHEN condition THEN result2
…
Else result
END CASE;

Example of SQL CASE Statement

Let’s look at some examples of the CASE statement in SQL to understand it better.

Let’s create a demo SQL table, which will be used in examples.

Demo SQL Database

We will be using this sample SQL table for our examples on SQL CASE statement:

CustomerID CustomerName LastName Country Age Phone
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

You can create the same Database in your system, by writing the following MySQL query:

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');

Example 1: Simple CASE Expression

In this example, we use CASE statement

Query:

SELECT CustomerName, Age,
CASE
    WHEN Country = "India" THEN 'Indian'
    ELSE 'Foreign'
END AS Nationality
FROM Customer;

Output:

CustomerName Age Nationality
Shubham 23 Indian
Aman 21 Foreign
Naveen 24 Foreign
Aditya 21 Foreign
Nishant. Salchichas S.A. 22 Foreign

Example 2: SQL CASE When Multiple Conditions

We can add multiple conditions in the CASE statement by using multiple WHEN clauses.

Query:

SELECT CustomerName, Age,
CASE
    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
FROM Customer;

Output:

CustomerName Age QuantityText
Shubham 23 The Age is greater than 22
Aman 21 The Age is 21
Naveen 24 The Age is greater than 22
Aditya 21 The Age is 21
Nishant. Salchichas S.A. 22 The Age is over 30

Example 3: 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 ORDER BY clause with the CASE statement.

Query:

SELECT CustomerName, Country
FROM Customer
ORDER BY
(CASE
    WHEN Country  IS 'India' THEN Country
    ELSE Age
END);

Output:

CustomerName Country
Aman Australia
Aditya Austria
Nishant. Salchichas S.A. Spain
Naveen Sri lanka
Shubham India

Important Points About CASE Statement

  • The SQL CASE statement is a conditional expression that allows for the execution of different queries based on specified conditions.
  • 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.

Conclusion

The CASE statement provides a robust mechanism for incorporating conditional logic in SQL queries. By using this statement, you can handle various conditions and customize the output of your queries effectively. Understanding how to implement CASE expressions allows you to perform more sophisticated data manipulation and reporting, making your SQL queries more dynamic and responsive to different scenarios.

FAQs

What is a CASE statement in SQL?

The CASE statement in SQL is a conditional expression that allows you to execute different logic based on certain conditions within a query. It is used to create new columns, customize values, or modify query outputs depending on specified criteria.

How to write a CASE statement?

To write a CASE statement, you need to specify conditions and corresponding results. You define different outcomes based on whether the conditions are met or not, with an optional default result if none of the conditions are true.

How to write a CASE statement in SQL with one condition?

To write a CASE statement with a single condition, you specify the condition to evaluate and provide the result if the condition is true. You can also include an alternative result if the condition is not met.


Get IBM Certification and a 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

Master Data Analysis using Excel, SQL, Python & PowerBI with this complete program and also get a 90% refund. What more motivation do you need? Start the challenge right away!


Next Article

Similar Reads

PL/SQL CASE Statement
PL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases it extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. The PL/SQL CASE statement is a powerful conditional control structure in Oracle database
4 min read
What is the CASE statement in SQL Server with or condition?
In SQL Server, the CASE statement cannot directly support the use of logical operators like OR with its structure. Instead of CASE it operates based on the evaluation of multiple conditions using the WHEN keyword followed by specific conditions. In this article, we will learn about the OR is not supported with CASE Statement in SQL Server with a de
4 min read
PostgreSQL - CASE Statement
In PostgreSQL, CASE statements provide a way to implement conditional logic within SQL queries. Using these statements effectively can help streamline database functions, optimize query performance, and provide targeted outputs. This guide will break down the types of CASE statements available in PostgreSQL, with detailed examples and explanations.
4 min read
How to do Case Sensitive and Case Insensitive Search in a Column in MySQL
LIKE Clause is used to perform case-insensitive searches in a column in MySQL and the COLLATE clause is used to perform case-sensitive searches in a column in MySQL. Learning both these techniques is important to understand search operations in MySQL. Case sensitivity can affect search queries in MySQL so knowing when to perform a specific type of
4 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
SQL | INSERT IGNORE Statement
We know that a primary key of a table cannot be duplicated. For instance, the roll number of a student in the student table must always be distinct. Similarly, the EmployeeID is expected to be unique in an employee table. When we try to insert a tuple into a table where the primary key is repeated, it results in an error. However, with the INSERT I
2 min read
Reverse Statement Word by Word in SQL server
To reverse any statement Word by Word in SQL server we could use the SUBSTRING function which allows us to extract and display the part of a string. Pre-requisite :SUBSTRING function Approach : Declared three variables (@Input, @Output, @Length) using the DECLARE statement. Use the WHILE Loop to iterate every character present in the @Input. For th
2 min read
SQL USE Database Statement
SQL(Structured Query Language) is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. It is flexible and user-friendly. In SQL, to interact with the database, the users have to type queries that have certain syntax, and use command is one of them. The use command is
2 min read
SQL Statement to Remove Part of a String
Here we will see SQL statements to remove part of the string.Method 1: Using SUBSTRING() and LEN() functionWe will use this method if we want to remove a part of the string whose position is known to us.1. SUBSTRING(): This function is used to find a sub-string from the string from the given position. It takes three parameters:  String: It is a req
4 min read