SQL CASE Statement

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
By Srikanth Varma
Free
star5
Enrolled: 1000
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
Srikanth Varma
Free
5
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

Sometimes, a situation may arise when adding data to a particular cell depends on a condition based on another column. For example, we need to calculate the students' grades based on their marks. Grades and marks will be two different columns in a table, and we will use the marks column to calculate the values of the grades column. In these scenarios, we use the case statement. The case statement in SQL will add the value only when the given condition based on some other cell is true.

What is CASE Statement in SQL?

The Case Statement in SQL returns a value when some condition is specified. This condition will be based on some other cell in the same table.

As in the if-else statement, several conditions are applied, and whichever first gives the result as true is executed. The case statement in SQL also works similarly. The conditions are specified using WHEN and THEN keywords. You can specify as many conditions using these keywords.

However, the CASE, WHEN, THEN, and END keywords are necessary while writing a case statement in SQL. The CASE keyword is used to specify the beginning of the case statement, whereas the END keyword specifies the end of the case statement and the end of the conditions. We can also write an ELSE keyword that would execute when all other conditions specified in the case statement return false.

The END keyword is followed by an alias_name, which is the column name you are adding to the table based on the conditions.

SQL CASE Syntax

The syntax of the Case Statement in SQL is as follows:

However, you can also write the syntax of the case statement in another way. This syntax adds an expression after the CASE statement that is compared with every value specified after the WHEN keyword.

In the former syntax, the entire condition to be checked is written after the CASE statement, and based on it, the data is added to the cells. However, in the latter syntax, the expression and the values to be compared are written separately. We don't need to write the entire condition again and again in each line.

It can be written as :

SQL CASE Parameters

ParametersExplanation
condition1, condition2,.., conditionNThese are the conditions based on which the values are added in the table column or on a particular cell.
output1, output2,.., outputNThese are the results that are to be added to the table column or the particular cell when their corresponding condition is true.
outputIt is the output that will be executed only if all the other conditions are false.
expressionIt is the expression that will be used to compare with all other values written after the WHEN keyword.
value1,value2,..valueNThese are the values that are to be compared with the expression written after the CASE keyword. It is based on these comparisons, the outputs written after the THEN keyword will be executed.

Note:

  1. In the first syntax, the entire condition to be compared is written after the WHEN keyword. Based on these conditions, it will add the outputs. The second syntax will compare the expression with each of the values written after the WHEN statements. After that, the respective outputs will be added if true.
  2. When all the conditions are false, only then the output written after the ELSE keyword will be executed.
  3. However, the ELSE keyword is optional in the syntax. If all the conditions are false and there is no ELSE keyword then it will return null.
  4. It is a must to write the END keyword signifying the end of the case statement.
  5. The conditions will be checked in sequential order, and if a condition is true, then all the other conditions following it will not be checked.

SQL CASE Examples

Example : 1

Let us say we have a table student in which the students' id, Name, and marks are stored.

idNameMarks
1Tarush89
2Amit54
3Ankush94
4Atul31
5Aditya67

Now, we have to add one more column containing each student's grade.

Therefore, we will execute the query:

Output:

idNameMarksGrade
1Tarush82B
2Amit54C
3Ankush94A
4Atul31F
5Aditya67C

The output contains a table with the grade column added to it after comparing each student's marks with the given conditions specified in the query executed.


Example : 2

Now, let us see another example with a different syntax :

Consider a table student:

idNameMarksGrade
1Tarush82B
2Amit54C
3Ankush94A
4Atul31F
5Aditya67C

We will now add a Remarks column in the student table based on the students' Grades. Therefore, to achieve this, we have to execute the query :

Output:

idNameMarksGradeRemarks
1Tarush82BGood
2Amit54CImprove more
3Ankush94AExcellent
4Atul31FWork Hard
5Aditya67CImprove more

The above query compares the grade values and accordingly adds the items in the Remarks column.

Various Formats of SQL CASE Statement

1. Case Statement with Order by Clause

We can also use the ORDER BY clause with the case statement. In SQL, the ORDER BY clause is used to sort the results in an ascending or descending order.

Let us see an example to understand it better.

We will take a table named EmployeeDetails which is shown below :

IdNameAgeGender
2019Raman32M
2013Rita38F
2014Saloni18F
2012Prakhar23M
2011Rohan42M

In the above table, we will sort the rows by their ages, in which the ages of the female employees will be sorted in ascending order. In contrast, the ages of the male employees will be sorted in descending order using the case statement.

We will execute the following query to perform the above task:

Output:

IdNameAgeGender
5Rohan48M
1Raman32M
4Prakhar23M
3Saloni18F
2Rita38F

As you can see in the above output, the ages of the male employees are sorted in descending order, whereas the ages of the female employees are sorted in ascending order.

2. Case Statement in SQL with Group by Clause

We can also use the GROUP BY clause with the case statement. However, as we know, we use the GROUP CLAUSE to group the rows of a table. This clause is often used with the aggregate functions such as count(), sum(), min(), max(), etc for performing certain calculations.

Lets us understand with an example how we will use the GROUP BY clause with the CASE statement.

We have a table named People in which there are records of some people around the world with their ages and eligibility to vote. We have to calculate the total number of citizens eligible to vote and the total number of citizens not eligible to vote.

The table is as shown below.

IDNameAgeVoting
1Rajiv42Eligible
2Ruhi16Not Eligible
3Rakesh21Eligible
4Daman32Eligible
5Ankit17Not Eligible

Now, we have to group the citizens to have the count of the eligible and the non-eligible voters.

We will be executing the following query to get our desired result.

Output:

VOTEcount(*)
Eligible3
Not Eligible2

3. Update Statement with a CASE Statement

In SQL, the UPDATE statement is used to update or change the existing records in the table. However, sometimes we only need to change some cells based on some condition. In such situations, we can use the CASE statement along with the UPDATE statement.

Lets us see it with an example.

We have a table named People, which is shown below.

NameStateCity
RoliUPLucknow
RaginiUKDehradun
RajatMPGwalior

We have to update the values in column State such that the value should not be an abbreviation of the state name but instead should store the full name of the state.

Therefore, we execute the following query:

Output:

NameStateCity
RoliUttar PradeshLucknow
RoliUttarakhandDehradun
RoliMadhya PradeshGwalior

As shown above, all the state names are updated to their full form.

4. Insert Statement with a CASE Statement

We can also use the CASE statement with the INSERT statement to insert data into the table. In SQL, the INSERT statement is used to insert records without any condition. However, we use the insert and the case statements together if you want to insert data based on a certain condition.

Let us understand it with an example:

We have a table named Example1 in which there are three columns: id, Name, and the State to which they belong.

The table is as follows:

idNameState
101RoliUP
102RajatTN
103RaviMP

Now we will insert the records of the columns Name and Stateinto another table using the CASE Statement.

We will execute the following query to understand it more:

Output:

NameState
RoliUttar Pradesh
RajatTamil Nadu
RaviMadhya Pradesh

Using the above query, we are inserting the values of the Name and State columns from the table Example1 to Example2. Here we are using the conditions that the abbreviations used in Example1 should be written in their corresponding full forms.

SQL CASE Statement Limitations

  1. We have multiple conditions in a CASE statement, but as it works sequentially if a condition is found true, then all other conditions after it will not even be checked.
  2. We cannot check NULL values in a table using a CASE statement.
  3. A CASE statement cannot be used to control the execution flow of a user-defined function.

Conclusion

  • CASE Statement checks several conditions to insert data into a table. It works just like an if-else statement in other programming languages.
  • Its syntax consists of the WHEN keyword followed by the condition according to which the data has to be inserted and a THEN keyword followed by the data that has to be inserted.
  • It also consists of an ELSE keyword which is executed when all other conditions are false. However, the ELSE keyword is optional. If all other conditions are false and there is no ELSE keyword then it returns a NULL value.
  • The END keyword is used to specify the end of the CASE statement.
  • The CASE Statement can also be used with the INSERT, UPDATE Statements, and the ORDER BY and GROUP BY clauses.