Start learning free

LESSON 61 OF 188 · BACKEND: SQL

CASE: Labels from Values in Python

Practice

Sometimes you want a word instead of a number: a label worked out from a value. SQL does this with a CASE expression. It lists rules of the form WHEN condition THEN value and ends with END; AS names the new column. For example, a label from the stock:

query = (
    "SELECT name, "
        "CASE "
            "WHEN stock = 0 THEN 'sold out' "
            "ELSE 'in stock' "
        "END AS availability "
    "FROM products "
)

CASE checks the rules from the top and stops at the first one that is true. ELSE gives the value for every row no rule matched; without it, those rows get NULL.

The check runs show(db, query), which must print:

name | price | price_band
Pen | 2 | cheap
Notebook | 7 | regular
Stapler | 9 | regular
Mug | 12 | regular
Plant | 15 | regular
Teapot | 22 | premium
Lamp | 29 | premium
Gift card | 50 | premium
(8 rows)

Your task: write query so it lists each product's name and price with a third column, price_band: 'cheap' under 5, 'regular' under 20 and 'premium' for the rest, cheapest first.


Assignment
Follow the Coding Tutorial to grow the CASE one rule at a time, then sort the rows by price.


Hint
Put the rule for under 5 before the rule for under 20: the first true rule wins. Text values go in single quotes, and ORDER BY comes after FROM.


STEP 1 OF 7
    Ctrl + Enter to check

    Sql Case in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free