bhylu.com

Advertisements

SQL Case

CASE chooses a value based on conditions. It can turn raw data into a useful report label without changing the stored value. The first matching WHEN branch supplies the result.

Understand the idea

This example labels stock as unavailable, low, or ready. The zero test comes first so it is not caught by a broader low-stock condition. ELSE gives a result when no earlier condition matches. Keep the output values compatible enough for the target database to choose a sensible result type.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT name,
  CASE
    WHEN stock = 0 THEN 'unavailable'
    WHEN stock < 10 THEN 'low'
    ELSE 'ready'
  END AS availability
FROM products
ORDER BY product_id;

Read the result

Canvas bag is unavailable, Desk lamp is low, and the two Stationery products are ready. The numeric stock values remain stored as before.

Try one change

Add a separate label for stock under 30. Place its branch carefully so the zero and under-10 rules still work.