Developer Guides, Cheat Sheets & Tools

SQL course - Part 3: WORKING WITH DATA (CRUD)

Part index Prerequisites Previous Next Full course

๐Ÿ“ฅ PART 3 โ€” WORKING WITH DATA (CRUD)

CRUD = Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE). These four verbs are 95% of the SQL written in the world.


12. INSERT, putting data in

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 20 min Add one row or many ยท Copy rows from another table ยท Avoid inserting duplicates ยท Load data from a file

[!NOTE] ๐Ÿ“Œ In plain words: INSERT adds new rows to a table. That is the whole idea โ€” but there are five useful variations worth knowing.

๐ŸŒ Analogy: Adding new cards to a card index box. You can add one card, a whole stack at once, or photocopy cards from another box.

12.1 โœ๏ธ The basic INSERT

-- โœ… Works in BOTH: always list your columns explicitly
INSERT INTO categories (category_name, description)
VALUES ('Gaming', 'Consoles, controllers, and gaming accessories');
-- โš ๏ธ ๐ŸŸฅ MSSQL: works (the IDENTITY column is skipped), but NEVER do this in real code
INSERT INTO categories VALUES ('Wearables', 'Smartwatches and fitness bands');
-- โš ๏ธ ๐ŸŸฆ MySQL: every column must be supplied, even the AUTO_INCREMENT one (NULL = generate it)
INSERT INTO categories VALUES (NULL, 'Wearables', 'Smartwatches and fitness bands');

[!WARNING] โš ๏ธ Why leaving out the column list is dangerous: it depends on column order. The day someone adds a column in the middle, every one of these statements silently writes data into the wrong column, or fails at 3 a.m. Always name your columns. It costs 10 seconds and prevents a whole family of failures on live systems.

12.2 ๐Ÿ“ฆ Inserting multiple rows at once

๐Ÿ’ก Why one multi-row INSERT beats three single-row ones: each separate statement is its own round trip to the server and, under autocommit, its own transaction โ€” with its own log flush. One statement means one round trip and one commit. The gap is negligible for three rows and large for thousands; it grows with network latency and with how durable your commit settings are.

-- โœ… Works in BOTH โ€” and it is one round trip instead of three
INSERT INTO categories (category_name, description) VALUES
('Cameras',     'Action cameras and camcorders'),
('Networking',  'Routers, switches, cables'),
('Accessories', 'Bags, stands, adapters');

[!TIP] ๐Ÿ’ก Pro tip: A single multi-row insert is one round trip (one message to the server and one reply) and one transaction. A thousand separate inserts are a thousand round trips. On a remote server, the difference is often 50x. When loading data, batch your inserts in groups of 500 to 1000 rows.

12.3 ๐Ÿ“‹ INSERT โ€ฆ SELECT โ€” copying data between tables

This is where INSERT becomes genuinely powerful.

-- โœ… Works in BOTH
-- Real-world task: archive every delivered order from before July 2026
CREATE TABLE orders_archive (
    order_id     INT PRIMARY KEY,
    customer_id  INT NOT NULL,
    order_date   DATE NOT NULL,
    status       VARCHAR(20) NOT NULL
);

INSERT INTO orders_archive (order_id, customer_id, order_date, status)
SELECT order_id, customer_id, order_date, status
FROM orders
WHERE status = 'Delivered'
  AND order_date < '2026-07-01';

The next example uses JOIN, SUM, and GROUP BY, which you will meet in Chapters 25โ€“28. For now, just notice the shape: the SELECT produces rows, and INSERT saves them into the new table.

-- Real-world task: create a VIP list from an aggregate query
CREATE TABLE vip_customers (
    customer_id  INT PRIMARY KEY,
    full_name    VARCHAR(100) NOT NULL,
    lifetime_spend DECIMAL(12,2) NOT NULL
);

INSERT INTO vip_customers (customer_id, full_name, lifetime_spend)
SELECT
    c.customer_id,
    c.full_name,
    SUM(oi.unit_price * oi.quantity * (1 - oi.discount))
FROM customers c
JOIN orders      o  ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY c.customer_id, c.full_name
HAVING SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) > 2000;

12.4 ๐Ÿšซ Inserting only rows that do not already exist

WHERE NOT EXISTS (โ€ฆ) means โ€œonly if no such row is foundโ€ (Chapter 30 explains it fully):

-- โœ… Works in BOTH: the NOT EXISTS guard
INSERT INTO categories (category_name, description)
SELECT 'Gaming', 'Consoles and accessories'
WHERE NOT EXISTS (
    SELECT 1 FROM categories WHERE category_name = 'Gaming'
);
-- ๐ŸŸฆ MySQL shortcuts
INSERT IGNORE INTO categories (category_name, description)
VALUES ('Gaming', 'Consoles and accessories');
-- Silently skips rows that would violate a unique key

INSERT INTO categories (category_name, description)
VALUES ('Gaming', 'Consoles and accessories') AS new
ON DUPLICATE KEY UPDATE description = new.description;
-- Insert, or update if it already exists (a true UPSERT โ€” see Chapter 44)

[!WARNING] โš ๏ธ Be careful with INSERT IGNORE. It hides every error it can, not just duplicates โ€” including text being cut short to fit. A row can end up saved with silently damaged values. Prefer ON DUPLICATE KEY UPDATE or an explicit NOT EXISTS guard.

12.5 ๐ŸŽฏ Capturing what was inserted

-- ๐ŸŸฅ MSSQL: OUTPUT gives you the inserted rows back, even for many rows
INSERT INTO customers (full_name, email, country)
OUTPUT inserted.customer_id, inserted.full_name, inserted.signup_date
VALUES ('New Person', 'new.person@example.com', 'Canada');

-- Or capture them into a table for further processing
DECLARE @new_rows TABLE (customer_id INT, email NVARCHAR(150));

INSERT INTO customers (full_name, email, country)
OUTPUT inserted.customer_id, inserted.email INTO @new_rows
VALUES ('A', 'a@example.com', 'UK'), ('B', 'b@example.com', 'UK');

SELECT * FROM @new_rows;
-- ๐ŸŸฆ MySQL: LAST_INSERT_ID()
INSERT INTO customers (full_name, email, country)
VALUES ('New Person', 'new.person@example.com', 'Canada');

SELECT LAST_INSERT_ID() AS new_customer_id;

12.6 ๐Ÿšš Bulk loading large files

[!NOTE] ๐Ÿ“Œ What a staging table is: a table shaped like your incoming file, usually without business keys or relationship checks. SQL data types and column lengths still apply. Typed staging accepts already parseable fields; a separate wide text landing table is needed to preserve malformed input for later conversion. Several later chapters use these, so create them once now:

-- โœ… Works in BOTH: the staging tables used in Chapters 12, 19, 23 and 44
-- No business constraints/indexes/FKs, but the declared data types and lengths
-- still reject or convert malformed input according to the engine/load mode.
-- These typed tables require valid numeric/date fields and bounded text.

CREATE TABLE staging_products (
    product_name    VARCHAR(120),
    category_id     INT,
    supplier_id     INT,
    unit_price      DECIMAL(10,2),
    units_in_stock  INT
);

CREATE TABLE staging_orders (
    order_id     INT,
    customer_id  INT,
    order_date   DATE,
    status       VARCHAR(20)
);

CREATE TABLE staging_customers (
    customer_code  VARCHAR(50),      -- may contain junk like 'ABC123'
    full_name      VARCHAR(100),
    email          VARCHAR(150)
);

[!TIP] ๐Ÿ’ก Why no constraints on a staging table? Avoiding business constraints lets you inspect duplicates and missing relationships before accepting rows. It does not make typed staging accept arbitrary input: bad numbers/dates and overlong text can still fail or be converted. To retain original values, load into wide text columns first, keep rejected records, then validate and convert into typed staging. Loader error/strict-mode settings also matter.

Loading a file. The next two examples load a CSV file โ€” a spreadsheet saved as plain text, with commas between the values (in Excel: File โ†’ Save As โ†’ CSV).

[!WARNING] โš ๏ธ Before you run them: create the file first, with a header row and these five columns in this order: product_name,category_id,supplier_id,unit_price,units_in_stock. The path is a path on the database serverโ€™s computer โ€” for a Docker or remote server, the file must be copied there. Without the file you will simply get โ€œfile does not existโ€.

-- ๐ŸŸฅ MSSQL
BULK INSERT staging_products
FROM 'C:\data\products.csv'
WITH (
    FORMAT = 'CSV',
    FIRSTROW = 2,              -- skip the header
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n',
    TABLOCK                    -- locks the table while loading: much faster
);
-- ๐ŸŸฆ MySQL
LOAD DATA INFILE '/var/lib/mysql-files/products.csv'
INTO TABLE staging_products
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(product_name, category_id, supplier_id, unit_price, units_in_stock);

[!TIP] ๐Ÿ’ก Pro tip for loading millions of rows: load into a staging table with no indexes and no constraints, clean the data there, then insert into the real table. Indexes make inserts slower; adding them once after the load is far faster than maintaining them during it.

[!WARNING] โš ๏ธ MySQL LOAD DATA INFILE and the secure_file_priv setting: by default MySQL only reads files from one specific directory. Check it with SHOW VARIABLES LIKE 'secure_file_priv';. Use LOAD DATA LOCAL INFILE to read from the client machine instead, if the server permits it.

12.7 ๐Ÿ› The four INSERT errors you will definitely hit

Error Cause Fix
Cannot insert NULL into column X A NOT NULL column got no value Supply a value or add a DEFAULT
Violation of UNIQUE KEY constraint The value already exists Check first, or use an upsert (insert-or-update, Chapter 44)
FOREIGN KEY constraint conflict The row it points to (the parent) does not exist Insert the parent row first
String or binary data would be truncated The text is longer than the column Widen the column or shorten the data

[!TIP] ๐Ÿ’ก MSSQL 2019+ gives a much better truncation message naming the exact table, column, and value. If you are on an older version, find the culprit yourself:

-- ๐ŸŸฅ MSSQL
-- Use a wider raw landing table, NOT staging_products whose name is VARCHAR(120).
CREATE TABLE raw_staging_products (product_name VARCHAR(1000));
-- Load original names here before truncation/conversion.
SELECT * FROM raw_staging_products WHERE LEN(product_name) > 120;

12.8 ๐Ÿงช Try it yourself

  1. Add three new products to the Gaming category in a single statement.
  2. Copy every Cancelled order into a new cancelled_orders_log table using INSERT ... SELECT.
  3. Deliberately trigger each of the four errors above and read the messages carefully.
  4. Write an insert that only adds the category 'Audio' if it does not already exist. Run it twice; confirm nothing changes the second time.

๐Ÿงญ In practice โ€” INSERT

How to use it. Write INSERT INTO table (column_list) VALUES (...), always naming the columns. Insert several rows in one statement by listing several VALUES tuples โ€” far faster than one statement per row. Use INSERT ... SELECT to copy rows from a query. Expected result: the engine reports the number of rows inserted, and any constraint violation rejects the whole statement.

When to use it. Whenever data enters the database: a new customer signs up, an order is placed, a nightly file is loaded.

Where to use it. Application code and data-loading jobs. Scenario: importing 50,000 products from a supplier feed. Batching 1,000 rows per INSERT instead of 50,000 single-row statements turns a job that takes minutes into one that takes seconds, because each statement carries its own round trip and transaction overhead.

When not to use it. Do not use INSERT row-by-row in a loop for bulk loading โ€” use multi-row VALUES, INSERT ... SELECT, or a bulk-load tool (BULK INSERT, bcp, LOAD DATA INFILE). And never build an INSERT by concatenating user input into a string; that is SQL injection (Chapter 55). Parameterise, always.

Best practices. Always list the column names explicitly. INSERT INTO products VALUES (...) depends on column order, so the day someone adds a column, every such statement silently writes the wrong values into the wrong columns. Let auto-numbered keys assign themselves rather than supplying them, and wrap multi-table inserts in a transaction so a half-finished order cannot exist.


13. SELECT, the heart of SQL

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 20 min Read chosen columns and rows ยท Rename result columns ยท Calculate new values ยท Remove duplicate rows

[!NOTE] ๐Ÿ“Œ In plain words: SELECT asks the database a question and gets a table of rows back. You will write more SELECT statements in your career than every other command combined.

๐ŸŒ Analogy: Asking a librarian: โ€œBring me the title and author of every book about cooking.โ€ You say which details you want (the columns) and from where (the table); the librarian brings back a neat list. Nothing on the shelves changes.

13.1 ๐ŸŒฑ The simplest possible queries

-- โœ… Works in BOTH

-- Every column, every row
SELECT * FROM customers;

-- Only the columns you need
SELECT full_name, email, city FROM customers;

-- SELECT does not even need a table
SELECT 1 + 1 AS answer;
SELECT 'Hello, SQL' AS greeting;

[!WARNING] โš ๏ธ SELECT * is fine while exploring, and a bad habit in real code. Here is why:

  1. It moves columns you do not need across the network โ€” sometimes megabytes of TEXT.
  2. It stops the database using some of its fastest shortcuts (covering indexes, Chapter 46), so it reads far more data than it needs.
  3. Your app breaks in a new way when someone adds or reorders a column.
  4. It hides your actual intent from the next reader.

In real applications, name your columns.

[!IMPORTANT] ๐ŸŽฏ When SELECT * IS acceptable:

  • Exploring a table you have never seen, interactively
  • EXISTS (SELECT * FROM ...) โ€” the column list is ignored entirely
  • INSERT INTO archive SELECT * FROM source where the two tables are deliberately identical
  • Quick one-off checks you will never save

Everywhere else โ€” application code, views, stored procedures, reports โ€” name the columns.

13.2 ๐Ÿท๏ธ Aliases โ€” renaming columns and tables

-- โœ… Works in BOTH: column aliases with AS (AS is optional but clearer)
SELECT
    full_name    AS customer_name,
    email        AS contact_email,
    signup_date  AS joined_on
FROM customers;

-- Aliases with spaces or special characters
SELECT full_name AS "Customer Name" FROM customers;   -- โœ… both engines
-- ๐ŸŸฅ MSSQL also allows square brackets, and an alternative = form
SELECT full_name AS [Customer Name] FROM customers;
SELECT [Customer Name] = full_name FROM customers;
-- โœ… Works in BOTH: table aliases keep long queries readable
SELECT
    c.full_name,
    o.order_id,
    o.order_date
FROM customers AS c
JOIN orders    AS o ON o.customer_id = c.customer_id;

[!TIP] ๐Ÿ’ก Pro tip: Use short, meaningful table aliases (c for customers, oi for order_items), and use them the same way in all of your code. Never use a, b, c โ€” after three joins nobody, including you, knows what b was.

13.3 ๐Ÿงฎ Computed columns and expressions

An expression is a calculation, such as unit_price * quantity. The database works it out separately for every row and shows the answer as a new column.

-- โœ… Works in BOTH
-- Real-world task: show the true line total after discount
SELECT
    order_id,
    product_id,
    unit_price,
    quantity,
    discount,
    unit_price * quantity                       AS gross_amount,
    unit_price * quantity * (1 - discount)      AS net_amount,
    unit_price * quantity * discount            AS discount_amount
FROM order_items
WHERE order_id = 1002;

String building differs between engines:

-- ๐ŸŸฅ MSSQL: + concatenates strings
SELECT full_name + ' <' + email + '>' AS contact FROM customers;
-- ๐ŸŸฆ MySQL: + is ARITHMETIC. 'abc' + 'def' = 0 !
SELECT CONCAT(full_name, ' <', email, '>') AS contact FROM customers;
-- โœ… CONCAT works in BOTH โ€” use it and forget the difference
SELECT CONCAT(full_name, ' <', email, '>') AS contact FROM customers;

[!CAUTION] ๐Ÿ› Common mistake: A developer moving from MSSQL to MySQL writes first_name + ' ' + last_name and gets 0 for every row. MySQL converted the strings to numbers and added them. CONCAT() is the answer that works in both engines.

13.4 โ™ป๏ธ DISTINCT โ€” removing duplicates

-- โœ… Works in BOTH

-- Which countries do our customers come from?
SELECT DISTINCT country FROM customers ORDER BY country;

-- DISTINCT applies to the WHOLE row, not one column
SELECT DISTINCT country, city FROM customers ORDER BY country, city;

-- Count how many distinct countries
SELECT COUNT(DISTINCT country) AS country_count FROM customers;

[!WARNING] โš ๏ธ DISTINCT is often a symptom, not a solution. If you added DISTINCT because your join suddenly produced duplicate rows, the real problem is the join (Chapter 28) โ€” usually a missing condition, or one row matching many rows in the other table. DISTINCT hides the problem and makes the database do an expensive sort. Fix the join instead. See Chapter 28.

13.5 ๐ŸŽฉ Useful SELECT tricks

-- โœ… Works in BOTH

-- A fixed text column โ€” handy for labelling rows when you combine two results (Chapter 29)
SELECT full_name, 'customer' AS record_type FROM customers;

-- Check structure quickly without reading data
SELECT * FROM orders WHERE 1 = 0;    -- returns column headers, zero rows

-- ๐ŸŸฆ MySQL: test an expression with no table at all
SELECT CONCAT('Total: ', CAST(1499.00 * 2 AS CHAR)) AS demo;

-- ๐ŸŸฅ MSSQL: the same test (MySQL has no VARCHAR target for CAST)
SELECT CONCAT('Total: ', CAST(1499.00 * 2 AS VARCHAR(20))) AS demo;

13.6 ๐Ÿงช Try it yourself

  1. List every product with its name, price, and the price including 15% tax, aliased clearly.
  2. Produce a single column label reading UltraBook Pro 14 โ€” $1499.00 for every product.
  3. Find how many distinct cities your customers live in.
  4. List the distinct combinations of status and shipping_country from orders.

๐Ÿงญ In practice โ€” SELECT

How to use it. Name the columns you want, then FROM the table. Rename output columns with AS, remove duplicate rows with DISTINCT, and compute values with expressions (unit_price * 1.15). Expected result: a result set โ€” rows and columns โ€” which is what every later feature in this guide filters, groups, joins, or ranks.

When to use it. Constantly. SELECT is the statement you will write more than all the others combined.

Where to use it. Everywhere: application queries, reports, ad-hoc investigation, and the source of every INSERT ... SELECT and view. Scenario: a support agent asks โ€œwhat did customer 7 order in March?โ€ That is a SELECT with a filter and a join โ€” and it is the shape of most real work.

When not to use it. Avoid SELECT * in anything you save โ€” application code, views, stored procedures. It fetches columns nobody needs (which costs network and memory), breaks the moment a column is added or reordered, and hides which columns the query actually depends on. SELECT * is fine while exploring interactively.

Best practices. Treat DISTINCT as a symptom rather than a fix: if a join suddenly produced duplicates, the join is wrong, and DISTINCT hides the bug while adding an expensive sort. Name computed columns with AS so the result is self-describing. Remember that a SELECT with no ORDER BY has no guaranteed row order, however stable it looks in testing.


14. WHERE, asking precise questions

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 25 min Filter rows with conditions ยท Combine AND and OR safely ยท Filter date ranges correctly ยท Search text with patterns

[!NOTE] ๐Ÿ“Œ In plain words: WHERE is the filter. It looks at every candidate row and asks a yes/no question. Only the rows that answer yes survive.

๐ŸŒ Analogy: WHERE is the bouncer with a guest list. Every row walks up; the bouncer checks the condition; the row gets in or is turned away.

14.1 โš–๏ธ Comparison operators

Operator Meaning Example
= Equal to WHERE country = 'UK'
<> or != Not equal to WHERE status <> 'Cancelled'
> < Greater / less than WHERE unit_price > 500
>= <= Greater/less than or equal WHERE units_in_stock <= 10
BETWEEN a AND b Between two values, including both ends WHERE unit_price BETWEEN 100 AND 500
IN (โ€ฆ) Matches any value in a list WHERE country IN ('UK','Germany','Italy')
LIKE Matches a text pattern WHERE email LIKE '%@example.com'
IS NULL Has no value WHERE ship_date IS NULL
EXISTS (โ€ฆ) Another query finds at least one row See Chapter 30
-- โœ… Works in BOTH โ€” real business questions

-- Which products are expensive?
SELECT product_name, unit_price
FROM products
WHERE unit_price > 500;

-- Which orders have not shipped yet?
SELECT order_id, order_date, status
FROM orders
WHERE ship_date IS NULL;

-- Which products are low on stock and still being sold?
SELECT product_name, units_in_stock, reorder_level
FROM products
WHERE units_in_stock <= reorder_level      -- comparing two COLUMNS
  AND discontinued = 0;

[!TIP] ๐Ÿ’ก Note that last one. WHERE conditions can compare two columns of the same row, not just a column against a constant. units_in_stock <= reorder_level is a genuine business rule โ€” โ€œtime to reorderโ€ โ€” expressed in one line.

14.2 ๐Ÿ”— AND, OR, NOT, and the parentheses trap

-- โœ… Works in BOTH
SELECT product_name, unit_price, category_id
FROM products
WHERE category_id = 1
  AND unit_price > 1000
  AND discontinued = 0;

[!WARNING] โš ๏ธ The single most common WHERE bug in the world: SQL works out AND before OR โ€” just as maths works out ร— before +. Without parentheses, this happens:

-- โŒ WRONG: reads as "category 1" OR "(category 2 AND price > 1000)"
SELECT * FROM products
WHERE category_id = 1 OR category_id = 2 AND unit_price > 1000;
-- Returns ALL of category 1, at any price. Not what anyone meant.

-- โœ… RIGHT
SELECT * FROM products
WHERE (category_id = 1 OR category_id = 2)
  AND unit_price > 1000;

[!TIP] ๐Ÿ’ก Pro tip: When a WHERE clause mixes AND and OR, always use parentheses, even when you are sure they are unnecessary. They cost nothing and they document your intent to the next reader.

14.3 ๐Ÿ“ BETWEEN โ€” and its date trap

-- โœ… Works in BOTH: BETWEEN is INCLUSIVE on both ends
SELECT product_name, unit_price
FROM products
WHERE unit_price BETWEEN 100 AND 200;      -- includes exactly 100 and exactly 200

-- Identical to:
SELECT product_name, unit_price FROM products
WHERE unit_price >= 100 AND unit_price <= 200;

-- Exclude a range
SELECT product_name, unit_price FROM products
WHERE unit_price NOT BETWEEN 100 AND 200;

[!WARNING] โš ๏ธ The date-range trap that silently loses data. If a column is DATETIME, this query misses almost the entire last day:

-- โŒ WRONG for DATETIME columns:
--    '2026-01-31' means '2026-01-31 00:00:00', so a payment at
--    09:15 on the 31st is EXCLUDED.
SELECT payment_id, payment_date, amount FROM payments
WHERE payment_date BETWEEN '2026-01-01' AND '2026-01-31';
-- โœ… RIGHT: the half-open range. Works for DATE and DATETIME alike.
SELECT payment_id, payment_date, amount FROM payments
WHERE payment_date >= '2026-01-01'
  AND payment_date <  '2026-02-01';

[!TIP] ๐Ÿ’ก Learn the half-open pattern >= start AND < next_start (the start is included, the end is not) and use it for every date range for the rest of your life. It is correct regardless of the columnโ€™s precision, it never needs adjusting for leap years or month lengths, and โ€” crucially โ€” it is SARGable, meaning an index on the date column can still be used. See Chapter 48.

14.4 ๐Ÿ“‹ IN and NOT IN

-- โœ… Works in BOTH
SELECT full_name, country
FROM customers
WHERE country IN ('UK', 'Germany', 'Italy', 'Spain');

-- Identical to, but far more readable than:
SELECT full_name, country FROM customers
WHERE country = 'UK' OR country = 'Germany' OR country = 'Italy' OR country = 'Spain';

-- IN with a subquery: customers who have actually ordered something
SELECT full_name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);

[!WARNING] โš ๏ธ NOT IN breaks silently when the list contains NULL. This is one of SQLโ€™s genuinely surprising behaviours:

-- โŒ Returns ZERO rows if ANY order has a NULL employee_id
SELECT first_name FROM employees
WHERE employee_id NOT IN (SELECT employee_id FROM orders);

Why: x NOT IN (1, 2, NULL) expands to x <> 1 AND x <> 2 AND x <> NULL. That last comparison is UNKNOWN (see Chapter 15), never TRUE, so the whole condition can never be true. Silence, no error, no rows.

-- โœ… FIX 1: exclude the NULLs
SELECT first_name FROM employees
WHERE employee_id NOT IN (SELECT employee_id FROM orders WHERE employee_id IS NOT NULL);

-- โœ… FIX 2 (better): use NOT EXISTS, which is immune to this problem
SELECT e.first_name
FROM employees e
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.employee_id = e.employee_id);

[!TIP] ๐Ÿ’ก Professional habit: prefer NOT EXISTS over NOT IN for subqueries, always. It is NULL-safe and usually produces a better execution plan (the step-by-step route the database takes to answer โ€” Chapter 47).

14.5 ๐Ÿ” LIKE and pattern matching

Wildcard Meaning Example Matches
% Any number of characters (including none) 'A%' Amara, Anna, A
_ Exactly one character '_ohn' John, Bohn
[abc] ๐ŸŸฅ One character from the set (MSSQL only) '[JM]%' John, Mei
[a-f] ๐ŸŸฅ One character from the range (MSSQL only) '[A-C]%' Amara, Bob, Carlos
[^abc] ๐ŸŸฅ One character NOT in the set (MSSQL only) '[^A]%' anything not starting with A
-- โœ… Works in BOTH
SELECT full_name FROM customers WHERE full_name LIKE 'A%';        -- starts with A
SELECT full_name FROM customers WHERE full_name LIKE '%Silva';    -- ends with Silva
SELECT full_name FROM customers WHERE full_name LIKE '%ei%';      -- contains "ei"
SELECT email     FROM customers WHERE email LIKE '%@example.com'; -- domain match
SELECT phone     FROM customers WHERE phone LIKE '+94%';          -- Sri Lankan numbers
-- ๐ŸŸฅ MSSQL only: character classes
SELECT full_name FROM customers WHERE full_name LIKE '[A-C]%';
SELECT full_name FROM customers WHERE full_name LIKE '[^AJ]%';
-- ๐ŸŸฆ MySQL only: regular expressions (a powerful pattern language)
SELECT full_name FROM customers WHERE full_name REGEXP '^[A-C]';
SELECT email     FROM customers WHERE email REGEXP '^[a-z]+\\.[a-z]+@';

Searching for a literal % or _:

-- โœ… Works in BOTH: define an escape character
SELECT * FROM products WHERE product_name LIKE '%50!%%' ESCAPE '!';
-- finds names containing the literal text "50%"

[!WARNING] โš ๏ธ Performance warning: a leading wildcard kills your index. LIKE 'Ultra%' can use an index on product_name โ€” the engine jumps straight to the โ€œUltraโ€ section, like finding a word in a dictionary. LIKE '%Book%' cannot โ€” the engine must read every single row. On a million-row table that is the difference between 2 milliseconds and 4 seconds.

If you genuinely need โ€œcontainsโ€ search on a large table, use full-text search instead (Chapter 58).

๐Ÿ”€ Case sensitivity differs by default:

  • MSSQLโ€™s default collation (its rules for comparing text โ€” Chapter 60) is case-insensitive: LIKE 'a%' matches โ€œAmaraโ€.
  • MySQL with a _ci collation is also case-insensitive; with _bin or _cs it is case-sensitive.
  • To force case-sensitivity: MSSQL COLLATE Latin1_General_CS_AS, MySQL LIKE BINARY 'a%'.

14.6 ๐Ÿงช Try it yourself

  1. Find every product priced between 100 and 400 that is not discontinued.
  2. Find all customers whose email is at example.com and who live outside the UK.
  3. Find every order placed in March 2026, using the half-open date pattern.
  4. Find the products whose name contains the word โ€œProโ€. Then check whether an index could help โ€” why not?
  5. Deliberately write a WHERE mixing AND and OR without parentheses and count how the row count changes when you add them.

๐Ÿงญ In practice โ€” WHERE

How to use it. Add WHERE condition to keep only matching rows. Combine conditions with AND/OR and parenthesise whenever you mix them. Use BETWEEN for ranges, IN for lists, and LIKE for patterns. Expected result: the row count drops to exactly the rows you meant โ€” which you should check before you use the same WHERE in an UPDATE or DELETE.

When to use it. On essentially every query against a real table. A query with no WHERE reads everything, which is fine for 18 products and catastrophic for 18 million orders.

Where to use it. Everywhere, and especially as a safety rehearsal. Scenario: before running DELETE FROM orders WHERE status = 'cancelled', run SELECT COUNT(*) FROM orders WHERE status = 'cancelled' with the identical WHERE. If the number surprises you, you have just avoided an incident.

When not to use it. Avoid wrapping the filtered column in a function โ€” WHERE YEAR(order_date) = 2026 cannot use an index on order_date, so the engine reads every row. Write WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01' instead. That property is called SARGability and it is covered in Chapter 48. Avoid leading-wildcard LIKE '%phone' for the same reason.

Best practices. Mind operator precedence: AND binds tighter than OR, so WHERE a = 1 OR a = 2 AND b = 3 does not mean what most people read it as. Parenthesise. Compare values of the same type so the engine does not have to convert a whole column โ€” an implicit conversion silently disables an index and can raise errors, as ยง23.3 demonstrates.


15. NULL, the value that is not there

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 20 min Explain what NULL really means ยท Test for NULL correctly ยท Replace missing values ยท Avoid the NOT IN trap

[!NOTE] ๐Ÿ“Œ In plain words: NULL does not mean zero. It does not mean an empty string. It means โ€œwe do not knowโ€ or โ€œthis does not apply.โ€ And unknown values behave in ways that surprise everyone the first time.

๐ŸŒ Analogy: You have two sealed boxes. Are their contents equal? You cannot say yes. You cannot say no. The honest answer is โ€œunknown.โ€ That is exactly what NULL = NULL returns.

15.1 ๐Ÿ’ฅ The three golden rules of NULL

-- RULE 1: NULL is never equal to anything, not even to itself.
SELECT * FROM orders WHERE ship_date = NULL;      -- โŒ returns ZERO rows, always
SELECT * FROM orders WHERE ship_date IS NULL;     -- โœ… this is the correct way

-- RULE 2: Any arithmetic with NULL produces NULL.
SELECT 100 + NULL;        -- NULL, not 100
SELECT NULL * 5;          -- NULL
SELECT CONCAT('a', NULL); -- ๐ŸŸฆ MySQL: NULL   ๐ŸŸฅ MSSQL CONCAT(): 'a' (it ignores NULLs)

-- RULE 3: Comparisons with NULL are UNKNOWN, which is not TRUE.
SELECT * FROM products WHERE unit_price > NULL;   -- zero rows
SELECT * FROM products WHERE unit_price <> NULL;  -- zero rows

SQL uses three-valued logic โ€” TRUE, FALSE, and UNKNOWN:

A B A AND B A OR B
TRUE UNKNOWN UNKNOWN TRUE
FALSE UNKNOWN FALSE UNKNOWN
UNKNOWN UNKNOWN UNKNOWN UNKNOWN

[!CAUTION] ๐Ÿ› The classic bug this causes: you want โ€œall orders except cancelled ones.โ€

SELECT * FROM orders WHERE status <> 'Cancelled';

If status allowed NULL, every row with a NULL status disappears from the result โ€” silently. The user reports โ€œsome orders are missingโ€ and you spend a day hunting.

-- โœ… The NULL-safe version
SELECT * FROM orders WHERE status <> 'Cancelled' OR status IS NULL;

15.2 ๐Ÿงฐ The NULL-handling toolkit

Function ๐ŸŸฅ MSSQL ๐ŸŸฆ MySQL What it does
Replace NULL with a value ISNULL(x, 0) IFNULL(x, 0) Two arguments only
First non-NULL of many COALESCE(a,b,c) COALESCE(a,b,c) โœ… Standard, works in both
NULL if two values match NULLIF(a, b) NULLIF(a, b) โœ… Works in both
Equality that treats two NULLs as equal (use IS NULL logic) a <=> b MySQL only
-- โœ… COALESCE works in BOTH โ€” prefer it over ISNULL/IFNULL so your SQL runs in either engine

-- Real-world: show a friendly status for unshipped orders
SELECT
    order_id,
    order_date,
    COALESCE(CAST(ship_date AS CHAR(10)), 'Not shipped yet') AS ship_status
FROM orders;

-- Real-world: fall back through several contact options
SELECT
    full_name,
    COALESCE(phone, email, 'No contact on file') AS best_contact
FROM customers;

-- Real-world: prevent division by zero using NULLIF
SELECT
    product_name,
    units_in_stock,
    reorder_level,
    units_in_stock / NULLIF(reorder_level, 0) AS stock_ratio   -- NULL instead of an error
FROM products;

[!TIP] ๐Ÿ’ก The NULLIF divide-by-zero trick is worth memorizing. x / NULLIF(y, 0) turns a hard error into a NULL, which you can then handle with COALESCE. Combined: COALESCE(x / NULLIF(y,0), 0).

๐Ÿ”€ A subtle MSSQL difference: ISNULL returns the data type of its first argument, so ISNULL(CAST(x AS VARCHAR(5)), 'Not available') silently truncates to 'Not a'. COALESCE picks a type big enough for all of its values, so it does not do this. Another reason to prefer COALESCE.

15.3 ๐Ÿ“Š How NULL behaves in aggregates, sorting, and grouping

-- โœ… Works in BOTH: aggregates IGNORE NULLs. This surprises everyone once.
-- 5 employees, 2 with NULL commission:
CREATE TABLE employees_demo (
    employee_id INT PRIMARY KEY,
    commission  DECIMAL(10,2) NULL
);
INSERT INTO employees_demo VALUES (1, 100.00), (2, 200.00), (3, 300.00), (4, NULL), (5, NULL);

SELECT
    COUNT(*)              AS all_rows,          -- 5
    COUNT(commission)     AS non_null_values,   -- 3
    AVG(commission)       AS avg_of_3_not_5,    -- divides by 3, NOT 5!
    SUM(commission)       AS sum_ignores_nulls
FROM employees_demo;

[!WARNING] โš ๏ธ AVG divides by the count of non-NULL values. If you want NULL to count as zero, say so explicitly: AVG(COALESCE(commission, 0)). These two give different answers and only you know which is correct for the business question.

-- GROUP BY treats all NULLs as ONE group (unlike =, which never matches)
SELECT city, COUNT(*) FROM customers GROUP BY city;
-- Produces one row where city IS NULL

-- DISTINCT also treats NULLs as one value
SELECT DISTINCT city FROM customers;   -- at most one NULL row

๐Ÿ”€ Sort order of NULLs differs:

  • MSSQL: NULL sorts first in ASC.
  • MySQL: NULL sorts first in ASC too, and last in DESC.
  • To control it explicitly, sort by a flag first:
    -- โœ… Works in BOTH: force NULLs to the end regardless of engine
    SELECT order_id, ship_date FROM orders
    ORDER BY CASE WHEN ship_date IS NULL THEN 1 ELSE 0 END, ship_date;
    

15.4 ๐Ÿ•ณ๏ธ NULL vs empty string vs zero

-- These are three completely different things
INSERT INTO customers (full_name, email, country, phone) VALUES
('Test A', 'a@x.com', 'UK', NULL),   -- phone unknown / not provided
('Test B', 'b@x.com', 'UK', ''),     -- phone is an empty string (they gave nothing?)
('Test C', 'c@x.com', 'UK', '0');    -- phone is literally "0"

SELECT full_name, phone FROM customers WHERE phone IS NULL;   -- finds A only
SELECT full_name, phone FROM customers WHERE phone = '';      -- finds B only

[!TIP] ๐Ÿ’ก Pick one convention and enforce it. Most teams choose: use NULL for โ€œno valueโ€, never the empty string. Then add a CHECK (phone <> '') constraint so the empty string can never sneak in. Mixed conventions mean every query needs WHERE phone IS NULL OR phone = '', forever.

๐Ÿ”€ Oracle-style trap for people arriving from Oracle: Oracle treats '' as NULL. MSSQL and MySQL do not. They are genuinely different values.

15.5 ๐ŸŽฏ When to allow NULL, and which tool to reach for

Question Answer
Should this column allow NULL? Only if โ€œunknownโ€ or โ€œnot applicableโ€ is a real business state. ship_date yes; email no.
I need โ€œ0 if missingโ€ COALESCE(x, 0)
I need โ€œfirst thing that has a valueโ€ COALESCE(a, b, c, 'fallback')
I need to avoid divide-by-zero x / NULLIF(y, 0)
I need โ€œis this empty?โ€ IS NULL โ€” never = NULL
I need โ€œeverything except Xโ€, and the column allows NULL WHERE col <> 'X' OR col IS NULL
I need NULLs sorted last ORDER BY CASE WHEN col IS NULL THEN 1 ELSE 0 END, col
Should the average treat missing as zero? Decide explicitly: AVG(col) skips them, AVG(COALESCE(col,0)) counts them

[!CAUTION] ๐Ÿ› Common mistake: using NOT NULL DEFAULT '' or DEFAULT 0 to โ€œavoid the NULL problemโ€. You have not removed the ambiguity, you have hidden it โ€” now you cannot tell โ€œwe asked and they have no phoneโ€ from โ€œwe never askedโ€. A NULL that means something is better than a fake value that means nothing.

15.6 ๐Ÿงช Try it yourself

  1. Count how many orders have no ship_date. Then try it with = NULL and confirm you get zero.
  2. Write a query showing every order with a shipping status of either the date, or the text 'In progress'.
  3. Compute the average discount in order_items two ways: ignoring zeros and treating them as zero. Explain the difference.
  4. Sort orders so that unshipped orders appear last, and shipped ones by date descending.

๐Ÿงญ In practice โ€” NULL

How to use it. Test for it with IS NULL / IS NOT NULL โ€” never = NULL, which is never true. Replace it in output with COALESCE(column, fallback). Expected result: rows with missing values are handled deliberately instead of vanishing from your results without explanation.

When to use it. Every time a column is nullable, which in practice is most of the time โ€” optional phone numbers, unshipped orders, unassigned sales reps.

Where to use it. Filters, joins, and every aggregate report. Scenario: WHERE status <> 'shipped' looks like it returns everything not yet shipped. It silently omits every row where status is NULL, because NULL <> 'shipped' is unknown, not true. The report then understates the backlog, and nobody notices until a customer complains.

When not to use it. Do not use NULL as a stand-in for zero, an empty string, or โ€œfalseโ€. NULL means unknown or not applicable; a stock level of zero is a known fact and should be 0. Conflating them makes SUM and AVG produce results nobody can interpret. And do not use NOT IN with a subquery that might return a NULL โ€” the whole predicate becomes unknown and you get no rows at all; use NOT EXISTS instead.

Best practices. Learn the three-valued logic properly, because it explains a whole class of silent wrong answers: COUNT(*) counts rows while COUNT(column) skips NULLs; AVG ignores NULLs rather than treating them as zero; and NULL sorts differently between the two engines. Make columns NOT NULL with a sensible DEFAULT wherever โ€œunknownโ€ is not a real state โ€” every nullable column is a special case in every query that touches it.


16. ORDER BY, sorting results

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 15 min Sort by one or several columns ยท Build a custom sort order ยท Know why unsorted results are unpredictable

[!NOTE] ๐Ÿ“Œ In plain words: Without ORDER BY, the database returns rows in whatever order is cheapest โ€” which can change between runs, versions, and even from one execution to the next. If order matters, you must say so.

16.1 ๐Ÿ”ค The basics

-- โœ… Works in BOTH
SELECT product_name, unit_price FROM products ORDER BY unit_price;        -- ASC is the default
SELECT product_name, unit_price FROM products ORDER BY unit_price DESC;   -- highest first

-- Multiple sort keys: sort by the first, break ties with the second
SELECT category_id, product_name, unit_price
FROM products
ORDER BY category_id ASC, unit_price DESC;

๐ŸŒ Analogy for multi-column sort: a phone book. Sort by surname first; when two people share a surname, sort those by first name. The second column only matters within a tie of the first.

16.2 ๐ŸŽฏ Sorting by expressions, aliases, and positions

-- โœ… Works in BOTH: by an alias (legal because ORDER BY runs after SELECT)
SELECT product_name, unit_price * 1.15 AS price_with_tax
FROM products
ORDER BY price_with_tax DESC;

-- โš ๏ธ Works in BOTH: by column POSITION โ€” works, but avoid it
SELECT product_name, unit_price FROM products ORDER BY 2 DESC;

-- โœ… ๐ŸŸฅ MSSQL: by an expression not even in the SELECT list (MSSQL uses LEN)
SELECT product_name FROM products ORDER BY LEN(product_name) DESC;
-- โœ… MySQL: same idea, but the length function is CHAR_LENGTH
SELECT product_name FROM products ORDER BY CHAR_LENGTH(product_name) DESC;

[!WARNING] โš ๏ธ Never use ORDER BY 2 in real code. The day someone adds a column to the SELECT list, your sort silently changes to a different column. It is a time bomb.

16.3 ๐ŸŽจ Custom sort order with CASE

A genuinely useful real-world technique: sorting by business priority rather than alphabetically.

-- โœ… Works in BOTH
-- Task: show orders with the most urgent statuses first
SELECT order_id, status, order_date
FROM orders
ORDER BY
    CASE status
        WHEN 'Pending'   THEN 1
        WHEN 'Paid'      THEN 2
        WHEN 'Shipped'   THEN 3
        WHEN 'Delivered' THEN 4
        WHEN 'Refunded'  THEN 5
        WHEN 'Cancelled' THEN 6
        ELSE 99
    END,
    order_date DESC;
-- ๐ŸŸฆ MySQL has a shortcut for exactly this
SELECT order_id, status
FROM orders
ORDER BY FIELD(status, 'Pending','Paid','Shipped','Delivered','Refunded','Cancelled');
-- Put your own country at the top, then everyone else alphabetically
SELECT full_name, country
FROM customers
ORDER BY
    CASE WHEN country = 'Sri Lanka' THEN 0 ELSE 1 END,
    country,
    full_name;

16.4 โš ๏ธ The unordered-result trap

-- โŒ NEVER assume this returns rows in insertion order
SELECT * FROM customers;

[!NOTE] ๐Ÿ“Œ In plain words: A table is a bag of rows, not a list. Rows have no inherent order. What looks like โ€œthe order the rows were addedโ€ today is just luck โ€” the order the database happened to read its storage in. Add an index, upgrade the server, or load more data, and the order can change without warning.

If you need order, write ORDER BY. Every time. No exceptions.

[!WARNING] โš ๏ธ A view (a saved query, Chapter 36) or a subquery with ORDER BY guarantees nothing. In MSSQL, ORDER BY inside a view is only legal alongside TOP/OFFSET, and even then the outer query may reorder the rows. Sorting belongs in the final, outermost query.

16.5 โšก Sorting and performance

Sorting a million rows costs memory and processor time, and when memory runs out the database has to use slow disk space. An index in the right order removes that cost entirely.

-- Without an index, this must read and sort every row
SELECT order_id, order_date FROM orders ORDER BY order_date DESC;

-- With this index, the engine reads the index backwards โ€” no sort at all
CREATE INDEX ix_orders_order_date ON orders(order_date);

[!TIP] ๐Ÿ’ก Pro tip: An index can satisfy an ORDER BY only if the sort direction pattern matches. ORDER BY a ASC, b DESC needs an index defined as (a ASC, b DESC). Both engines support per-column direction in an index definition (MySQL genuinely honours DESC in indexes from 8.0 onward; earlier versions parsed and ignored it).

16.6 ๐ŸŽฏ When to sort โ€” and when not to

Situation Sort?
Final result shown to a human โœ… Always ORDER BY
Paging (OFFSET/LIMIT) โœ… Mandatory โ€” and it must give the same order every time
Inside a subquery or CTE (a named subquery, Chapter 31) feeding an outer query โŒ Wasted work; the outer query decides order
Inside a view โŒ Not guaranteed, and usually illegal without TOP
Before an INSERT ... SELECT โŒ Pointless โ€” tables have no order
A window functionโ€™s OVER (ORDER BY โ€ฆ) (Chapter 33) โœ… Different thing entirely โ€” required for ranking/running totals

[!TIP] ๐Ÿ’ก Make every sort that users see deterministic (the same order every time). ORDER BY order_date DESC on data with duplicate dates returns rows in an arbitrary order that can change between runs. Add a unique tiebreaker: ORDER BY order_date DESC, order_id DESC. Without it, paging silently repeats and skips rows.

16.7 ๐Ÿงช Try it yourself

  1. List all products from most to least expensive, with category as a tiebreaker.
  2. Sort customers so that Gold and Platinum tiers appear first, then alphabetically by name.
  3. Sort orders by status priority (Pending โ†’ Delivered) and then by newest first.
  4. Sort products by the length of their name, longest first.

๐Ÿงญ In practice โ€” ORDER BY

How to use it. Append ORDER BY column [ASC|DESC], listing several columns to break ties. Sort by an expression or an alias (both legal, because ORDER BY runs after SELECT), or by a CASE expression for a custom business order. Expected result: a guaranteed row order โ€” the only way to get one.

When to use it. Whenever the order shown to a human matters, and always before paging. OFFSET/LIMIT without ORDER BY can return the same row on two different pages and skip another entirely.

Where to use it. Reports, screens, exports, and any paged API. Scenario: an โ€œOrders, newest firstโ€ screen sorted only by order_date. Several orders share a date, so their relative order is undefined and page 2 sometimes repeats a row from page 1. Adding order_id DESC as a tiebreaker makes the sort deterministic and the bug disappears.

When not to use it. Never use ORDER BY 2 (sort by column position) in saved code โ€” the day someone adds a column to the SELECT list, the sort silently changes to a different column. Avoid sorting huge result sets you are about to discard; sorting is expensive, and ORDER BY in a subquery or view is usually meaningless because the outer query may reorder freely.

Best practices. Always make the sort deterministic by including enough columns to break every tie โ€” usually by ending with the primary key. A supporting index in the same order as your ORDER BY lets the engine skip the sort entirely, which is often the single largest win on a slow paged query. Be aware that sort order depends on collation (Chapter 60), so case and accent handling can differ between servers.


17. Paging: TOP, LIMIT, OFFSET, FETCH

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 20 min Show the top N rows ยท Show results page by page ยท Use fast โ€œLoad moreโ€ paging on big tables

[!NOTE] ๐Ÿ“Œ In plain words: You rarely want all 4 million rows. You want the top 10, or page 7 of the search results. This is where the two engines differ most visibly.

๐ŸŒ Analogy: A search engine never shows you all 4 million results at once. It shows page 1 with 10 results, and a โ€œNextโ€ button. Paging is how you build that โ€œNextโ€ button.

17.1 ๐Ÿ” Getting the first N rows

-- ๐ŸŸฅ MSSQL
SELECT TOP 5 product_name, unit_price
FROM products
ORDER BY unit_price DESC;

SELECT TOP 10 PERCENT product_name FROM products ORDER BY unit_price DESC;

-- WITH TIES: also include rows tied with the last one
SELECT TOP 3 WITH TIES product_name, unit_price
FROM products
ORDER BY unit_price DESC;
-- ๐ŸŸฆ MySQL
SELECT product_name, unit_price
FROM products
ORDER BY unit_price DESC
LIMIT 5;

17.2 ๐Ÿ“„ Paging through results

-- ๐ŸŸฅ MSSQL (2012+): the official SQL-standard syntax. ORDER BY is REQUIRED.
SELECT product_name, unit_price
FROM products
ORDER BY product_id
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;     -- page 3, if the page size is 10
-- ๐ŸŸฆ MySQL
SELECT product_name, unit_price
FROM products
ORDER BY product_id
LIMIT 10 OFFSET 20;

-- Older shorthand: LIMIT offset, count  (note the reversed order!)
SELECT product_name FROM products ORDER BY product_id LIMIT 20, 10;

The page-number formula both engines share:

OFFSET = (page_number - 1) ร— page_size

Page 1, size 10 โ†’ OFFSET 0
Page 2, size 10 โ†’ OFFSET 10
Page 5, size 25 โ†’ OFFSET 100

[!WARNING] โš ๏ธ Paging without ORDER BY is meaningless and buggy. With no defined order, a row can appear on page 1 and page 3, while another never appears at all. MSSQL refuses to run OFFSET without ORDER BY; MySQL allows it and gives you nonsense. Always order by something unique โ€” add the primary key as the final tiebreaker.

-- โœ… ๐ŸŸฅ MSSQL โ€” the professional pattern: a deterministic sort
--    (MySQL: the same ORDER BY, then LIMIT 10 OFFSET 0)
SELECT order_id, order_date, status
FROM orders
ORDER BY order_date DESC, order_id DESC       -- order_id breaks every tie
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

17.3 ๐ŸŒ Why OFFSET gets slow, and what professionals use instead

-- ๐ŸŸฆ MySQL ยท ๐Ÿ˜ฑ To return rows 1,000,001 to 1,000,010, the engine reads and discards
--    the first million rows. Every single time.
SELECT * FROM orders ORDER BY order_id LIMIT 10 OFFSET 1000000;

The fix: keyset pagination (also called โ€œseekโ€ or โ€œcursorโ€ pagination). Instead of counting rows, remember where you stopped.

-- ๐ŸŸฆ MySQL shown (MSSQL: SELECT TOP 10 ... instead of LIMIT 10). Page 1:
SELECT order_id, order_date, customer_id
FROM orders
ORDER BY order_id
LIMIT 10;

-- The last row you showed had order_id = 1009. The next page:
SELECT order_id, order_date, customer_id
FROM orders
WHERE order_id > 1009        -- โšก jumps straight there using the index
ORDER BY order_id
LIMIT 10;
ย  OFFSET paging Keyset paging
Page 1 speed โšก Fast โšก Fast
Page 100,000 speed ๐ŸŒ Terrible โšก Still fast
Jump to an arbitrary page number โœ… Easy โŒ Not possible
Rows shift if data changes mid-paging โš ๏ธ Yes โ€” duplicates and skips โœ… Stable
Used by Admin tables with page numbers Infinite scroll, APIs, Twitter/Facebook feeds

[!TIP] ๐Ÿ’ก This is why modern apps use โ€œLoad moreโ€ instead of numbered pages. Keyset pagination is the reason your social media feed stays fast at post 10,000.

Keyset paging when you sort by two columns:

-- ๐ŸŸฆ MySQL (MSSQL: TOP 10 instead of LIMIT) โ€” sorting by date then id, so "after" must check both columns
SELECT order_id, order_date
FROM orders
WHERE (order_date > '2026-05-06')
   OR (order_date = '2026-05-06' AND order_id > 1013)
ORDER BY order_date, order_id
LIMIT 10;
-- ๐ŸŸฆ MySQL supports the compact row-comparison form
SELECT order_id, order_date
FROM orders
WHERE (order_date, order_id) > ('2026-05-06', 1013)
ORDER BY order_date, order_id
LIMIT 10;

17.4 ๐Ÿ”ข Getting the total row count for a pager

COUNT(*) OVER () is a window function (Chapter 33): it counts all the matching rows and repeats that total on every row returned โ€” even though you only fetch 10 of them.

-- ๐ŸŸฅ MSSQL: COUNT(*) OVER() gives the total alongside the page
SELECT
    order_id,
    order_date,
    COUNT(*) OVER () AS total_matching_rows
FROM orders
WHERE status = 'Delivered'
ORDER BY order_date DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;
-- ๐ŸŸฆ MySQL 8.0: the same window function works
SELECT
    order_id,
    order_date,
    COUNT(*) OVER () AS total_matching_rows
FROM orders
WHERE status = 'Delivered'
ORDER BY order_date DESC
LIMIT 10;

[!TIP] ๐Ÿ’ก Pro tip: For very large tables, an exact total count is expensive and usually pointless โ€” nobody clicks to page 40,000. Real systems either cache the count, show an approximation (โ€œabout 12,000 resultsโ€), or drop the count entirely in favour of โ€œLoad moreโ€.

17.5 ๐ŸŽฏ When to use which paging strategy

Your screen Use Why
โ€œPage 1 2 3 โ€ฆ 47โ€ numbered pager, small table OFFSET/LIMIT Simple, and jumping to page 30 works
Infinite scroll / โ€œLoad moreโ€ Keyset Stays fast forever, no duplicates when data changes
An app or API that asks for โ€œthe next batchโ€ Keyset Stable and cheap
Top 10 / leaderboard TOP / LIMIT alone No paging needed
Export everything Neither โ€” read it in one continuous stream, or in ID ranges ย 
A table over ~100k rows where users jump to far-away pages Keyset OFFSET 500000 reads and throws away half a million rows

[!CAUTION] ๐Ÿ› Common mistake: paging a result whose sort is not unique. The database is free to return tied rows in a different order each query, so the same row appears on page 2 and page 3 while another never appears at all. Users report โ€œrecords go missingโ€ and it is almost impossible to reproduce. Always end ORDER BY with a unique column.

17.6 ๐Ÿงช Try it yourself

  1. Get the 5 most expensive products in both dialects.
  2. Return page 2 of customers, 5 per page, sorted by signup date.
  3. Rewrite that as keyset pagination and explain why it scales better.
  4. Use TOP 3 WITH TIES (MSSQL) on unit_price and explain what makes it different from plain TOP 3.

๐Ÿงญ In practice โ€” paging

How to use it. SQL Server uses OFFSET n ROWS FETCH NEXT m ROWS ONLY (or TOP n); MySQL uses LIMIT m OFFSET n. Both require an ORDER BY to be meaningful. Expected result: one page of rows, with no row appearing on two pages and none skipped.

When to use it. Any time a result set is too big to show at once โ€” a product listing, an admin table, an API endpoint.

Where to use it. User interfaces and APIs. Scenario: an admin screen showing 50 orders per page. At page 3 nobody notices anything; at page 4,000 the query has become slow, because OFFSET 200000 makes the engine find and discard 200,000 rows before returning 50.

When not to use it. OFFSET is the wrong tool for deep paging and for โ€œinfinite scrollโ€ feeds. Use keyset (or seek) paging instead โ€” remember the last rowโ€™s sort key and query WHERE (order_date, order_id) < (last_date, last_id). That stays fast at any depth because the index jumps straight to the position. Its trade-off is that you cannot jump to an arbitrary page number, which is exactly why it suits feeds and not numbered page links.

Best practices. Always pair paging with a deterministic ORDER BY. Index the sort columns so the engine can seek rather than sort. If the interface must show โ€œpage 400 of 9,000โ€, consider whether anyone actually visits page 400 โ€” usually the honest answer is to add better filtering and search instead of optimising deep pagination nobody uses.


18. UPDATE, changing data

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 25 min Change data safely ยท Follow the check โ†’ transaction โ†’ commit routine ยท Update from another table ยท Update huge tables in batches

[!NOTE] ๐Ÿ“Œ In plain words: UPDATE changes values in rows that already exist. It is the most dangerous everyday command in SQL, because forgetting one clause changes every row in the table.

๐ŸŒ Analogy: Correcting entries in an address book with a pen. The WHERE clause says which entries to correct. Forget it, and you have just written the same new phone number into every single entry in the book.

18.1 โœ๏ธ Basic UPDATE

-- โœ… Works in BOTH
UPDATE products
SET unit_price = 1399.00
WHERE product_id = 1;

-- Several columns at once
UPDATE customers
SET city = 'Kandy',
    phone = '+94-81-555-0199',
    loyalty_tier = 'Platinum'
WHERE customer_id = 1;

-- Using the existing value: a 10% price rise for one category
UPDATE products
SET unit_price = unit_price * 1.10
WHERE category_id = 3;

18.2 ๐Ÿšจ The most expensive mistake in SQL

-- ๐Ÿ’€ THIS UPDATES EVERY ROW IN THE TABLE
UPDATE products SET unit_price = 0;

[!WARNING] โš ๏ธ There is no undo. Unless you started a transaction first (an โ€œundo pointโ€ โ€” Step 3 below and Chapter 42), those 18 products (or 18 million) are now zero, and the only way back is a restore from backup.

The professional safety ritual โ€” follow it every time:

-- โœ… Works in BOTH
-- STEP 1: Write it as a SELECT first and look at the rows.
SELECT product_id, product_name, unit_price
FROM products
WHERE category_id = 3;

-- STEP 2: Confirm the count is what you expect.
SELECT COUNT(*) FROM products WHERE category_id = 3;   -- expecting 3

Step 3 uses a transaction. BEGIN TRANSACTION (MySQL: START TRANSACTION) sets an undo point. COMMIT makes the change permanent. ROLLBACK cancels everything since the undo point, as if it never happened.

-- ๐ŸŸฅ MSSQL โ€” STEP 3: Wrap it in a transaction, run, verify, THEN commit.
BEGIN TRANSACTION;

    UPDATE products
    SET unit_price = unit_price * 1.10
    WHERE category_id = 3;

    -- Did it touch the number of rows you expected?
    SELECT product_id, unit_price FROM products WHERE category_id = 3;

COMMIT;      -- or ROLLBACK; if it looks wrong
-- ๐ŸŸฆ MySQL โ€” STEP 3: the same, but MySQL starts a transaction with START TRANSACTION
START TRANSACTION;

    UPDATE products
    SET unit_price = unit_price * 1.10
    WHERE category_id = 3;

    SELECT product_id, unit_price FROM products WHERE category_id = 3;

COMMIT;      -- or ROLLBACK; if it looks wrong

[!TIP] ๐Ÿ’ก Turn on โ€œsafe update modeโ€ in MySQL and leave it on:

-- ๐ŸŸฆ MySQL
SET SQL_SAFE_UPDATES = 1;

MySQL will then refuse any UPDATE or DELETE whose WHERE clause does not use a key column (such as the ID). MySQL Workbench enables this by default โ€” do not turn it off. It exists because this mistake is so common.

[!TIP] ๐Ÿ’ก In SSMS, tick Tools โ†’ Options โ†’ Query Execution โ†’ SQL Server โ†’ ANSI โ†’ SET IMPLICIT_TRANSACTIONS โ€” then every change waits until you type COMMIT. Or simply build the habit of typing BEGIN TRAN before every hand-typed UPDATE on a live server.

18.3 ๐Ÿ”— UPDATE with a JOIN

Extremely common in real work: update one table based on data in another.

๐Ÿ”€ The syntax is completely different in the two engines. This is one of the biggest dialect gaps.

-- ๐ŸŸฅ MSSQL: UPDATE the alias, then FROM ... JOIN
UPDATE o
SET o.shipping_city    = c.city,
    o.shipping_country = c.country
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
WHERE o.shipping_city IS NULL;
-- ๐ŸŸฆ MySQL: joins go BEFORE the SET
UPDATE orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
SET o.shipping_city    = c.city,
    o.shipping_country = c.country
WHERE o.shipping_city IS NULL;
-- โœ… Works in BOTH: a subquery that looks up each order's customer (a correlated subquery, Chapter 30)
UPDATE orders
SET shipping_city = (
        SELECT c.city FROM customers c
        WHERE c.customer_id = orders.customer_id
    )
WHERE shipping_city IS NULL;

A real-world example โ€” recalculate loyalty tiers from actual spend. It works out each customerโ€™s total with SUM โ€ฆ GROUP BY (Chapters 25โ€“26) inside the update, so skim it now and come back later:

-- ๐ŸŸฅ MSSQL
UPDATE c
SET c.loyalty_tier =
    CASE
        WHEN s.total_spend >= 5000 THEN 'Platinum'
        WHEN s.total_spend >= 2000 THEN 'Gold'
        WHEN s.total_spend >=  500 THEN 'Silver'
        ELSE 'Bronze'
    END
FROM customers AS c
INNER JOIN (
    SELECT o.customer_id,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total_spend
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    WHERE o.status IN ('Delivered','Shipped')
    GROUP BY o.customer_id
) AS s ON s.customer_id = c.customer_id;
-- ๐ŸŸฆ MySQL
UPDATE customers AS c
INNER JOIN (
    SELECT o.customer_id,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total_spend
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    WHERE o.status IN ('Delivered','Shipped')
    GROUP BY o.customer_id
) AS s ON s.customer_id = c.customer_id
SET c.loyalty_tier =
    CASE
        WHEN s.total_spend >= 5000 THEN 'Platinum'
        WHEN s.total_spend >= 2000 THEN 'Gold'
        WHEN s.total_spend >=  500 THEN 'Silver'
        ELSE 'Bronze'
    END;

18.4 ๐Ÿ“ธ Seeing what changed

-- ๐ŸŸฅ MSSQL: OUTPUT shows the before AND after values
UPDATE products
SET unit_price = unit_price * 1.10
OUTPUT
    inserted.product_id,
    deleted.unit_price  AS old_price,
    inserted.unit_price AS new_price
WHERE category_id = 3;

[!TIP] ๐Ÿ’ก OUTPUT with deleted. and inserted. is one of MSSQLโ€™s best features. deleted. holds each rowโ€™s old values and inserted. its new ones, so the same statement hands you a free record of exactly what changed. MySQL has no equivalent โ€” you must first copy the old values into a temporary table (Chapter 40), or use a trigger (Chapter 39).

-- โœ… MSSQL: how many rows did I just change?
SELECT @@ROWCOUNT AS rows_affected;
-- โœ… MySQL: how many rows did I just change?
SELECT ROW_COUNT() AS rows_affected;

[!WARNING] โš ๏ธ Read it immediately. @@ROWCOUNT is reset by the next statement โ€” even by a PRINT or an IF. Capture it into a variable on the very next line if you need it later: DECLARE @n INT = @@ROWCOUNT;

18.5 ๐Ÿ”€ Conditional and bulk updates

-- โœ… Works in BOTH: different new values per row, one pass
UPDATE products
SET unit_price = CASE
        WHEN units_in_stock = 0            THEN unit_price          -- unchanged
        WHEN units_in_stock < reorder_level THEN unit_price * 1.05  -- scarce: raise
        WHEN units_in_stock > 100          THEN unit_price * 0.90   -- overstocked: cut
        ELSE unit_price
    END
WHERE discontinued = 0;

[!WARNING] โš ๏ธ Note the ELSE unit_price. Without it, every row that matches no branch would be set to NULL, because CASE with no ELSE returns NULL. This single omission has corrupted many tables. Always write an explicit ELSE.

[!TIP] ๐Ÿ’ก Pro tip for updating millions of rows: do it in batches. One giant UPDATE locks other users out of those rows for a long time, makes the transaction log grow huge, and can freeze your whole application.

-- ๐ŸŸฅ MSSQL: batched update loop
WHILE 1 = 1
BEGIN
    UPDATE TOP (5000) orders
    SET status = 'Cancelled'                  -- auto-cancel stale unpaid orders
    WHERE order_date < '2024-01-01' AND status = 'Pending';

    IF @@ROWCOUNT = 0 BREAK;
END;
-- ๐ŸŸฆ MySQL: same idea with LIMIT
UPDATE orders
SET status = 'Cancelled'
WHERE order_date < '2024-01-01' AND status = 'Pending'
LIMIT 5000;
-- repeat until ROW_COUNT() = 0

18.6 ๐Ÿงช Try it yourself

  1. Give every product in the Audio category a 5% price cut โ€” inside a transaction, and roll it back.
  2. Set shipping_city from the customerโ€™s city for every order where it is NULL, in both dialects.
  3. Recalculate all loyalty tiers using the query above, then check how many customers changed.
  4. Write an update with no WHERE inside a transaction, look at the damage with a SELECT, then ROLLBACK. Feel the fear. Learn the habit.

๐Ÿงญ In practice โ€” UPDATE

How to use it. Write UPDATE table SET column = value WHERE condition. Run the WHERE as a SELECT first and check the row count. Wrap it in an explicit transaction so you can ROLLBACK if the count is wrong. Expected result: the number of rows reported as updated matches the number your SELECT predicted.

When to use it. Whenever existing data changes state: an order ships, a price changes, a customer edits their address.

Where to use it. Application code and one-off data corrections. Scenario: a supplier raises prices 5%. UPDATE products SET unit_price = unit_price * 1.05 WHERE supplier_id = 3 touches only that supplierโ€™s rows โ€” and running the matching SELECT COUNT(*) first tells you it should be 4 rows, so if the UPDATE reports 18 you know immediately that you mistyped the WHERE.

When not to use it. Never run an UPDATE without a WHERE unless you genuinely intend to change every row โ€” it is the most common self-inflicted data disaster there is, and there is no undo outside a transaction. Avoid huge single UPDATEs on busy tables: they hold locks for their whole duration and can block everyone else; batch them instead.

Best practices. Make it a habit to type the WHERE clause before the SET clause, so a half-typed statement cannot execute against everything. Work inside BEGIN TRANSACTION for anything manual, and only COMMIT once the row count looks right. Take a backup before bulk corrections, and remember that UPDATE fires triggers (Chapter 39) โ€” so it may do more than you wrote.


19. DELETE, TRUNCATE, DROP

๐ŸŽš๏ธ Level โฑ๏ธ Time ๐ŸŽฏ After this chapter you canโ€ฆ
๐ŸŸข Beginner 20 min Delete chosen rows ยท Empty a table fast ยท Use soft deletes ยท Follow the pre-delete checklist

[!NOTE] ๐Ÿ“Œ In plain words: Three ways to remove things, and each one destroys a very different amount. Choosing wrongly is how people lose data permanently.

๐ŸŒ Analogy: A notebook. DELETE rubs out chosen lines. TRUNCATE tears out every page but keeps the empty notebook. DROP throws the whole notebook in the bin.

19.1 ๐ŸŽฏ DELETE โ€” remove selected rows

-- โœ… Works in BOTH
DELETE FROM order_items WHERE order_id = 1004;

DELETE FROM orders
WHERE status = 'Cancelled'
  AND order_date < '2026-01-01';

-- ๐Ÿ’€ Deletes EVERY row โ€” same danger as UPDATE with no WHERE
DELETE FROM order_items;

DELETE with a JOIN or subquery:

-- ๐ŸŸฅ MSSQL
DELETE oi
FROM order_items AS oi
INNER JOIN orders AS o ON o.order_id = oi.order_id
WHERE o.status = 'Cancelled';
-- ๐ŸŸฆ MySQL: name the table(s) to delete from BEFORE the FROM
DELETE oi
FROM order_items AS oi
INNER JOIN orders AS o ON o.order_id = oi.order_id
WHERE o.status = 'Cancelled';

-- MySQL can delete from BOTH tables in one statement
DELETE oi, o
FROM order_items AS oi
INNER JOIN orders AS o ON o.order_id = oi.order_id
WHERE o.status = 'Cancelled';
-- โœ… Portable version with a subquery (works in BOTH)
DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders WHERE status = 'Cancelled');

[!CAUTION] ๐Ÿ› MySQL error 1093: โ€œYou canโ€™t specify target table for update in FROM clause.โ€ MySQL will not let you read the same table you are deleting from in a plain subquery. The workaround is to wrap the subquery one level deeper, which makes MySQL build a temporary copy of the list first:

DELETE FROM orders
WHERE order_id IN (
    SELECT order_id FROM (
        SELECT order_id FROM orders WHERE status = 'Cancelled'
    ) AS tmp
);

19.2 ๐Ÿงน TRUNCATE โ€” empty the table fast

-- โœ… Works in BOTH
TRUNCATE TABLE staging_products;

Why it is so much faster than DELETE: DELETE is row-by-row. It writes every removed row into the transaction log so each one can be rolled back, fires any DELETE triggers, and updates every index. TRUNCATE instead deallocates the tableโ€™s storage pages and logs only the deallocations โ€” a tiny, fixed amount of work regardless of how many rows were in the table.

That difference in mechanism is why TRUNCATE scales differently: DELETE cost grows with the row count, TRUNCATE cost does not. On a large table the practical gap is commonly several orders of magnitude โ€” but the exact numbers depend on row size, index count, trigger count, recovery model, and your storage. Measure on your own data rather than trusting any figure quoted in a guide, this one included.

[!WARNING] โš ๏ธ Three things that will bite you:

  1. You cannot TRUNCATE a table referenced by a foreign key, even if there are no child rows. Remove the foreign key, truncate, then add the foreign key back โ€” or just use DELETE.
  2. Triggers do not fire. If you rely on a delete trigger to record deletions, TRUNCATE skips it completely.
  3. In MySQL, TRUNCATE is saved the moment it runs (an implicit commit), so it cannot be rolled back. In MSSQL it can be rolled back inside an explicit transaction. Do not carry the habit across engines.

19.3 ๐Ÿ—‘๏ธ Soft delete โ€” what production systems actually do

Real applications very rarely delete anything. They mark it as gone.

-- โœ… MSSQL
ALTER TABLE customers ADD is_deleted BIT NOT NULL DEFAULT 0;
ALTER TABLE customers ADD deleted_at DATETIME2(0) NULL;
GO

-- "Deleting" a customer
UPDATE customers
SET is_deleted = 1, deleted_at = SYSDATETIME()
WHERE customer_id = 4;

-- Every normal query then filters them out
SELECT * FROM customers WHERE is_deleted = 0;
-- โœ… MySQL
ALTER TABLE customers ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE customers ADD COLUMN deleted_at DATETIME NULL;

UPDATE customers
SET is_deleted = 1, deleted_at = CURRENT_TIMESTAMP
WHERE customer_id = 4;

SELECT * FROM customers WHERE is_deleted = 0;
ย  Hard delete (DELETE) Soft delete (is_deleted flag)
Data recoverable โŒ Only from backup โœ… Instantly
Foreign keys stay valid โš ๏ธ Cascades or blocks โœ… Nothing breaks
Historical reports still work โŒ Orders lose their customer โœ… Everything still joins
Table size โœ… Shrinks โš ๏ธ Grows forever
Query complexity โœ… Simple โš ๏ธ Every query needs the filter
Erasure requirement Removes these live rows; retention, replicas and backups still need a policy Needs a separate purge process; soft deletion alone retains the data

[!TIP] ๐Ÿ’ก The professional pattern: soft delete for everyday operations, plus a scheduled job that permanently deletes or anonymizes rows once they are older than the period you must keep them. Wrap the filter in a view so nobody forgets it:

CREATE VIEW v_active_customers AS
SELECT * FROM customers WHERE is_deleted = 0;

19.4 ๐Ÿ›Ÿ The pre-delete checklist

-- ๐ŸŸฅ MSSQL
-- 1. SELECT first. Always. Look at the actual rows.
SELECT * FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';

-- 2. Count them. Does the number match your expectation?
SELECT COUNT(*) FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';

-- 3. Back them up.  (๐ŸŸฅ MSSQL form โ€” see the MySQL form below)
SELECT * INTO orders_deleted_backup
FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';

-- 4. Delete inside a transaction and verify before committing.
BEGIN TRANSACTION;
    DELETE FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';
    SELECT @@ROWCOUNT AS rows_deleted;
-- COMMIT;  -- only after you are satisfied
ROLLBACK;
-- โœ… MySQL: same four steps
SELECT * FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';
SELECT COUNT(*) FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';

CREATE TABLE orders_deleted_backup AS
SELECT * FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';

START TRANSACTION;
    DELETE FROM orders WHERE status = 'Cancelled' AND order_date < '2026-01-01';
    SELECT ROW_COUNT() AS rows_deleted;
-- COMMIT;
ROLLBACK;

[!TIP] ๐Ÿ’ก Batch large deletes for the same reason you batch large updates โ€” so other users are not locked out and the transaction log does not balloon:

-- ๐ŸŸฅ MSSQL
WHILE 1 = 1
BEGIN
    DELETE TOP (5000) FROM payments WHERE payment_date < '2024-01-01';
    IF @@ROWCOUNT = 0 BREAK;
END;

-- ๐ŸŸฆ MySQL
DELETE FROM payments WHERE payment_date < '2024-01-01' LIMIT 5000;  -- repeat

19.5 ๐Ÿงช Try it yourself

  1. Delete all order_items belonging to cancelled orders โ€” first as a SELECT, then for real inside a transaction, then roll back.
  2. Add a soft-delete column to products and write the view that hides discontinued and deleted items.
  3. Try to TRUNCATE TABLE orders. Read the exact error and explain which constraint caused it.
  4. Delete order 1000 and check what happened to its order_items and payments. Which referential action was responsible?

๐Ÿงญ In practice โ€” DELETE, TRUNCATE, and DROP

How to use it. DELETE FROM t WHERE ... removes chosen rows and can be rolled back. TRUNCATE TABLE t removes all rows very fast, resets auto-numbering, and is minimally logged. DROP TABLE t removes the table itself. Expected result: exactly the level of destruction you intended โ€” which is why knowing the difference matters more here than anywhere else in the guide.

When to use it. DELETE for removing specific rows in normal operation; TRUNCATE for emptying a staging or scratch table between loads; DROP only when the object should cease to exist.

Where to use it. TRUNCATE belongs in ETL and test-data workflows. Scenario: a nightly import clears a staging table before reloading it. TRUNCATE is near-instant; DELETE on the same table writes every removed row to the transaction log and can take minutes and inflate the log file.

When not to use it. Do not use TRUNCATE when you need a WHERE clause (it has none), when triggers must fire (they do not), or when foreign keys reference the table (it is refused). Do not use DELETE to empty a huge table you could truncate. And never use any of the three on production without a current, tested backup โ€” an untested backup is a hope, not a recovery plan.

Best practices. Rehearse every delete as a SELECT with the identical WHERE. Use an explicit transaction for manual work so a wrong row count can be rolled back. Prefer a soft delete (an is_deleted flag or a deleted_at timestamp) for anything a user might want restored or an auditor might need to see โ€” but then remember that every query must filter on it, which is the real cost of that choice.


Part index Prerequisites Previous Next Full course