Developer Guides, Cheat Sheets & Tools
SQL course - Part 4: FUNCTIONS
| Part index | Prerequisites | Previous | Next | Full course |
🧮 PART 4 — FUNCTIONS
[!NOTE] 📌 In plain words: A function takes a value in and gives a transformed value back.
UPPER('tom')gives'TOM'. Functions are how raw stored data becomes a readable report.
20. String functions
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟢 Beginner | 25 min | Clean and reshape text · Split and join text · Build codes like INV-00042 · Combine many rows into one list |
[!NOTE] 📌 In plain words: String functions reshape text. They cut pieces out of it, glue pieces together, change its case, strip the junk off the ends, and find things inside it. Real data arrives messy —
" aMARA ","AMARA.SILVA@EXAMPLE.COM ","+94 77 555 0101"— and these are the tools that make it usable.
🌍 Analogy: String functions are your text workshop: scissors to cut, glue to join, a magnifying glass to search, and sandpaper to clean up messy edges.
[!IMPORTANT] 🎯 When you will reach for them: cleaning imported data, building display labels and full names, extracting the domain from an email, generating reference codes like
INV-00042, and tidying values (for example, making every email lower-case) before you compare them.
20.1 📏 Length, case, and trimming
When a table cell says (2017+) or (2022+), that function needs SQL Server 2017 or 2022 or newer.
| Task | 🟥 MSSQL | 🟦 MySQL |
|---|---|---|
| Length in characters | LEN(s) ⚠️ ignores trailing spaces |
CHAR_LENGTH(s) |
| Length in bytes (storage size) | DATALENGTH(s) |
LENGTH(s) |
| Uppercase | UPPER(s) |
UPPER(s) |
| Lowercase | LOWER(s) |
LOWER(s) |
| Trim both ends | TRIM(s) (2017+) |
TRIM(s) |
| Trim left / right | LTRIM(s) / RTRIM(s) |
LTRIM(s) / RTRIM(s) |
| Trim a specific character | TRIM('x' FROM s) (2017+) |
TRIM('x' FROM s) |
| Repeat | REPLICATE(s, n) |
REPEAT(s, n) |
| Reverse | REVERSE(s) |
REVERSE(s) |
| Pad left / right | RIGHT(REPLICATE('0',5)+s,5) |
LPAD(s,5,'0') / RPAD(s,5,'0') |
| Space characters | SPACE(n) |
SPACE(n) |
-- ✅ Works in BOTH: clean up messy imported data
SELECT
TRIM(full_name) AS trimmed,
UPPER(country) AS country_code,
LOWER(email) AS normalized_email
FROM customers;
[!WARNING] ⚠️ MSSQL
LENvsDATALENGTH:LEN('abc ')returns 3 — it ignores trailing spaces.DATALENGTHreturns the true byte count (6 forVARCHAR, 12 forNVARCHAR). If you are checking whether data will fit a column, you wantDATALENGTH.
-- 🟦 MySQL: LPAD for invoice numbers like INV-00042
SELECT CONCAT('INV-', LPAD(order_id, 8, '0')) AS invoice_no FROM orders;
-- 🟥 MSSQL: the same result
SELECT 'INV-' + RIGHT(REPLICATE('0', 8) + CAST(order_id AS VARCHAR(10)), 8) AS invoice_no
FROM orders;
-- MSSQL 2012+ has FORMAT, which is prettier but SLOW on large sets
SELECT 'INV-' + FORMAT(order_id, '00000000') AS invoice_no FROM orders;
[!WARNING] ⚠️ Avoid
FORMAT()in MSSQL on large result sets. It runs extra Microsoft .NET code for every single row and is often 40x slower than plain text functions. It is fine for a 50-row report, terrible for a million-row export.
20.2 ✂️ Extracting parts of a string
| Task | 🟥 MSSQL | 🟦 MySQL |
|---|---|---|
| First n characters | LEFT(s, n) |
LEFT(s, n) |
| Last n characters | RIGHT(s, n) |
RIGHT(s, n) |
| Middle | SUBSTRING(s, start, len) |
SUBSTRING(s, start, len) |
| Find a position | CHARINDEX(what_to_find, text) |
LOCATE(what_to_find, text) or INSTR(text, what_to_find) |
| Split at a separator | STRING_SPLIT(s, ',') (2016+) |
SUBSTRING_INDEX(s, ',', n) |
[!TIP] 💡 Both use 1-based positions, not 0-based like most programming languages.
SUBSTRING('Hello', 1, 3)is'Hel'.
-- ✅ Real-world: split an email into the user part and the domain
-- 🟥 MSSQL
SELECT
email,
LEFT(email, CHARINDEX('@', email) - 1) AS user_part,
SUBSTRING(email, CHARINDEX('@', email) + 1, 200) AS domain_part
FROM customers;
-- 🟦 MySQL
SELECT
email,
SUBSTRING_INDEX(email, '@', 1) AS user_part,
SUBSTRING_INDEX(email, '@', -1) AS domain_part
FROM customers;
-- ✅ Real-world: split "Amara Silva" into first and last name
-- 🟥 MSSQL
SELECT
full_name,
LEFT(full_name, CHARINDEX(' ', full_name + ' ') - 1) AS first_name,
LTRIM(SUBSTRING(full_name, CHARINDEX(' ', full_name + ' '), 100)) AS last_name
FROM customers;
-- 🟦 MySQL
SELECT
full_name,
SUBSTRING_INDEX(full_name, ' ', 1) AS first_name,
SUBSTRING_INDEX(full_name, ' ', -1) AS last_name
FROM customers;
[!TIP] 💡 Note the
full_name + ' 'trick in the MSSQL version.CHARINDEX(' ', 'Madonna')returns 0, andLEFT(s, -1)errors. Appending a space guarantees a match and makes the expression safe for single-word names. Small defensive touches like this are what separates code that works on your test data from code that works on real data.
20.3 🔗 Joining and replacing
-- ✅ CONCAT syntax works in BOTH: SQL Server treats NULL as empty; MySQL returns NULL if any argument is NULL
SELECT CONCAT(full_name, ' (', country, ')') AS label FROM customers;
-- ✅ CONCAT_WS: "with separator" — joins and skips NULLs cleanly
SELECT CONCAT_WS(', ', city, country) AS location FROM customers;
-- If city is NULL you get "Sri Lanka", not ", Sri Lanka"
-- ✅ REPLACE works in BOTH
SELECT REPLACE(phone, '-', '') AS digits_only FROM customers;
SELECT REPLACE(REPLACE(REPLACE(phone,'-',''),' ',''),'+','') AS clean_phone FROM customers;
-- 🟥 MSSQL: STRING_AGG joins ROWS into one string (2017+)
SELECT
o.order_id,
STRING_AGG(p.product_name, ', ') WITHIN GROUP (ORDER BY p.product_name) AS items
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
GROUP BY o.order_id;
-- 🟦 MySQL: GROUP_CONCAT does the same
SELECT
o.order_id,
GROUP_CONCAT(p.product_name ORDER BY p.product_name SEPARATOR ', ') AS items
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
GROUP BY o.order_id;
Result — the query has no WHERE, so it returns one row per order (23 of them). One row,
shown in full, so you can see what the joined string looks like:
| order_id | items |
|---|---|
| 1002 | MechKey RGB Keyboard, VisionPanel 32 4K, WorkStation X17 |
(Built from the ShopDB of Chapter 4 — your order 1002 should read exactly this.)
[!WARNING] ⚠️ MySQL
GROUP_CONCATsilently truncates at 1024 characters by default. Your report looks fine in testing and loses data in production. Raise it:-- 🟦 MySQL SET SESSION group_concat_max_len = 100000;
20.4 🧼 A real-world data cleaning pipeline
-- ✅ Works in BOTH: normalize a messy imported customer file
SELECT
customer_id,
-- Fix casing: "aMARA silva" → "Amara silva"
CONCAT(UPPER(LEFT(TRIM(full_name), 1)), LOWER(SUBSTRING(TRIM(full_name), 2, 200))) AS clean_name,
-- Normalize the email
LOWER(TRIM(email)) AS clean_email,
-- Strip everything but digits from the phone
REPLACE(REPLACE(REPLACE(COALESCE(phone,''), '-', ''), ' ', ''), '+', '') AS clean_phone,
-- Flag rows that still look wrong
CASE
WHEN email NOT LIKE '%_@_%._%' THEN 'Invalid email'
WHEN TRIM(COALESCE(phone,'')) = '' THEN 'Missing phone'
ELSE 'OK'
END AS data_quality
FROM customers;
[!TIP] 💡 Pro tip: Do heavy text cleaning once, on the way in (in a staging table), not on every read. Cleaning in a
SELECTmeans the CPU work repeats for every user, every query, forever — and it stops indexes from being used (see Chapter 48).
20.5 🧪 Try it yourself
- Produce a column reading
SILVA, Amarafor every customer. - Extract the email domain and count customers per domain.
- Build a padded product code like
PRD-0007fromproduct_id. - For each order, produce one row listing all its product names, comma-separated.
🧭 In practice — string functions
How to use it. Join text with
CONCAT, cut it withSUBSTRING/LEFT/RIGHT, clean it withTRIM, change case withUPPER/LOWER, and swap content withREPLACE. Measure length withLEN(SQL Server) orCHAR_LENGTH(MySQL). Expected result: readable output built in the query instead of patched up in application code.When to use it. For presentation — building a full name, formatting a reference, masking a card number — and for one-off cleaning of imported data.
Where to use it. Reports and data-cleaning pipelines. Scenario: a supplier feed arrives with trailing spaces and inconsistent capitalisation.
TRIMandUPPERin the load query normalise it once, at the boundary, so every downstream query and everyJOINon those values behaves predictably.When not to use it. Do not apply a string function to a column inside a
WHEREclause on a large table —WHERE UPPER(email) = 'A@B.COM'cannot use an index onBest practices. Clean data on the way in rather than in every query that reads it. Beware the differences:
CONCATtreatsNULLas empty in SQL Server; MySQLCONCATreturnsNULLif any argument isNULL. Use explicitCOALESCEarguments for matching behavior. SQL Server+propagatesNULL. Remember that character length and byte length diverge for non-ASCII text, which matters for both truncation and column sizing (Chapter 60).
21. Numeric and math functions
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟢 Beginner | 20 min | Round numbers correctly · Avoid the integer-division trap · Calculate percentages · Pick random rows |
[!NOTE] 📌 In plain words: These are the everyday calculator buttons of SQL — rounding money to two decimals, working out a percentage, splitting a total into whole units. You will use four of them constantly and the rest almost never.
🌍 Real-world analogy: A till at a shop counter. It adds, it applies tax, and — crucially — it decides how to round the awkward half-cent. Get the rounding rule wrong and every receipt is a penny out; do it a million times and someone notices.
21.1 🔢 The essential list
| Task | 🟥 MSSQL | 🟦 MySQL | Example |
|---|---|---|---|
| Round to n places | ROUND(x, n) |
ROUND(x, n) |
ROUND(3.567, 2) → 3.57 |
| Round up | CEILING(x) |
CEIL(x) / CEILING(x) |
CEILING(3.1) → 4 |
| Round down | FLOOR(x) |
FLOOR(x) |
FLOOR(3.9) → 3 |
| Chop off decimals | ROUND(x, 0, 1) |
TRUNCATE(x, 0) |
TRUNCATE(3.99, 0) → 3 |
| Absolute value | ABS(x) |
ABS(x) |
ABS(-15) → 15 |
| Remainder | x % y |
MOD(x, y) or x % y |
10 % 3 → 1 |
| Power | POWER(x, y) |
POW(x, y) |
POWER(2, 10) → 1024 |
| Square root | SQRT(x) |
SQRT(x) |
|
| Sign | SIGN(x) |
SIGN(x) |
-1, 0, or 1 |
| Random 0–1 | RAND() |
RAND() |
|
| Greatest / least | GREATEST/LEAST (2022+) |
GREATEST/LEAST |
|
| Logarithms | LOG(x), LOG10(x), EXP(x) |
same |
-- ✅ Works in BOTH: a realistic pricing report
SELECT
product_name,
unit_price,
ROUND(unit_price * 0.15, 2) AS tax_amount,
ROUND(unit_price * 1.15, 2) AS price_with_tax,
CEILING(unit_price) AS rounded_up_display_price,
ROUND(unit_price * 0.85, 2) AS sale_price_15_off
FROM products
ORDER BY unit_price DESC;
21.2 ⚠️ The integer division trap
-- ⚠️ Works in BOTH, but the engines DISAGREE on integer ÷ integer
SELECT 10 / 4; -- 🟥 MSSQL: 2, not 2.5 — the decimals are DISCARDED
-- 🟦 MySQL: 2.5000 (MySQL promotes to decimal, friendlier here)
-- 🟦 MySQL: explicit integer division, when that is what you want
SELECT 10 DIV 4; -- 2
🔀 This really matters when you move code between engines. MSSQL does whole-number division; MySQL switches to decimal maths. Code that computes percentages correctly in MySQL can return all zeros in MSSQL.
-- ✅ The portable fix: force a decimal into the expression
SELECT
category_id,
COUNT(*) AS product_count,
-- ❌ WRONG in MSSQL: gives 0
COUNT(*) / (SELECT COUNT(*) FROM products) AS bad_share,
-- ✅ RIGHT in both: multiply by 100.0 (a number written with a decimal point)
ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM products), 2) AS pct_of_catalog
FROM products
GROUP BY category_id;
[!TIP] 💡 Memorize this habit:
100.0 * a / b, never100 * a / b. The.0turns the whole calculation into decimal maths. It is the single most common cause of “why is my percentage zero?”
21.3 🎲 Random rows and rounding modes
-- ✅ MSSQL: a random sample of 5 products
SELECT TOP 5 * FROM products ORDER BY NEWID();
-- ✅ MySQL: a random sample of 5 products
SELECT * FROM products ORDER BY RAND() LIMIT 5;
[!WARNING] ⚠️
ORDER BY RAND()sorts the entire table before taking 5 rows. Fine for 18 products, catastrophic for 18 million. For large tables, pick random ID numbers instead.
Some systems round 2.5 to 2 (banker’s rounding: to the nearest even number); others round it to 3 (half-up). Check what your engine does:
-- Banker's rounding vs half-up: know which your engine does
SELECT ROUND(2.5, 0), ROUND(3.5, 0);
-- Both MSSQL and MySQL round half AWAY FROM ZERO here: 3 and 4.
-- But floating-point inputs can behave differently — another reason to use DECIMAL for money.
21.4 🎯 When to use which rounding function
This is the decision people get wrong most often, so here it is as a table:
| You want to… | Use | 12.7 becomes |
-12.7 becomes |
|---|---|---|---|
| Round to the nearest value (normal maths) | ROUND(x, 0) |
13 | -13 |
| Round money to 2 decimals for display | ROUND(x, 2) then CAST(... AS DECIMAL(12,2)) |
— | — |
| Always round up (order enough boxes) | CEILING(x) |
13 | -12 |
| Always round down (how many fit in a pallet) | FLOOR(x) |
12 | -13 |
| Chop the decimals off, keep the sign | ROUND(x,0,1) 🟥 / TRUNCATE(x,0) 🟦 |
12 | -12 |
[!WARNING] ⚠️ Note the negative-number column.
CEILING(-12.7)is-12, not-13— “up” means towards bigger numbers, and −12 is bigger than −13.FLOORandTRUNCATEdisagree on negatives too. If your data can go negative (refunds, adjustments, temperature), pick deliberately and write a test.
Real-world uses, in the language of the business:
-- ✅ Works in BOTH
-- 📦 "How many 12-packs must we order to cover demand?" → always round UP
SELECT product_name, units_in_stock, reorder_level,
CEILING((reorder_level * 2.0 - units_in_stock) / 12.0) AS packs_to_order
FROM products
WHERE units_in_stock < reorder_level;
-- 💰 "Split an order total evenly across 3 instalments, to the cent"
SELECT
order_id,
CAST(SUM(unit_price*quantity*(1-discount)) AS DECIMAL(12,2)) AS total,
CAST(SUM(unit_price*quantity*(1-discount))/3 AS DECIMAL(12,2)) AS per_instalment
FROM order_items GROUP BY order_id;
-- 🔢 "Give me every 3rd product" → the remainder operator %
SELECT product_id, product_name FROM products WHERE product_id % 3 = 0;
-- 📊 "What percentage of stock is this product?" → the 100.0 trick (SUM(...) OVER () = the grand total, Chapter 33)
SELECT product_name,
ROUND(100.0 * units_in_stock / SUM(units_in_stock) OVER (), 2) AS pct_of_stock
FROM products;
[!CAUTION] 🐛 Common mistake: rounding at the wrong moment. Round once, at the end, for display. If you round each line of an order to 2 decimals and then add them up, your total can differ from the true total by several cents — and an invoice whose lines do not add up to its total is an invoice the finance team rejects. Do the maths at full precision; round only the final number you show.
[!TIP] 💡 Pro tip:
ROUND()changes the value but not the number of decimal places the result is shown with, so it can still display as129.00000. When the number is going straight onto a report, finish withCAST(x AS DECIMAL(12,2)). See Chapter 28 for a worked example.
21.5 🧪 Try it yourself
- Show each product’s price, price with 8.25% tax, and the tax rounded to 2 places.
- Compute each category’s share of the total catalogue as a percentage — and confirm it is not zero in MSSQL.
- Find products whose
product_idis even (MOD/%). - Calculate the average order value, rounded to 2 decimal places.
🧭 In practice — numeric and math functions
How to use it. Round with
ROUND, truncate toward zero withROUND(x,0,1)(SQL Server) orTRUNCATE(x,0)(MySQL);FLOOR/CEILINGround toward negative/positive infinity, take a remainder with%orMOD, and compute absolute values and powers withABSandPOWER. Expected result: numbers formatted and bucketed as the business defines them, not as the engine happens to default.When to use it. Financial rounding, percentage calculations, bucketing values into bands, and anywhere a raw computed number needs a defined precision.
Where to use it. Reporting and billing. Scenario: an order total computed as
unit_price * quantity * (1 - discount)produces long fractions.ROUND(..., 2)applied once, at a defined point, keeps the invoice, the payment, and the ledger agreeing — rounding at three different points is how a penny goes missing.When not to use it. Do not do financial arithmetic on
FLOAT/DOUBLEcolumns: the type cannot represent many decimal values exactly, so sums drift. UseDECIMAL. Also avoid integer division surprises — SQL Server5 / 2yields2, so cast one side when you want2.5. MySQL/yields a fractional result; MySQLDIVperforms integer division.Best practices. Decide once where rounding happens and document it; rounding at several stages of a calculation is a classic source of off-by-a-penny disputes. Be aware that
ROUNDuses half-away-from-zero in both engines here, which is not the banker’s rounding some financial rules require — if your domain specifies a rounding mode, implement it explicitly rather than assuming.
22. Date and time functions
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟢🟡 Beginner–Intermediate | 30 min | Get today’s date and time · Add and subtract dates · Measure the time between dates · Build monthly reports safely |
[!NOTE] 📌 In plain words: Dates are the most error-prone data type in SQL. Time zones, month lengths, leap years, and date formats all work against you. This chapter is your defence.
🌍 Analogy: Is
03/04/2026the 3rd of April or the 4th of March? A British person and an American person will give you different answers — and so will two databases. Date functions are how you stop guessing.
22.1 🕐 Getting the current date and time
| Task | 🟥 MSSQL | 🟦 MySQL |
|---|---|---|
| Now (date + time) | GETDATE(), SYSDATETIME() |
NOW(), CURRENT_TIMESTAMP |
| Now in UTC | GETUTCDATE(), SYSUTCDATETIME() |
UTC_TIMESTAMP() |
| Today only | CAST(GETDATE() AS DATE) |
CURDATE(), CURRENT_DATE |
| Time only | CAST(GETDATE() AS TIME) |
CURTIME() |
-- 🟥 MSSQL
SELECT GETDATE() AS now_local,
SYSDATETIME() AS now_high_precision,
SYSUTCDATETIME() AS now_utc,
CAST(GETDATE() AS DATE) AS today;
-- 🟦 MySQL
SELECT NOW() AS now_local,
UTC_TIMESTAMP() AS now_utc,
CURDATE() AS today,
CURTIME() AS time_now;
[!TIP] 💡
SYSDATETIME()is more precise thanGETDATE()(100 nanoseconds vs 3.33 milliseconds). Prefer it for new MSSQL code.
22.2 🧩 Extracting parts of a date
| Part | 🟥 MSSQL | 🟦 MySQL |
|---|---|---|
| Year | YEAR(d) or DATEPART(YEAR, d) |
YEAR(d) |
| Month number | MONTH(d) |
MONTH(d) |
| Day of month | DAY(d) |
DAY(d) |
| Hour / minute / second | DATEPART(HOUR, d) |
HOUR(d), MINUTE(d), SECOND(d) |
| Day of week | DATEPART(WEEKDAY, d) ⚠️ depends on the server’s language settings |
DAYOFWEEK(d) (1=Sun), WEEKDAY(d) (0=Mon) |
| Day of year | DATEPART(DAYOFYEAR, d) |
DAYOFYEAR(d) |
| Week number | DATEPART(ISO_WEEK, d) |
WEEK(d, 3) for the ISO (international standard) week |
| Quarter | DATEPART(QUARTER, d) |
QUARTER(d) |
| Month name | DATENAME(MONTH, d) |
MONTHNAME(d) |
| Day name | DATENAME(WEEKDAY, d) |
DAYNAME(d) |
| Last day of month | EOMONTH(d) |
LAST_DAY(d) |
-- 🟥 MSSQL — real-world: break orders down by time period
SELECT
order_id,
order_date,
YEAR(order_date) AS order_year,
MONTH(order_date) AS order_month,
DATENAME(MONTH, order_date) AS month_name, -- 🟥 MSSQL
DATEPART(QUARTER, order_date) AS quarter -- 🟥 MSSQL
FROM orders;
-- 🟦 MySQL equivalent
SELECT
order_id,
order_date,
YEAR(order_date) AS order_year,
MONTH(order_date) AS order_month,
MONTHNAME(order_date) AS month_name,
QUARTER(order_date) AS quarter
FROM orders;
22.3 ➕ Date arithmetic
-- 🟥 MSSQL: DATEADD(part, number, date)
SELECT
GETDATE() AS today,
DATEADD(DAY, 7, GETDATE()) AS next_week,
DATEADD(MONTH, 1, GETDATE()) AS next_month,
DATEADD(YEAR, -1, GETDATE()) AS last_year,
DATEADD(HOUR, -2, GETDATE()) AS two_hours_ago;
-- 🟦 MySQL: DATE_ADD / DATE_SUB, or the INTERVAL shorthand
SELECT
NOW() AS today,
DATE_ADD(NOW(), INTERVAL 7 DAY) AS next_week,
NOW() + INTERVAL 1 MONTH AS next_month,
NOW() - INTERVAL 1 YEAR AS last_year,
DATE_SUB(NOW(), INTERVAL 2 HOUR) AS two_hours_ago;
Difference between two dates:
-- 🟥 MSSQL: DATEDIFF(part, start, end)
SELECT
order_id,
order_date,
ship_date,
DATEDIFF(DAY, order_date, ship_date) AS days_to_ship
FROM orders
WHERE ship_date IS NOT NULL;
-- 🟦 MySQL: DATEDIFF gives DAYS only; TIMESTAMPDIFF takes a unit
SELECT
order_id,
DATEDIFF(ship_date, order_date) AS days_to_ship,
TIMESTAMPDIFF(HOUR, order_date, ship_date) AS hours_to_ship,
TIMESTAMPDIFF(MONTH, order_date, CURDATE()) AS months_ago
FROM orders
WHERE ship_date IS NOT NULL;
[!WARNING] ⚠️ Argument order is reversed! MSSQL is
DATEDIFF(part, earlier, later). MySQL isDATEDIFF(later, earlier). Get it backwards and every duration in your report is negative.
[!WARNING] ⚠️
DATEDIFFcounts calendar boundaries crossed (such as New Year), not the time that really passed. In MSSQL,DATEDIFF(YEAR, '2025-12-31', '2026-01-01')is 1, despite being one day apart. Calculating someone’s age withDATEDIFF(YEAR, date_of_birth, GETDATE())is therefore wrong for anyone whose birthday has not happened yet this year.
-- ✅ MSSQL: correct age calculation (adjust for a birthday not yet reached)
SELECT DATEDIFF(YEAR, '1990-11-20', GETDATE())
- CASE WHEN (MONTH(GETDATE()) < 11)
OR (MONTH(GETDATE()) = 11 AND DAY(GETDATE()) < 20)
THEN 1 ELSE 0 END AS age;
-- ✅ MySQL has a built-in for exactly this
SELECT TIMESTAMPDIFF(YEAR, '1990-11-20', CURDATE()) AS age;
22.4 📅 Truncating to period boundaries — the reporting workhorse
Reports often need to turn every date into “the first day of its month”, so that all of March’s orders fall into one group. That is called truncating a date.
-- ✅ MSSQL 2012+ : works on every supported version
-- First day of the month
SELECT DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1) AS month_start FROM orders;
-- The classic trick that works everywhere
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, order_date), 0) AS month_start FROM orders;
-- Last day of the month
SELECT EOMONTH(order_date) AS month_end FROM orders;
-- ✅ MSSQL 2022+ ONLY: DATETRUNC is cleaner, but it does not exist before 2022.
-- On SQL Server 2019 or older this fails with:
-- 'DATETRUNC' is not a recognized built-in function name.
SELECT DATETRUNC(MONTH, order_date) AS month_start FROM orders;
-- 🟦 MySQL
SELECT DATE_FORMAT(order_date, '%Y-%m-01') AS month_start FROM orders;
SELECT LAST_DAY(order_date) AS month_end FROM orders;
-- ✅ Real-world: monthly revenue report (the query every business asks for)
-- 🟥 MSSQL
SELECT
DATEFROMPARTS(YEAR(o.order_date), MONTH(o.order_date), 1) AS month_start,
COUNT(DISTINCT o.order_id) AS order_count,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY DATEFROMPARTS(YEAR(o.order_date), MONTH(o.order_date), 1)
ORDER BY month_start;
-- 🟦 MySQL
SELECT
DATE_FORMAT(o.order_date, '%Y-%m') AS month_key,
COUNT(DISTINCT o.order_id) AS order_count,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY DATE_FORMAT(o.order_date, '%Y-%m')
ORDER BY month_key;
22.5 🎨 Formatting dates for display
-- 🟥 MSSQL
SELECT
FORMAT(GETDATE(), 'yyyy-MM-dd') AS iso_date,
FORMAT(GETDATE(), 'dd MMM yyyy') AS friendly,
FORMAT(GETDATE(), 'dddd, dd MMMM yyyy') AS long_form,
CONVERT(VARCHAR(10), GETDATE(), 120) AS fast_iso; -- style 120 = ISO
-- 🟦 MySQL
SELECT
DATE_FORMAT(NOW(), '%Y-%m-%d') AS iso_date,
DATE_FORMAT(NOW(), '%d %b %Y') AS friendly,
DATE_FORMAT(NOW(), '%W, %d %M %Y') AS long_form;
Common MySQL DATE_FORMAT codes:
| Code | Meaning | Example |
|---|---|---|
%Y / %y |
4- / 2-digit year | 2026 / 26 |
%m / %c |
Month with / without leading zero | 09 / 9 |
%M / %b |
Month name / abbreviated | September / Sep |
%d / %e |
Day with / without leading zero | 09 / 9 |
%W / %a |
Weekday name / abbreviated | Wednesday / Wed |
%H:%i:%s |
24-hour time | 14:30:00 |
%h:%i %p |
12-hour time | 02:30 PM |
[!TIP] 💡 Pro tip — format in the application, not in SQL. Return plain
DATE/DATETIMEvalues and let your app display them in each user’s own style (for example03/12/2026in the US and12/03/2026in Europe). Formatting in SQL makes results bigger, breaks sorting ('01/02/2026'sorts as text), and is slow. The exception is a CSV export (a plain text file of rows that Excel can open) or a report where SQL is genuinely the last stop.
22.6 ⚠️ Date literals, formats, and the biggest trap
-- ✅ SAFE in BOTH: ISO 8601 (year-month-day), understood the same way everywhere
SELECT order_id FROM orders WHERE order_date >= '2026-03-01';
-- ✅ Also safe in MSSQL: no separators at all
SELECT order_id FROM orders WHERE order_date >= '20260301';
-- ❌ DANGEROUS: interpreted differently by region/language settings
-- Is this 1 March or 3 January? In MSSQL it depends on the session's language;
-- MySQL (strict mode, the default) rejects it outright: ERROR 1525 Incorrect DATE value.
SELECT order_id FROM orders WHERE order_date >= '03/01/2026';
[!WARNING] ⚠️
'2026-03-01'is safe in both engines today, but MSSQL’s olderDATETIMEtype could readYYYY-MM-DDdifferently depending on a language setting calledDATEFORMAT. The bulletproof MSSQL literal is'20260301'(no separators) orCAST('2026-03-01' AS DATE). Always write dates in ISO order and never inDD/MMorMM/DDform.
[!WARNING] ⚠️ The performance trap — never wrap the column in a function:
-- ❌ SLOW: the index on order_date cannot be used SELECT order_id FROM orders WHERE YEAR(order_date) = 2026; -- ✅ FAST: the index works perfectly SELECT order_id FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01';This applies to
MONTH(),CAST(),CONVERT(),DATE_FORMAT()— any function applied to the column. See Chapter 48.
22.7 🎯 When to use which date tool
| You want to… | Use | ⚠️ Watch out |
|---|---|---|
| Filter a month / year / range | >= start AND < next_start |
Never YEAR(col) = 2026 — the index can no longer be used |
| Group a report by month | DATEFROMPARTS(...) 🟥 / DATE_FORMAT(d,'%Y-%m') 🟦 |
Grouping by a function is fine; filtering by one is not |
| Measure a duration | DATEDIFF 🟥 / TIMESTAMPDIFF 🟦 |
Argument order is reversed between engines |
| Someone’s age | TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) 🟦 / DATEDIFF + a birthday check 🟥 |
DATEDIFF(YEAR,…) counts New Years crossed, not full years |
| Show a date to a user | Format in the application | Formatting in SQL breaks sorting and is slow |
| Store when something happened | DATETIME2 / DATETIME in UTC |
Mixed local times are unrecoverable |
| Store a wall-clock appointment | DATETIME (no zone conversion) |
TIMESTAMP in MySQL converts, and dies in 2038 |
| The last day of the month | EOMONTH 🟥 / LAST_DAY 🟦 |
Do not hand-code 30/31 — February exists |
[!CAUTION] 🐛 Common mistake:
BETWEEN '2026-01-01' AND '2026-01-31'on aDATETIMEcolumn. It silently drops everything after midnight on the 31st — roughly one day of data per month, forever. Use the half-open range.
22.8 🧪 Try it yourself
- Show every order with the number of days it took to ship.
- List orders placed in April–June 2026 (Q2) using the index-friendly half-open date range from 14.3.
- Produce a monthly revenue report in both dialects.
- Find the last day of the month for every order date.
- Calculate how many days each unshipped order has been waiting.
🧭 In practice — date and time functions
How to use it. Get the current moment with
GETDATE()/SYSDATETIME()(SQL Server) orNOW()(MySQL). Add intervals withDATEADD/DATE_ADD, measure gaps withDATEDIFF, and extract parts withYEAR,MONTH,DAY. Expected result: date arithmetic the database understands, rather than string manipulation that breaks at month ends.When to use it. Reporting by period, age and duration calculations, expiry and reminder logic, and anything with a deadline.
Where to use it. Business reporting. Scenario: “revenue per month” needs every order truncated to its month boundary. Doing that with a date function is correct across leap years and month lengths; doing it by slicing the first seven characters of a formatted string is a bug waiting for a non-ISO locale.
When not to use it. Never filter with a function wrapped around the date column —
WHERE YEAR(order_date) = 2026disables the index. Use a half-open range:>= '2026-01-01' AND < '2027-01-01'. Half-open also avoids theBETWEENend-of-day trap, whereBETWEEN '2026-03-01' AND '2026-03-31'silently excludes everything that happened on the 31st after midnight.Best practices. Store timestamps in UTC and convert for display (Chapter 61); a system that stores local time cannot answer “what happened first?” across a daylight-saving change. Write date literals in the unambiguous
YYYY-MM-DDform —'03/04/2026'means different days on different servers, and the default interpretation depends on language settings you do not control.
23. Conversion and casting
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟢🟡 Beginner–Intermediate | 20 min | Convert between text, numbers, and dates · Convert safely without errors · Spot slow hidden conversions |
[!NOTE] 📌 In plain words: Converting turns one data type into another — text into a number, a date into text. Do it deliberately, because otherwise the database will do it implicitly (silently, on its own), and those silent conversions are a leading cause of slow queries.
🌍 Analogy: Currency exchange. You can swap your money at the bank at a clear rate (an explicit conversion), or let a shop quietly convert it at the till for you (an implicit one). Both work — but only one of them lets you see what just happened.
23.1 🔁 CAST and CONVERT
-- 🟥 MSSQL: CAST is standard SQL — but the target type NAMES differ by engine
SELECT CAST('123' AS INT) AS text_to_number;
SELECT CAST(123.99 AS INT) AS decimal_to_int; -- 123, truncated
SELECT CAST('2026-06-15' AS DATE) AS text_to_date;
SELECT CAST(unit_price AS VARCHAR(20)) AS price_as_text FROM products;
-- 🟦 MySQL: there is no INT or VARCHAR target — use SIGNED / UNSIGNED / DECIMAL / CHAR
SELECT CAST('123' AS SIGNED) AS text_to_number;
SELECT CAST(123.99 AS SIGNED) AS decimal_to_int; -- 124: MySQL ROUNDS
SELECT CAST('2026-06-15' AS DATE) AS text_to_date;
SELECT CAST(unit_price AS CHAR) AS price_as_text FROM products;
-- 🟥 MSSQL: CONVERT adds style codes, mainly useful for dates
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS iso; -- 2026-09-09
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS british; -- 09/09/2026
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS american; -- 09/09/2026
-- 🟦 MySQL: CONVERT exists with different syntax, mostly for character sets
SELECT CONVERT('123', UNSIGNED) AS n;
SELECT CONVERT(full_name USING utf8mb4) AS s FROM customers;
23.2 🛡️ Safe conversion that does not blow up
-- ✅ Works in BOTH: put a few messy rows into the staging table from Chapter 12
INSERT INTO staging_customers (customer_code, full_name, email) VALUES
('1001', 'Clean Row', 'clean@example.com'),
('1002', 'Also Clean', 'also@example.com'),
('ABC123', 'Junk Code', 'junk@example.com');
-- ❌ 🟥 MSSQL: one bad row kills the entire query
SELECT CAST(customer_code AS INT) FROM staging_customers;
-- "Conversion failed when converting the varchar value 'ABC123' to data type int."
-- 🟥 MSSQL 2012+: TRY_CAST / TRY_CONVERT return NULL instead of erroring
SELECT
customer_code,
TRY_CAST(customer_code AS INT) AS numeric_code
FROM staging_customers;
-- Find exactly which rows are bad
SELECT * FROM staging_customers WHERE TRY_CAST(customer_code AS INT) IS NULL;
-- 🟦 MySQL: no TRY_CAST. Keep only the rows that really look like numbers first.
SELECT customer_code
FROM staging_customers
WHERE customer_code REGEXP '^[0-9]+$'; -- only genuinely numeric rows
[!TIP] 💡
TRY_CASTis a data-cleaning superpower in MSSQL. After loading a CSV file, you can find every badly formatted value in one query, instead of discovering them one error at a time.
23.3 ⚠️ Implicit conversion — the silent performance killer
-- The column holds text (VARCHAR), but the value typed here is a number
SELECT * FROM customers WHERE phone = 94775550101;
[!WARNING] ⚠️ What just happened: SQL cannot compare text with a number, so it converts one of them. SQL ranks data types, and numbers rank above text, so the engine converts the column — every row of it — into numbers. Converting the column means the index on
phonecannot be used, and every row must be read and converted.There are then two possible outcomes, and you should know both:
If every value in the column converts cleanly If any value does not The query works, but silently reads the whole table. A 5-millisecond index lookup (a seek) becomes a 5-second read of every row (a scan). The query fails outright partway through. Run the query above against ShopDB and you get the second outcome, because the phone numbers contain
+and-:Msg 8114: Error converting data type nvarchar to numeric.The error is actually the lucky case — it is loud. The dangerous case is a numeric-looking column where everything converts, the query keeps working, and it just quietly gets 1000x slower as the table grows.
-- ✅ Match the types: quote the literal
SELECT * FROM customers WHERE phone = '+94-77-555-0101';
How to spot it (execution plans are explained in Chapter 47): in an MSSQL execution plan, look for a CONVERT_IMPLICIT warning on a scan operator. In MySQL, EXPLAIN shows a full table scan where you expected a ref lookup.
[!TIP] 💡 The rule: always compare a column with a value of the same data type. Numbers without quotes, text in quotes, dates as
'YYYY-MM-DD'. This one habit prevents a whole family of slowdowns on live systems.
23.4 🧮 Numeric conversion precision
-- ✅ Works in BOTH
SELECT
CAST(10 AS DECIMAL(10,2)) / CAST(3 AS DECIMAL(10,2)) AS careful; -- 3.333333
SELECT 10 / 3; -- 🟥 MSSQL: 3 (integer!) 🟦 MySQL: 3.3333
-- ✅ MSSQL: FORMAT takes a PATTERN such as 'N2', not a number of decimal places
SELECT
product_name,
unit_price,
CAST(unit_price AS VARCHAR(20)) AS as_text,
CONCAT('$', FORMAT(unit_price, 'N2')) AS formatted -- $1,499.00
FROM products;
-- ✅ MySQL: FORMAT takes the NUMBER OF DECIMAL PLACES
SELECT
product_name,
unit_price,
CAST(unit_price AS CHAR) AS as_text,
CONCAT('$', FORMAT(unit_price, 2)) AS formatted -- $1,499.00
FROM products;
🔀 Same function name, completely different second argument. MySQL’s
FORMAT(x, 2)means “two decimal places”. MSSQL’sFORMAT(x, 'N2')takes a .NET format string. Passing MySQL’s integer to SQL Server gives you:Msg 8116: Argument data type int is invalid for argument 2 of format function.Useful MSSQL format strings:
'N2'(1,499.00),'C'(currency, in the server’s local style),'P1'(percent),'0.00'(no thousands separator). And remember the warning from Chapter 20:FORMAT()in MSSQL is slow — fine for a report, bad for a million rows.
23.5 🧪 Try it yourself
- Convert every product price to a string prefixed with
USD. - In MSSQL, use
TRY_CASTto find which values in a text column are not valid integers. - Write a query that triggers an implicit conversion, then check the execution plan for the warning.
- Convert
order_dateto three different display formats.
🧭 In practice — conversion and casting
How to use it. Convert explicitly with
CAST(value AS type). When the input might not be convertible, useTRY_CAST/TRY_CONVERTin SQL Server, which returnNULLinstead of raising. Expected result: conversions happen where you decided, with a failure mode you chose.When to use it. At boundaries: loading text files into typed columns, accepting input of uncertain quality, and formatting values for display.
Where to use it. Staging and import pipelines. Scenario: a CSV of customer codes should be numeric, but three rows contain text.
SELECT * FROM staging WHERE TRY_CAST(code AS INT) IS NULLfinds exactly those three rows so you can fix them — whereas a plainCASTfails the whole load and tells you nothing about which row was bad.When not to use it. Avoid relying on implicit conversion, which is the silent performance killer this chapter demonstrates: comparing an
NVARCHARcolumn to a number makes the engine convert the entire column, disabling the index, and it can fail outright withMsg 8114. Note also that the two engines differ — SQL Server casts toINT/VARCHAR(n), MySQL toSIGNED/CHAR— so cast expressions are among the least portable SQL you will write.Best practices. Compare like with like: fix the type mismatch rather than casting in the
WHEREclause, because casting the column is precisely what destroys index usage. Be explicit about formats when converting dates to text, and prefer doing final display formatting in the application, where locale is known.
24. Conditional logic: CASE, IIF, IF
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟢 Beginner | 20 min | Write if/then logic with CASE · Label and group values · Count many different things in one query |
[!NOTE] 📌 In plain words:
CASEis SQL’s “if this, then that”. It lets one query return different values depending on the data — for example, labelling each product as Cheap, Mid-range, or Premium.
🌍 Analogy: Sorting post at a post office: if the envelope says London, put it in bag A; if it says Paris, bag B; otherwise, bag C.
CASEdoes exactly this for every row.
24.1 🔀 The two forms of CASE
A searched CASE tests any condition you like. A simple CASE compares one column with a list of values.
-- ✅ SEARCHED CASE (most flexible) — works in BOTH
SELECT
product_name,
unit_price,
CASE
WHEN unit_price >= 1000 THEN 'Premium'
WHEN unit_price >= 500 THEN 'Mid-range'
WHEN unit_price >= 100 THEN 'Budget'
ELSE 'Entry level'
END AS price_band
FROM products
ORDER BY unit_price DESC;
-- ✅ SIMPLE CASE (equality only) — works in BOTH
SELECT
order_id,
status,
CASE status
WHEN 'Pending' THEN 'Awaiting payment'
WHEN 'Paid' THEN 'Ready to pack'
WHEN 'Shipped' THEN 'On the way'
WHEN 'Delivered' THEN 'Complete'
ELSE 'Needs attention'
END AS friendly_status
FROM orders;
[!WARNING] ⚠️
CASEstops at the first matchingWHEN— order matters. If you putWHEN unit_price >= 100first, everything above 100 becomes “Budget” and the premium branch is unreachable. Put the strictest condition first.
[!WARNING] ⚠️ Always write
ELSE. With noELSE, unmatched rows silently becomeNULL. In aSELECTthat is confusing; in anUPDATEit is data loss.
24.2 ⚡ Shorthand forms
-- 🟥 MSSQL: IIF is a compact two-branch CASE
SELECT product_name,
IIF(units_in_stock = 0, 'Out of stock', 'Available') AS availability
FROM products;
-- CHOOSE picks the nth item from a list
SELECT CHOOSE(3, 'Bronze', 'Silver', 'Gold', 'Platinum') AS tier; -- 'Gold'
-- 🟦 MySQL: IF(condition, true_value, false_value)
SELECT product_name,
IF(units_in_stock = 0, 'Out of stock', 'Available') AS availability
FROM products;
-- ELT picks the nth item
SELECT ELT(3, 'Bronze', 'Silver', 'Gold', 'Platinum') AS tier; -- 'Gold'
[!TIP] 💡 Use
CASEin code you intend to keep.IIFandIFonly work in one engine each;CASEworks in every SQL database on earth. Save the shorthand for quick one-off queries.
24.3 🎯 The five patterns you will actually use
Some of these examples also use JOIN and GROUP BY (Chapters 26 and 28). Focus on the CASE part for now.
① Bucketing values into categories
-- ✅ Works in BOTH: customer segmentation by recency
SELECT
c.full_name,
MAX(o.order_date) AS last_order,
CASE
WHEN MAX(o.order_date) IS NULL THEN 'Never ordered'
WHEN MAX(o.order_date) >= '2026-07-01' THEN 'Active'
WHEN MAX(o.order_date) >= '2026-04-01' THEN 'Cooling off'
ELSE 'Dormant'
END AS segment
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.full_name;
② Conditional aggregation — counting things that match a condition
This is one of the most valuable techniques in all of SQL.
-- ✅ Works in BOTH: one pass over the table, many different counts
SELECT
COUNT(*) AS total_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,
SUM(CASE WHEN ship_date IS NULL THEN 1 ELSE 0 END) AS not_shipped,
ROUND(100.0 * SUM(CASE WHEN status = 'Cancelled' THEN 1 ELSE 0 END)
/ COUNT(*), 2) AS cancel_rate_pct
FROM orders;
[!TIP] 💡 Why this beats running four separate queries: the table is read once. Four
SELECT COUNT(*) … WHEREstatements read it four times. On a large table this is a 4x difference, and the results are guaranteed consistent with each other.
③ Pivoting rows into columns
-- ✅ Works in BOTH: units sold per month, as columns
SELECT
p.product_name,
SUM(CASE WHEN MONTH(o.order_date) = 1 THEN oi.quantity ELSE 0 END) AS jan_units,
SUM(CASE WHEN MONTH(o.order_date) = 2 THEN oi.quantity ELSE 0 END) AS feb_units,
SUM(CASE WHEN MONTH(o.order_date) = 3 THEN oi.quantity ELSE 0 END) AS mar_units
FROM products p
JOIN order_items oi ON oi.product_id = p.product_id
JOIN orders o ON o.order_id = oi.order_id
WHERE YEAR(o.order_date) = 2026
GROUP BY p.product_name
ORDER BY p.product_name;
④ Custom sort order — covered in Chapter 16.
⑤ Safe division
SELECT
product_name,
CASE WHEN reorder_level = 0 THEN NULL
ELSE ROUND(1.0 * units_in_stock / reorder_level, 2)
END AS stock_ratio
FROM products;
24.4 🧠 CASE in every clause
-- In SELECT ✅ (shown above)
-- In WHERE
SELECT * FROM products
WHERE CASE WHEN discontinued = 1 THEN 0 ELSE units_in_stock END < 10;
-- In ORDER BY
SELECT order_id, status, order_date
FROM orders
ORDER BY CASE WHEN status = 'Pending' THEN 0 ELSE 1 END, order_date;
-- In GROUP BY
SELECT
CASE WHEN unit_price >= 500 THEN 'Expensive' ELSE 'Affordable' END AS band,
COUNT(*) AS product_count
FROM products
GROUP BY CASE WHEN unit_price >= 500 THEN 'Expensive' ELSE 'Affordable' END;
-- In UPDATE ✅ (shown in Chapter 18)
-- In HAVING, in JOIN conditions, in CHECK constraints — CASE goes everywhere.
🔀 MySQL convenience: MySQL lets you
GROUP BYthe alias (GROUP BY band), so you do not have to repeat the expression. MSSQL does not — repeat it, or wrap the query in a CTE (Chapter 31).
24.5 🎯 When to use CASE
| You need to… | Use |
|---|---|
| Turn values into human labels | CASE in SELECT |
| Bucket numbers into bands (Premium / Mid / Budget) | Searched CASE |
| Count several different things in one pass | SUM(CASE WHEN … THEN 1 ELSE 0 END) |
| Turn rows into columns | SUM(CASE WHEN month = n …) |
| Sort by business priority, not alphabetically | CASE in ORDER BY |
Set different values per row in one UPDATE |
CASE in SET |
| Avoid divide-by-zero | CASE WHEN d = 0 THEN NULL ELSE n/d END or NULLIF |
| Just pick between two values | IIF 🟥 / IF 🟦 for quick work — CASE for code you keep |
[!CAUTION] 🐛 Common mistake: omitting
ELSE. ACASEwith no matching branch returnsNULL. In aSELECTthat is merely confusing; in anUPDATE ... SET col = CASE ...it wipes the column to NULL for every unmatched row. Always write an explicitELSE, even if it isELSE colmeaning “leave it alone”.
24.6 🧪 Try it yourself
- Classify every customer as
DomesticorInternationalbased on country. - In one query, count orders by status and show each status as a percentage of the total.
- Build a table showing units sold per quarter as four columns.
- Categorise products into stock levels:
Out,Critical(below reorder),Low(below 2× reorder),Healthy.
🧭 In practice — conditional logic
How to use it. Use
CASE WHEN condition THEN result ... ELSE default END— it works in both engines and almost anywhere an expression is allowed: theSELECTlist,ORDER BY,GROUP BY, even inside aggregates. The shorthandsIIF(SQL Server) andIF(MySQL) handle simple two-way choices. Expected result: business categories computed in the query, without a temporary table or application loop.When to use it. Labelling and bucketing (“Gold / Silver / Bronze”), custom sort priorities, and conditional aggregation — counting or summing only the rows that meet a condition, all in one pass.
Where to use it. Reporting. Scenario: one query returns paid, pending, and cancelled totals as three columns, using
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END)three times. WithoutCASEthat is three separate queries and three table scans.When not to use it. Avoid long
CASEladders encoding business rules that change often — those belong in a lookup table you can edit without a deployment.CASEis also the wrong tool for choosing between whole queries; that is dynamic SQL (Chapter 59) or simply separate statements.Best practices. Always include an
ELSE. Without one, unmatched rows silently becomeNULL, and aNULLflowing into aSUMor a comparison is exactly the kind of bug that surfaces as a slightly wrong total nobody can explain. Prefer portableCASEtoIIF/IFin anything that might move between engines, and rememberCASEevaluates in order and stops at the first match — so put the most specific conditions first.
| Part index | Prerequisites | Previous | Next | Full course |