SQL Case Cheat Sheet in Common Concepts

CASE Clause

SQL provides CASE clause to perform conditional operations. This is similar to the switch case / if-else conditions in other programming languages.

Let's learn more about the usage of CASE clause using the given database

Database The IMDb dataset which consists of movies, actors and cast. You can refer to the database in the code playground for a better understanding.

CASE Clause

Each condition in the

CASE
clause is evaluated and results in corresponding value when the first condition is met.

Syntax

SELECT c1, c2
CASE
    WHEN condition1 THEN value1
    WHEN condition2 THEN value2
    ...
    ELSE value
    END AS cn
FROM table;
Note
  1. In CASE clause, if no condition is satisfied, it returns the value in the ELSE part. If we do not specify the ELSE part,

    CASE clause
    results in NULL

  2. We can use CASE in various clauses like SELECT, WHERE, HAVING, ORDER BY and GROUP BY.

Example

Calculate the tax amount for all movies based on the profit. Check the following table for tax percentages.

profittax_percentage
<=100 crores10% of profit
100< <=500 crores15% of profit
> 500 crores18% of profit

SELECT id, name,
  CASE
    WHEN collection_in_cr - budget_in_cr <= 100 THEN collection_in_cr - budget_in_cr * 0.1
    WHEN (collection_in_cr - budget_in_cr > 100
    AND collection_in_cr - budget_in_cr < 500) THEN collection_in_cr - budget_in_cr * 0.15
    ELSE collection_in_cr - budget_in_cr * 0.18
  END AS tax_amount
FROM
  movie;
Output
idnametax_amount
1The Matrix45.8
2Inception82.08
3The Dark Knight98.7
.........

Try it Yourself

Question 1

Categorise movies as following.

ratingcategory
< 5Poor
5 <= _ <= 7Average
7 <Good

CASE with Aggregates

CASE statements can also be used together with aggregate functions

Example

  • Get the number of movies with rating greater than or equal to 8, and the movies with rating less than 8, and are released between 2015 and 2020.

SELECT
  count(
    CASE
      WHEN rating >= 8 THEN 1
    END
  ) AS above_eight,
  count(
    CASE
      WHEN rating < 8 THEN 1
    END
  ) AS below_eight
FROM
  movie
WHERE
  CAST(strftime("%Y", release_date) AS INTEGER) BETWEEN 2015
  AND 2020;
Output
above_eightbelow_eight
42

Try it Yourself!

  • Get the number of movies with collection greater than or equal to 100 crores, and the movies with collection less than 100 crores.
Output
above_100_crbelow_100_cr
137






Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form