Start learning free

LESSON 61 OF 173 · BACKEND: SQL

CASE: Labels from Values in TypeScript

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:

const query: string = [
  "SELECT name,",
    "CASE",
      "WHEN stock = 0 THEN 'sold out'",
      "ELSE 'in stock'",
    "END AS availability",
  "FROM products",
].join(" ");

CASE checks the rules from the top and stops at the first one that is true, like an if … else if chain in TypeScript. 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, inside the TypeScript string's double quotes, and ORDER BY comes after FROM.


STEP 1 OF 7
    Ctrl + Enter to check

    Sql Case in TypeScript

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