CASE, Text and Date Functions
Real reports need labels and cleaned values: "Gold" customers above ₹10,000, names in proper case, dates as months. CASE adds if-then logic inside a query, and built-in functions handle text, numbers and dates.
CASE: if-then in SQL
Example
SELECT name, price,
CASE
WHEN price < 500 THEN 'Budget'
WHEN price < 1500 THEN 'Mid-range'
ELSE 'Premium'
END AS segment
FROM products
ORDER BY price;
-- Result:
-- name | price | segment
-- -------------------+-------+----------
-- Notebook Pack | 199 | Budget
-- Steel Water Bottle | 349 | Budget
-- Cotton T-shirt | 499 | Budget
-- Python Book | 599 | Mid-range
-- Yoga Mat | 799 | Mid-range
-- Table Lamp | 899 | Mid-range
-- Denim Jeans | 1299 | Mid-range
-- Wireless Earbuds | 1499 | Mid-range
-- Smart Watch | 3999 | Premium▶ Try it yourselfCASE also works inside aggregates - a neat trick for counting several things at once:
Example
SELECT COUNT(*) AS all_orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;
-- Result:
-- all_orders | delivered | cancelled
-- -----------+-----------+----------
-- 8 | 3 | 1▶ Try it yourselfText functions
Example
SELECT UPPER(name) AS upper_name,
LENGTH(name) AS letters,
SUBSTR(name, 1, 4) AS first_four,
name || ' (' || COALESCE(city, 'no city') || ')' AS label
FROM customers;
-- Result:
-- upper_name | letters | first_four | label
-- ------------+---------+------------+------------------------
-- ASHA VERMA | 10 | Asha | Asha Verma (Delhi)
-- RAVI KUMAR | 10 | Ravi | Ravi Kumar (Mumbai)
-- NEHA SINGH | 10 | Neha | Neha Singh (Pune)
-- ARJUN MEHTA | 11 | Arju | Arjun Mehta (Delhi)
-- FATIMA KHAN | 11 | Fati | Fatima Khan (Hyderabad)
-- VIKRAM RAO | 10 | Vikr | Vikram Rao (no city)▶ Try it yourself|| joins text in SQLite and PostgreSQL (MySQL uses CONCAT()). COALESCE(a, b) gives the first value that isn't NULL.
Date functions
Example
SELECT id, order_date,
strftime('%m', order_date) AS month,
julianday('2026-11-27') - julianday(order_date) AS days_ago
FROM orders
WHERE order_date >= '2026-11-01';
-- Result:
-- id | order_date | month | days_ago
-- ----+------------+-------+---------
-- 105 | 2026-11-01 | 11 | 26
-- 106 | 2026-11-03 | 11 | 24
-- 107 | 2026-11-10 | 11 | 17
-- 108 | 2026-11-15 | 11 | 12▶ Try it yourselfDate functions differ the most between databases: SQLite has
strftime and julianday, MySQL has DATE_FORMAT and DATEDIFF, PostgreSQL has to_char and date subtraction. The ideas are the same.Key points
- CASE WHEN ... THEN ... ELSE ... END adds conditions to queries.
- Text, number and date functions format and clean values.
- COALESCE replaces NULL with a default.
📝 Test yourself
1. What does COALESCE(city, 'no city') return when city is NULL?
2. Which counts only delivered orders inside one query?
3. Fill in the word that closes a CASE expression:
CASE WHEN price > 1000 THEN 'High' ELSE 'Low'
