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:
INSERTadds 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
INSERTbeats 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. PreferON DUPLICATE KEY UPDATEor an explicitNOT EXISTSguard.
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 INFILEand thesecure_file_privsetting: by default MySQL only reads files from one specific directory. Check it withSHOW VARIABLES LIKE 'secure_file_priv';. UseLOAD DATA LOCAL INFILEto 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
- Add three new products to the
Gamingcategory in a single statement. - Copy every
Cancelledorder into a newcancelled_orders_logtable usingINSERT ... SELECT. - Deliberately trigger each of the four errors above and read the messages carefully.
- 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 severalVALUEStuples โ far faster than one statement per row. UseINSERT ... SELECTto 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
INSERTinstead 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
INSERTrow-by-row in a loop for bulk loading โ use multi-rowVALUES,INSERT ... SELECT, or a bulk-load tool (BULK INSERT,bcp,LOAD DATA INFILE). And never build anINSERTby 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:
SELECTasks the database a question and gets a table of rows back. You will write moreSELECTstatements 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:
- It moves columns you do not need across the network โ sometimes megabytes of
TEXT.- It stops the database using some of its fastest shortcuts (covering indexes, Chapter 46), so it reads far more data than it needs.
- Your app breaks in a new way when someone adds or reorders a column.
- 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 entirelyINSERT INTO archive SELECT * FROM sourcewhere 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 (
cfor customers,oifor order_items), and use them the same way in all of your code. Never usea,b,cโ after three joins nobody, including you, knows whatbwas.
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_nameand gets0for 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] โ ๏ธ
DISTINCTis often a symptom, not a solution. If you addedDISTINCTbecause 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.DISTINCThides 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
- List every product with its name, price, and the price including 15% tax, aliased clearly.
- Produce a single column
labelreadingUltraBook Pro 14 โ $1499.00for every product. - Find how many distinct cities your customers live in.
- List the distinct combinations of
statusandshipping_countryfromorders.
๐งญ In practice โ SELECT
How to use it. Name the columns you want, then
FROMthe table. Rename output columns withAS, remove duplicate rows withDISTINCT, 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.
SELECTis 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 ... SELECTand view. Scenario: a support agent asks โwhat did customer 7 order in March?โ That is aSELECTwith 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
DISTINCTas a symptom rather than a fix: if a join suddenly produced duplicates, the join is wrong, andDISTINCThides the bug while adding an expensive sort. Name computed columns withASso the result is self-describing. Remember that aSELECTwith noORDER BYhas 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:
WHEREis the filter. It looks at every candidate row and asks a yes/no question. Only the rows that answer yes survive.
๐ Analogy:
WHEREis 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.
WHEREconditions can compare two columns of the same row, not just a column against a constant.units_in_stock <= reorder_levelis 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
ANDbeforeORโ 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
WHEREclause mixesANDandOR, 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 INbreaks 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 EXISTSoverNOT INfor 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 onproduct_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
_cicollation is also case-insensitive; with_binor_csit is case-sensitive.- To force case-sensitivity: MSSQL
COLLATE Latin1_General_CS_AS, MySQLLIKE BINARY 'a%'.
14.6 ๐งช Try it yourself
- Find every product priced between 100 and 400 that is not discontinued.
- Find all customers whose email is at
example.comand who live outside the UK. - Find every order placed in March 2026, using the half-open date pattern.
- Find the products whose name contains the word โProโ. Then check whether an index could help โ why not?
- Deliberately write a
WHEREmixingANDandORwithout parentheses and count how the row count changes when you add them.
๐งญ In practice โ WHERE
How to use it. Add
WHERE conditionto keep only matching rows. Combine conditions withAND/ORand parenthesise whenever you mix them. UseBETWEENfor ranges,INfor lists, andLIKEfor patterns. Expected result: the row count drops to exactly the rows you meant โ which you should check before you use the sameWHEREin anUPDATEorDELETE.When to use it. On essentially every query against a real table. A query with no
WHEREreads 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', runSELECT COUNT(*) FROM orders WHERE status = 'cancelled'with the identicalWHERE. 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) = 2026cannot use an index onorder_date, so the engine reads every row. WriteWHERE 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-wildcardLIKE '%phone'for the same reason.Best practices. Mind operator precedence:
ANDbinds tighter thanOR, soWHERE a = 1 OR a = 2 AND b = 3does 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:
NULLdoes 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 = NULLreturns.
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
statusallowedNULL, every row with aNULLstatus 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
NULLIFdivide-by-zero trick is worth memorizing.x / NULLIF(y, 0)turns a hard error into aNULL, which you can then handle withCOALESCE. Combined:COALESCE(x / NULLIF(y,0), 0).
๐ A subtle MSSQL difference:
ISNULLreturns the data type of its first argument, soISNULL(CAST(x AS VARCHAR(5)), 'Not available')silently truncates to'Not a'.COALESCEpicks a type big enough for all of its values, so it does not do this. Another reason to preferCOALESCE.
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] โ ๏ธ
AVGdivides 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:
NULLsorts first inASC.- MySQL:
NULLsorts first inASCtoo, and last inDESC.- 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
NULLfor โno valueโ, never the empty string. Then add aCHECK (phone <> '')constraint so the empty string can never sneak in. Mixed conventions mean every query needsWHERE phone IS NULL OR phone = '', forever.
๐ Oracle-style trap for people arriving from Oracle: Oracle treats
''asNULL. 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 ''orDEFAULT 0to โ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
- Count how many orders have no
ship_date. Then try it with= NULLand confirm you get zero. - Write a query showing every order with a shipping status of either the date, or the text
'In progress'. - Compute the average
discountinorder_itemstwo ways: ignoring zeros and treating them as zero. Explain the difference. - Sort
ordersso 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 withCOALESCE(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 wherestatusisNULL, becauseNULL <> '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
NULLas a stand-in for zero, an empty string, or โfalseโ.NULLmeans unknown or not applicable; a stock level of zero is a known fact and should be0. Conflating them makesSUMandAVGproduce results nobody can interpret. And do not useNOT INwith a subquery that might return aNULLโ the whole predicate becomes unknown and you get no rows at all; useNOT EXISTSinstead.Best practices. Learn the three-valued logic properly, because it explains a whole class of silent wrong answers:
COUNT(*)counts rows whileCOUNT(column)skipsNULLs;AVGignoresNULLs rather than treating them as zero; andNULLsorts differently between the two engines. Make columnsNOT NULLwith a sensibleDEFAULTwherever โ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 2in real code. The day someone adds a column to theSELECTlist, 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 BYguarantees nothing. In MSSQL,ORDER BYinside a view is only legal alongsideTOP/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 BYonly if the sort direction pattern matches.ORDER BY a ASC, b DESCneeds an index defined as(a ASC, b DESC). Both engines support per-column direction in an index definition (MySQL genuinely honoursDESCin 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 DESCon 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
- List all products from most to least expensive, with category as a tiebreaker.
- Sort customers so that Gold and Platinum tiers appear first, then alphabetically by name.
- Sort orders by status priority (Pending โ Delivered) and then by newest first.
- 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, becauseORDER BYruns afterSELECT), or by aCASEexpression 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/LIMITwithoutORDER BYcan 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. Addingorder_id DESCas 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 theSELECTlist, the sort silently changes to a different column. Avoid sorting huge result sets you are about to discard; sorting is expensive, andORDER BYin 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 BYlets 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 BYis 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 runOFFSETwithoutORDER 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 BYwith a unique column.
17.6 ๐งช Try it yourself
- Get the 5 most expensive products in both dialects.
- Return page 2 of customers, 5 per page, sorted by signup date.
- Rewrite that as keyset pagination and explain why it scales better.
- Use
TOP 3 WITH TIES(MSSQL) onunit_priceand explain what makes it different from plainTOP 3.
๐งญ In practice โ paging
How to use it. SQL Server uses
OFFSET n ROWS FETCH NEXT m ROWS ONLY(orTOP n); MySQL usesLIMIT m OFFSET n. Both require anORDER BYto 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 200000makes the engine find and discard 200,000 rows before returning 50.When not to use it.
OFFSETis 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 queryWHERE (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:
UPDATEchanges 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
WHEREclause 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
UPDATEorDELETEwhoseWHEREclause 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 typingBEGIN TRANbefore every hand-typedUPDATEon 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] ๐ก
OUTPUTwithdeleted.andinserted.is one of MSSQLโs best features.deleted.holds each rowโs old values andinserted.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.
@@ROWCOUNTis reset by the next statement โ even by aIF. 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 toNULL, becauseCASEwith noELSEreturnsNULL. This single omission has corrupted many tables. Always write an explicitELSE.
[!TIP] ๐ก Pro tip for updating millions of rows: do it in batches. One giant
UPDATElocks 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
- Give every product in the
Audiocategory a 5% price cut โ inside a transaction, and roll it back. - Set
shipping_cityfrom the customerโs city for every order where it is NULL, in both dialects. - Recalculate all loyalty tiers using the query above, then check how many customers changed.
- Write an update with no
WHEREinside a transaction, look at the damage with aSELECT, thenROLLBACK. Feel the fear. Learn the habit.
๐งญ In practice โ UPDATE
How to use it. Write
UPDATE table SET column = value WHERE condition. Run theWHEREas aSELECTfirst and check the row count. Wrap it in an explicit transaction so you canROLLBACKif the count is wrong. Expected result: the number of rows reported as updated matches the number yourSELECTpredicted.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 = 3touches only that supplierโs rows โ and running the matchingSELECT COUNT(*)first tells you it should be 4 rows, so if theUPDATEreports 18 you know immediately that you mistyped theWHERE.When not to use it. Never run an
UPDATEwithout aWHEREunless 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 singleUPDATEs 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
WHEREclause before theSETclause, so a half-typed statement cannot execute against everything. Work insideBEGIN TRANSACTIONfor anything manual, and onlyCOMMITonce the row count looks right. Take a backup before bulk corrections, and remember thatUPDATEfires 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.
DELETErubs out chosen lines.TRUNCATEtears out every page but keeps the empty notebook.DROPthrows 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:
- You cannot
TRUNCATEa 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 useDELETE.- Triggers do not fire. If you rely on a delete trigger to record deletions,
TRUNCATEskips it completely.- In MySQL,
TRUNCATEis 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
- Delete all
order_itemsbelonging to cancelled orders โ first as aSELECT, then for real inside a transaction, then roll back. - Add a soft-delete column to
productsand write the view that hides discontinued and deleted items. - Try to
TRUNCATE TABLE orders. Read the exact error and explain which constraint caused it. - Delete order 1000 and check what happened to its
order_itemsandpayments. 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 tremoves all rows very fast, resets auto-numbering, and is minimally logged.DROP TABLE tremoves 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.
DELETEfor removing specific rows in normal operation;TRUNCATEfor emptying a staging or scratch table between loads;DROPonly when the object should cease to exist.Where to use it.
TRUNCATEbelongs in ETL and test-data workflows. Scenario: a nightly import clears a staging table before reloading it.TRUNCATEis near-instant;DELETEon 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
TRUNCATEwhen you need aWHEREclause (it has none), when triggers must fire (they do not), or when foreign keys reference the table (it is refused). Do not useDELETEto 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
SELECTwith the identicalWHERE. Use an explicit transaction for manual work so a wrong row count can be rolled back. Prefer a soft delete (anis_deletedflag or adeleted_attimestamp) 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 |