⚡0 XP🔥0

CASE, Text, Date and NULL Functions

Lesson 6 of 8 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs SQL

Create categories with CASE WHEN, pivot data with conditional aggregation, use text functions, work with dates (SQLite with MySQL/PostgreSQL equivalents), and handle NULLs with COALESCE and NULLIF.

CASE WHEN - conditional logic#

CASE is SQL's IF / IFS:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE default_result
END
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Conditions are checked in order; the first true one wins (like an IF ladder).

Grouping by a CASE#

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Conditional aggregation - pivots in SQL#

Put CASE inside SUM or COUNT to create a column per category:

▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run
हिंदी में समझें

Conditional aggregation - SUM(CASE WHEN ... THEN 1 ELSE 0 END) - SQL में pivot table बनाने का तरीका है।

हर row के लिए CASE पूछता है: "क्या यह Delivered है?" - हाँ तो 1, नहीं तो 0। फिर SUM उन 1 को जोड़ देता है, यानी Delivered orders की गिनती। इसी तरह हर status के लिए अलग column बन जाता है।

Text functions#

Purpose SQLite MySQL PostgreSQL / SQL Server
Upper / lower case UPPER(x), LOWER(x) same same
Length LENGTH(x) LENGTH / CHAR_LENGTH LENGTH / LEN
Substring SUBSTR(x, start, len) SUBSTRING(x, start, len) SUBSTRING
Join text a || ' ' || b CONCAT(a, ' ', b) a || b / CONCAT
Trim spaces TRIM(x) same same
Replace REPLACE(x, 'a', 'b') same same
Position INSTR(x, 'a') INSTR / LOCATE POSITION / CHARINDEX
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

Date functions#

Dates in our database are stored as text 'YYYY-MM-DD' (ISO format), which sorts and compares correctly.

Purpose SQLite MySQL PostgreSQL
Year strftime('%Y', d) YEAR(d) EXTRACT(YEAR FROM d)
Month number strftime('%m', d) MONTH(d) EXTRACT(MONTH FROM d)
Year-month strftime('%Y-%m', d) DATE_FORMAT(d, '%Y-%m') TO_CHAR(d, 'YYYY-MM')
Day of week strftime('%w', d) (0 = Sun) DAYOFWEEK(d) EXTRACT(DOW FROM d)
Add days date(d, '+30 days') DATE_ADD(d, INTERVAL 30 DAY) d + INTERVAL '30 days'
Days between julianday(d2) - julianday(d1) DATEDIFF(d2, d1) d2 - d1
Today date('now') CURDATE() CURRENT_DATE
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run

NULL handling#

Function Does Example
COALESCE(a, b, ...) first non-NULL value COALESCE(manager_id, 0)
NULLIF(a, b) NULL if a = b revenue / NULLIF(orders, 0)
IFNULL(a, b) (SQLite/MySQL) / ISNULL (SQL Server) 2-argument COALESCE
▶ Try it Yourselfdatabase: shopSQL
Ctrl + Enter to run
Common Mistake

Any arithmetic with NULL gives NULL: 5 + NULL = NULL. And comparisons with NULL are never true. Use COALESCE before calculating when NULLs are possible.

CAST - converting types#

CAST('2025' AS INTEGER)
CAST(price AS TEXT)
ROUND(CAST(total AS REAL) / count, 2)

Summary#

  • CASE WHEN ... THEN ... ELSE ... END creates categories and flags.
  • SUM(CASE WHEN ... THEN 1 ELSE 0 END) builds pivot-style columns.
  • Text: UPPER, LOWER, LENGTH, SUBSTR, TRIM, REPLACE, ||/CONCAT.
  • Dates: SQLite strftime, date, julianday - know the MySQL/PostgreSQL equivalents.
  • NULLs: COALESCE, NULLIF; arithmetic with NULL returns NULL.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Price bands

Show each product's name, price and a price_band: 'Premium' if price ≥ 10000, 'Mid' if price ≥ 1000, otherwise 'Budget'. Sort by price descending.

Database: shop (see the tables in this lesson)
2

Status pivot by year

For each year (year), show the total number of orders (total), the number Delivered (delivered) and the number Cancelled or Returned (problem). Sort by year.

Database: shop (see the tables in this lesson)
3

Customer tenure

Show customer name, signup_date and signup_month (the month name like 'Jan', 'Feb'... using CASE on the month number, or use any method) - only for customers who signed up in 2024, sorted by signup_date. Hint - the month number is strftime('%m', signup_date).

Database: shop (see the tables in this lesson)

Quick Quiz

Q1.

What does CASE WHEN do?

Q2.

SUM(CASE WHEN status = 'Cancelled' THEN 1 ELSE 0 END) counts...

Q3.

What does COALESCE(manager_id, 0) return when manager_id is NULL?

Q4.

Why use NULLIF(denominator, 0) in a division?

Q5.

In MySQL, which function gives the year of a date?