Bird
Raised Fist0
SQLquery~10 mins

CASE in ORDER BY in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - CASE in ORDER BY
Start Query Execution
↓
Evaluate CASE in ORDER BY
↓
Assign Sort Value per Row
↓
Sort Rows by Assigned Values
↓
Return Sorted Result Set
↓
End
The database evaluates the CASE expression for each row in ORDER BY, assigns a sort value, then sorts rows accordingly before returning the result.
Execution Sample
SQL
SELECT name, score
FROM students
ORDER BY CASE
  WHEN score >= 90 THEN 1
  WHEN score >= 75 THEN 2
  ELSE 3
END;
This query sorts students by score groups: highest scores first, then medium, then others.
Execution Table
StepRow (name, score)CASE EvaluationSort ValueAction
1(Alice, 92)score >= 90 is TRUE1Assign sort value 1
2(Bob, 85)score >= 90 is FALSE; score >= 75 is TRUE2Assign sort value 2
3(Charlie, 70)score >= 90 is FALSE; score >= 75 is FALSE3Assign sort value 3
4(Diana, 95)score >= 90 is TRUE1Assign sort value 1
5(Evan, 60)score >= 90 is FALSE; score >= 75 is FALSE3Assign sort value 3
6Sort all rows by sort value ascendingRows ordered: Alice, Diana, Bob, Charlie, Evan
7Return sorted result setQuery ends
💡 All rows assigned sort values; sorting complete; query returns ordered rows.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
sort_value (per row)N/A1 (Alice)2 (Bob)3 (Charlie)1 (Diana)3 (Evan)All assigned
Key Moments - 2 Insights
Why does the CASE expression assign numbers like 1, 2, 3 in ORDER BY?
The CASE assigns numeric values to group rows for sorting priority. Lower numbers sort first. See execution_table rows 1-5 where each row gets a sort value.
What happens if multiple rows get the same sort value?
Rows with the same sort value keep their relative order or can be further sorted by other criteria. In the example, Alice and Diana both get 1 and appear first.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what sort value is assigned to Charlie?
A1
B2
C3
D0
💡 Hint
Check the 'Sort Value' column for step 3 in execution_table.
At which step does the query start sorting all rows by their assigned sort values?
AStep 6
BStep 4
CStep 2
DStep 7
💡 Hint
Look for the step describing sorting action in execution_table.
If we changed the CASE to assign 3 for score >= 90 and 1 for others, which rows would appear first?
AAlice and Diana
BCharlie and Evan
CBob only
DNo change
💡 Hint
Refer to how sort values determine order in variable_tracker and execution_table.
Concept Snapshot
CASE in ORDER BY lets you sort rows by custom conditions.
Syntax: ORDER BY CASE WHEN condition THEN value ELSE value END
Rows get sort values from CASE.
Lower values sort first.
Useful for grouping or custom priority sorting.
Full Transcript
This visual execution shows how SQL uses CASE in ORDER BY to sort rows. Each row is checked against CASE conditions, which assign a numeric sort value. Rows are then sorted by these values, with lower numbers appearing first. For example, students with scores 90 or above get sort value 1, so they appear first. This method helps group and order data flexibly. The execution table traces each row's CASE evaluation and assigned sort value, then the sorting step. Variable tracking shows how sort values change per row. Key moments clarify why numeric values are used and what happens with ties. The quiz tests understanding of sort values and sorting steps. The snapshot summarizes how CASE in ORDER BY works for custom sorting.

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