Start learning free

LESSON 61 OF 173 · BACKEND: SQL

CASE: Labels from Values in Java

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:

String query = "";
query += "SELECT name, ";
query += "CASE ";
query += "WHEN stock = 0 THEN 'sold out' ";
query += "ELSE 'in stock' ";
query += "END AS availability ";
query += "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: build 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, each piece added to query with +=, 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 Java string, and ORDER BY comes after FROM. End each piece with a space before the closing quote.


STEP 1 OF 7
    Ctrl + Enter to check

    Sql Case in Java

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