Bird
Raised Fist0
SQLquery~20 mins

CASE in ORDER BY in SQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CASE in ORDER BY Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of CASE in ORDER BY with simple conditions
Consider a table Employees with columns id, name, and department. What is the output order of names after running this query?

SELECT name, department FROM Employees ORDER BY CASE department WHEN 'HR' THEN 1 WHEN 'Sales' THEN 2 ELSE 3 END;
SQL
CREATE TABLE Employees (id INT, name VARCHAR(20), department VARCHAR(20));
INSERT INTO Employees VALUES (1, 'Alice', 'Sales'), (2, 'Bob', 'HR'), (3, 'Charlie', 'Engineering'), (4, 'Diana', 'Sales'), (5, 'Eve', 'HR');

SELECT name, department FROM Employees ORDER BY CASE department WHEN 'HR' THEN 1 WHEN 'Sales' THEN 2 ELSE 3 END;
A[('Bob', 'HR'), ('Alice', 'Sales'), ('Diana', 'Sales'), ('Eve', 'HR'), ('Charlie', 'Engineering')]
B[('Alice', 'Sales'), ('Diana', 'Sales'), ('Bob', 'HR'), ('Eve', 'HR'), ('Charlie', 'Engineering')]
C[('Charlie', 'Engineering'), ('Bob', 'HR'), ('Eve', 'HR'), ('Alice', 'Sales'), ('Diana', 'Sales')]
D[('Bob', 'HR'), ('Eve', 'HR'), ('Alice', 'Sales'), ('Diana', 'Sales'), ('Charlie', 'Engineering')]
Attempts:
2 left
💡 Hint
Think about how the CASE expression assigns numeric values to departments for sorting.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in CASE used in ORDER BY
Which option contains a syntax error when using CASE in ORDER BY clause?
SQL
SELECT id, name FROM Employees ORDER BY CASE WHEN department = 'HR' THEN 1 ELSE 2 END;
AORDER BY CASE WHEN department = 'HR' THEN 1 ELSE END
BORDER BY CASE department WHEN 'HR' THEN 1 ELSE 2 END
CORDER BY CASE WHEN department = 'HR' THEN 1 ELSE 2 END
DORDER BY CASE department WHEN 'HR' THEN 1 ELSE 2 END ASC
Attempts:
2 left
💡 Hint
Look for incomplete CASE expressions.
❓ optimization
advanced
2:00remaining
Optimizing ORDER BY CASE for performance
Given a large table Orders with a status column having values 'Pending', 'Shipped', 'Cancelled', which ORDER BY clause is most efficient to sort rows with 'Pending' first, then 'Shipped', then 'Cancelled'?
AORDER BY CASE status WHEN 'Pending' THEN 1 WHEN 'Shipped' THEN 2 ELSE 3 END
BORDER BY status = 'Pending' DESC, status = 'Shipped' DESC, status = 'Cancelled' DESC
CORDER BY FIELD(status, 'Pending', 'Shipped', 'Cancelled')
DORDER BY CASE WHEN status = 'Pending' THEN 1 WHEN status = 'Shipped' THEN 2 ELSE 3 END
Attempts:
2 left
💡 Hint
Consider built-in functions optimized for sorting by specific values.
❓ query_result
advanced
2:00remaining
Result of ORDER BY CASE with multiple conditions
Given a table Products with columns id, category, and price, what is the order of id after running this query?

SELECT id FROM Products ORDER BY CASE WHEN category = 'Electronics' AND price > 1000 THEN 1 WHEN category = 'Electronics' THEN 2 ELSE 3 END, price DESC;
SQL
CREATE TABLE Products (id INT, category VARCHAR(20), price INT);
INSERT INTO Products VALUES (1, 'Electronics', 1500), (2, 'Electronics', 800), (3, 'Clothing', 500), (4, 'Electronics', 1200), (5, 'Clothing', 700);

SELECT id FROM Products ORDER BY CASE WHEN category = 'Electronics' AND price > 1000 THEN 1 WHEN category = 'Electronics' THEN 2 ELSE 3 END, price DESC;
A[1, 4, 2, 5, 3]
B[4, 1, 2, 3, 5]
C[2, 1, 4, 3, 5]
D[1, 4, 2, 3, 5]
Attempts:
2 left
💡 Hint
First order by CASE result, then by price descending within groups.
🔧 Debug
expert
3:00remaining
Debug unexpected ORDER BY CASE behavior
A developer wrote this query to order customers by priority:

SELECT customer_id, priority FROM Customers ORDER BY CASE priority WHEN 'High' THEN 1 WHEN 'Medium' THEN 2 ELSE 3 END DESC;

But the results show 'Low' priority customers first. What is the cause?
AThe CASE expression is missing ELSE clause causing NULLs to be sorted first.
BThe DESC applies to the entire CASE result, reversing the order so 3 comes first, showing 'Low' priority first.
CThe priority column has trailing spaces causing CASE to fail matching values.
DThe query needs GROUP BY to order correctly by priority.
Attempts:
2 left
💡 Hint
Think about how DESC affects numeric values from CASE.

Practice

(1/5)
1. What does the CASE statement do when used inside an ORDER BY clause in SQL?
easy
A. It filters rows before sorting them.
B. It allows sorting rows based on custom conditions you define.
C. It changes the data type of the sorted column.
D. It groups rows before sorting.

Solution

  1. Step 1: Understand the role of CASE in ORDER BY

    The CASE statement inside ORDER BY assigns sorting values conditionally to each row.
  2. Step 2: Differentiate from filtering or grouping

    CASE does not filter or group rows; it only affects sorting order.
  3. Final Answer:

    It allows sorting rows based on custom conditions you define. -> Option B
  4. Quick Check:

    CASE in ORDER BY = custom sorting [OK]
Hint: CASE in ORDER BY controls sorting order by conditions [OK]
Common Mistakes:
  • Thinking CASE filters rows
  • Assuming CASE changes data types
  • Confusing CASE with GROUP BY
2. Which of the following is the correct syntax to use CASE inside an ORDER BY clause?
easy
A. ORDER BY CASE WHEN condition THEN value ELSE value END
B. ORDER BY IF condition THEN value ELSE value END
C. ORDER BY SWITCH condition THEN value ELSE value END
D. ORDER BY SELECT CASE condition THEN value ELSE value END

Solution

  1. Step 1: Recall correct CASE syntax in ORDER BY

    The correct syntax uses CASE WHEN ... THEN ... ELSE ... END without extra keywords.
  2. Step 2: Identify incorrect keywords

    Options A, B, and C use invalid keywords like SELECT, IF, or SWITCH which are not valid in ORDER BY CASE.
  3. Final Answer:

    ORDER BY CASE WHEN condition THEN value ELSE value END -> Option A
  4. Quick Check:

    CASE syntax = WHEN THEN ELSE END [OK]
Hint: Use CASE WHEN ... THEN ... ELSE ... END in ORDER BY [OK]
Common Mistakes:
  • Using IF instead of CASE
  • Adding SELECT inside ORDER BY
  • Using SWITCH keyword
3. Given the table Tasks with column priority having values 'High', 'Medium', 'Low', what will the query below return?

SELECT priority FROM Tasks ORDER BY CASE priority WHEN 'High' THEN 1 WHEN 'Medium' THEN 2 ELSE 3 END;
medium
A. Rows sorted with 'High' first, then 'Medium', then 'Low'.
B. Rows sorted alphabetically by priority.
C. Rows sorted with 'Low' first, then 'Medium', then 'High'.
D. Syntax error due to CASE in ORDER BY.

Solution

  1. Step 1: Understand CASE assigns sorting values

    CASE assigns 1 to 'High', 2 to 'Medium', and 3 to others (like 'Low').
  2. Step 2: ORDER BY sorts ascending by these values

    Rows with priority 'High' come first, then 'Medium', then 'Low'.
  3. Final Answer:

    Rows sorted with 'High' first, then 'Medium', then 'Low'. -> Option A
  4. Quick Check:

    CASE assigns order numbers = sorted by priority [OK]
Hint: CASE assigns numbers to priorities to sort custom order [OK]
Common Mistakes:
  • Assuming alphabetical sort
  • Thinking CASE causes syntax error
  • Confusing order direction
4. Identify the error in this SQL query:

SELECT name FROM Employees ORDER BY CASE WHEN department = 'Sales' THEN 1 WHEN department = 'HR' THEN 2 ELSE 3;
medium
A. ORDER BY cannot use CASE statements.
B. Incorrect use of ELSE in CASE.
C. Missing END keyword to close CASE statement.
D. Missing THEN keyword after conditions.

Solution

  1. Step 1: Check CASE syntax completeness

    The CASE statement must end with the keyword END to close it.
  2. Step 2: Identify missing END keyword

    The query lacks END after ELSE 3, causing syntax error.
  3. Final Answer:

    Missing END keyword to close CASE statement. -> Option C
  4. Quick Check:

    CASE must end with END [OK]
Hint: Always close CASE with END keyword [OK]
Common Mistakes:
  • Omitting END keyword
  • Misplacing ELSE clause
  • Thinking CASE not allowed in ORDER BY
5. You want to sort products so that 'Electronics' appear first, 'Clothing' second, and all others last. Which ORDER BY clause using CASE achieves this?
hard
A. ORDER BY CASE category WHEN 'Clothing' THEN 1 WHEN 'Electronics' THEN 2 ELSE 3 END
B. ORDER BY CASE WHEN category = 'Electronics' THEN 3 WHEN category = 'Clothing' THEN 2 ELSE 1 END
C. ORDER BY category = 'Electronics' DESC, category = 'Clothing' DESC
D. ORDER BY CASE category WHEN 'Electronics' THEN 1 WHEN 'Clothing' THEN 2 ELSE 3 END

Solution

  1. Step 1: Assign lowest number to 'Electronics' for first position

    ORDER BY CASE category WHEN 'Electronics' THEN 1 WHEN 'Clothing' THEN 2 ELSE 3 END assigns 1 to 'Electronics', 2 to 'Clothing', and 3 to others, sorting correctly.
  2. Step 2: Check other options for order correctness

    ORDER BY CASE WHEN category = 'Electronics' THEN 3 WHEN category = 'Clothing' THEN 2 ELSE 1 END reverses order numbers, ORDER BY CASE category WHEN 'Clothing' THEN 1 WHEN 'Electronics' THEN 2 ELSE 3 END swaps categories, ORDER BY category = 'Electronics' DESC, category = 'Clothing' DESC uses boolean sorting which may not guarantee order.
  3. Final Answer:

    ORDER BY CASE category WHEN 'Electronics' THEN 1 WHEN 'Clothing' THEN 2 ELSE 3 END -> Option D
  4. Quick Check:

    Lowest number = highest priority in CASE [OK]
Hint: Assign 1 to highest priority category in CASE [OK]
Common Mistakes:
  • Swapping priority numbers
  • Using boolean expressions without CASE
  • Forgetting ELSE clause
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard