DSA Factory
Free SQL queries lessonsSQL queries · Stage 1 · Shaping the results · Step 4

Compute new columns

Calculate values in SELECT and label rows with CASE WHEN. About 9 minutes.

SELECT can calculate

A column in SELECT doesn't have to be a stored column. It can be a calculation on columns: price times quantity, a mark out of 100, or a name plus a city. Give the result a name with AS so you can read it.

The calculation is done for every row, and nothing in the table changes. One trap: dividing two whole numbers gives a whole number in SQLite, so 7 / 2 is 3. Multiply by 1.0 first, or divide by a decimal.

7 / 2: is 3 when both are integers.
In code
SELECT item,
       price * qty AS total,
       round(price * 1.0 / qty, 2) AS each
FROM orders;

CASE WHEN labels rows

CASE WHEN is SQL's if / else. Give it a list of tests in order; the first one that is true decides the answer for that row. ELSE covers everything left, and without it the leftovers become NULL.

Write the strictest test first, because once a row matches, the rest are skipped.

CASE WHEN: first true test wins. ELSE is the rest.
In code
CASE WHEN score >= 90 THEN 'A'
     WHEN score >= 75 THEN 'B'
     ELSE 'C'
END AS grade
A grade for each score band
marks
studentscore
Kabir92
Isha78
Dev55
Mira90

92 is at least 90: the first test is true, grade A.

Move 1 of 4
Quick check

In SQLite, what does SELECT 7 / 2 return?

  1. A3
  2. B3.5
  3. C4
Show the answer

3. Both are integers, so the division is integer division and drops the fraction.

Your problem

Report card

The marks table has one row per student per subject. Show the student, the subject and a grade column that is Distinction for a score of 75 or more, Pass for 40 to 74, and Fail below 40. Order by student, then subject.

Tables
marks(id, student, subject, score)

Up to 2,000 rows

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve