Developer Guides, Cheat Sheets & Tools

SQL course - Part 13: MODERN AND EXPERT TOPICS

Part index Prerequisites Previous Next Full course

🚀 PART 13 — MODERN AND EXPERT TOPICS


58. JSON, XML, and semi-structured data

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡 Intermediate 30 min Store flexible details as JSON · Read, filter, and change JSON values · Index JSON for speed · Decide when JSON is the wrong choice

[!NOTE] 📌 In plain words: Sometimes data does not fit neat columns — a laptop has a CPU and RAM, a phone has a camera and colours, and a form has custom fields someone added last week. Both engines can store this flexible data as JSON (a simple text format) and still search it.

🌍 Analogy: A normal table is a printed form with fixed boxes. JSON is a blank notes page stapled to that form: you can write whatever details a particular item needs.

58.1 🟦 MySQL JSON — a native type

CREATE TABLE product_attributes (
    product_id  INT PRIMARY KEY,
    attributes  JSON NOT NULL,
    CONSTRAINT fk_pa_product FOREIGN KEY (product_id) REFERENCES products(product_id)
) ENGINE=InnoDB;

INSERT INTO product_attributes (product_id, attributes) VALUES
(1, '{"cpu":"Intel i7","ram_gb":16,"storage_gb":512,"screen":14.0,
      "ports":["USB-C","HDMI","USB-A"],"warranty":{"years":2,"onsite":true}}'),
(5, '{"os":"Android 15","ram_gb":8,"storage_gb":256,"camera_mp":50,
      "colors":["Black","Blue"],"warranty":{"years":1,"onsite":false}}');
-- Reading values
SELECT
    product_id,
    attributes->>'$.cpu'                     AS cpu,          -- ->> returns plain text
    attributes->'$.ram_gb'                   AS ram_quoted,   -- ->  keeps JSON quoting
    JSON_EXTRACT(attributes, '$.storage_gb') AS storage,
    attributes->>'$.warranty.years'          AS warranty_years,
    attributes->>'$.ports[0]'                AS first_port,
    JSON_LENGTH(attributes->'$.ports')       AS port_count
FROM product_attributes;

-- Filtering
SELECT product_id FROM product_attributes
WHERE CAST(attributes->>'$.ram_gb' AS UNSIGNED) >= 16;

SELECT product_id FROM product_attributes
WHERE JSON_CONTAINS(attributes->'$.ports', '"HDMI"');

SELECT product_id FROM product_attributes
WHERE JSON_UNQUOTE(attributes->'$.warranty.onsite') = 'true';
-- ✅ MySQL: modifying JSON in place
UPDATE product_attributes
SET attributes = JSON_SET(attributes, '$.ram_gb', 32)
WHERE product_id = 1;

UPDATE product_attributes
SET attributes = JSON_INSERT(attributes, '$.color', 'Silver')   -- only if absent
WHERE product_id = 1;

UPDATE product_attributes
SET attributes = JSON_REMOVE(attributes, '$.warranty.onsite')
WHERE product_id = 1;

UPDATE product_attributes
SET attributes = JSON_ARRAY_APPEND(attributes, '$.ports', 'Ethernet')
WHERE product_id = 1;
-- ⭐ JSON_TABLE: turn a JSON array into rows (MySQL 8.0+) — extremely useful
SELECT pa.product_id, p.port
FROM product_attributes pa,
     JSON_TABLE(pa.attributes, '$.ports[*]' COLUMNS (port VARCHAR(30) PATH '$')) AS p;

Indexing JSON in MySQL:

-- ✅ Extract to a generated column and index THAT
ALTER TABLE product_attributes
    ADD COLUMN ram_gb INT AS (CAST(attributes->>'$.ram_gb' AS UNSIGNED)) STORED,
    ADD INDEX ix_pa_ram (ram_gb);

-- Now this search uses the index instead of reading every row:
SELECT * FROM product_attributes WHERE ram_gb >= 16;

-- Multi-valued index: one index entry per array element (MySQL 8.0.17+)
ALTER TABLE product_attributes
    ADD INDEX ix_pa_ports ((CAST(attributes->'$.ports' AS CHAR(30) ARRAY)));

58.2 🟥 MSSQL JSON — functions over NVARCHAR

CREATE TABLE product_attributes (
    product_id INT PRIMARY KEY,
    attributes NVARCHAR(MAX) NOT NULL,
    CONSTRAINT ck_pa_json CHECK (ISJSON(attributes) = 1),      -- 🔑 validity guard
    CONSTRAINT fk_pa_product FOREIGN KEY (product_id) REFERENCES products(product_id)
);

INSERT INTO product_attributes (product_id, attributes) VALUES
(1, N'{"cpu":"Intel i7","ram_gb":16,"storage_gb":512,"screen":14.0,
      "ports":["USB-C","HDMI","USB-A"],"warranty":{"years":2,"onsite":true}}'),
(5, N'{"os":"Android 15","ram_gb":8,"storage_gb":256,"camera_mp":50,
      "colors":["Black","Blue"],"warranty":{"years":1,"onsite":false}}');
-- Reading values
SELECT
    product_id,
    JSON_VALUE(attributes, '$.cpu')            AS cpu,          -- scalar
    JSON_VALUE(attributes, '$.ram_gb')         AS ram_gb,
    JSON_VALUE(attributes, '$.warranty.years') AS warranty_years,
    JSON_QUERY(attributes, '$.ports')          AS ports_array   -- object or array
FROM product_attributes;

-- Filtering
SELECT product_id FROM product_attributes
WHERE CAST(JSON_VALUE(attributes, '$.ram_gb') AS INT) >= 16;

-- ⭐ OPENJSON: turn JSON into rows and columns
SELECT pa.product_id, p.value AS port
FROM product_attributes pa
CROSS APPLY OPENJSON(pa.attributes, '$.ports') AS p;

SELECT *
FROM OPENJSON(
    (SELECT attributes FROM product_attributes WHERE product_id = 1))
WITH (
    cpu             NVARCHAR(50) '$.cpu',
    ram_gb          INT          '$.ram_gb',
    warranty_years  INT          '$.warranty.years',
    ports           NVARCHAR(MAX) '$.ports' AS JSON
);
-- Modifying
UPDATE product_attributes
SET attributes = JSON_MODIFY(attributes, '$.ram_gb', 32)
WHERE product_id = 1;

UPDATE product_attributes
SET attributes = JSON_MODIFY(attributes, 'append $.ports', 'Ethernet')
WHERE product_id = 1;

Indexing JSON in MSSQL:

-- ✅ Same idea: a persisted computed column, then an index
ALTER TABLE product_attributes
    ADD ram_gb AS CAST(JSON_VALUE(attributes, '$.ram_gb') AS INT) PERSISTED;
CREATE INDEX ix_pa_ram ON product_attributes(ram_gb);

58.3 📤 Producing JSON from query results

-- 🟥 MSSQL: FOR JSON — build the JSON an app or website expects, directly in SQL
SELECT
    o.order_id,
    o.order_date,
    c.full_name AS [customer.name],
    c.country   AS [customer.country],
    (SELECT p.product_name AS name, oi.quantity AS qty, oi.unit_price AS price
     FROM order_items oi
     JOIN products p ON p.product_id = oi.product_id
     WHERE oi.order_id = o.order_id
     FOR JSON PATH) AS items
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_id = 1002
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;
-- 🟦 MySQL: JSON_OBJECT / JSON_ARRAYAGG
SELECT JSON_OBJECT(
    'order_id',  o.order_id,
    'order_date', o.order_date,
    'customer',  JSON_OBJECT('name', c.full_name, 'country', c.country),
    'items', (
        SELECT JSON_ARRAYAGG(
            JSON_OBJECT('name', p.product_name, 'qty', oi.quantity, 'price', oi.unit_price))
        FROM order_items oi
        JOIN products p ON p.product_id = oi.product_id
        WHERE oi.order_id = o.order_id
    )
) AS order_json
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_id = 1002;

58.4 ⚖️ When to use JSON — and when not to

✅ Good use of JSON ❌ Bad use of JSON
Genuinely variable attributes per row (product specs across categories) Data every row has (email, order_date)
Storing an API request/response payload for audit Anything you filter or join on constantly
User preferences, feature flags, form definitions Relationships between entities
Sparse optional fields (500 possible, 5 used per row) Anything requiring a foreign key
Rapid prototyping before the schema settles Financial or transactional values

[!WARNING] ⚠️ The three real costs of JSON columns:

  1. No constraints. The database cannot enforce that ram_gb is a positive integer, or that cpu exists at all. Every JSON column is a place your data-quality rules cannot reach.
  2. No foreign keys. A product ID inside JSON can point at nothing.
  3. Slower filtering. Every filter must read through the JSON text unless you add a generated column and index — at which point you have re-invented a column, badly.

[!TIP] 💡 The practical rule: use real columns for what you query, and JSON for the many rarely used details. Put price, stock, and category_id in columns; put the 40 category-specific spec fields in JSON. That is how mature systems actually do it.

58.5 📄 XML (MSSQL)

-- 🟥 MSSQL has a full built-in XML type, queried with XQuery (the query language for XML)
CREATE TABLE order_xml (
    order_id INT PRIMARY KEY,
    payload  XML NOT NULL
);

INSERT INTO order_xml VALUES (1002,
'<order id="1002">
    <customer>Mei Chen</customer>
    <items>
        <item sku="3" qty="1" price="2450.00"/>
        <item sku="15" qty="2" price="749.00"/>
    </items>
</order>');

SELECT
    payload.value('(/order/customer)[1]', 'VARCHAR(100)') AS customer,
    payload.value('count(/order/items/item)', 'INT')      AS item_count
FROM order_xml;

-- Shred into rows
SELECT
    x.item.value('@sku', 'INT')            AS sku,
    x.item.value('@qty', 'INT')            AS qty,
    x.item.value('@price', 'DECIMAL(10,2)') AS price
FROM order_xml
CROSS APPLY payload.nodes('/order/items/item') AS x(item);

-- Produce XML
SELECT order_id, order_date, status FROM orders WHERE order_id = 1002
FOR XML PATH('order'), ROOT('orders');

🔀 MySQL has only basic XML support (ExtractValue, UpdateXML) and no XML data type. If you work with XML, MSSQL is dramatically better equipped. For new work, prefer JSON — it is simpler, better supported on both sides, and universally understood by APIs.

58.6 🧪 Try it yourself

  1. Create product_attributes in your engine and add JSON specs for 5 products.
  2. Query all products with 16 GB or more RAM.
  3. Shred the ports array into one row per port.
  4. Add an indexed generated/computed column for ram_gb and confirm the plan improves.
  5. Produce a nested JSON document for one full order, items included.

🧭 In practice — JSON, XML, and semi-structured data

How to use it. MySQL has a native JSON type with -> and ->> operators; SQL Server stores JSON in NVARCHAR and reads it with JSON_VALUE, JSON_QUERY, and OPENJSON. Index a JSON path by extracting it into a generated column (MySQL) or a computed persisted column (SQL Server) and indexing that. Expected result: flexible attributes stored in a relational database without a column per attribute.

When to use it. For genuinely variable data — per-category product attributes, third-party API payloads you want to keep verbatim, sparse settings — and for accepting or emitting JSON at an API boundary.

Where to use it. The edges of a relational schema. Scenario: products in different categories have different attributes (screen size, wattage, capacity). A JSON attributes column avoids fifty mostly-NULL columns, while the fields everyone queries — price, stock, category — stay as proper typed columns.

When not to use it. Do not use JSON as a way to avoid designing a schema. Data inside JSON has no constraints, no foreign keys, no type checking, and no statistics, so the database cannot protect it or plan well against it. Anything you filter, join, or aggregate on regularly belongs in a real column. A table with one id and one data blob is a document database implemented badly.

Best practices. Keep the relational parts relational and use JSON for the genuinely variable tail. If you find yourself querying the same JSON path repeatedly, promote it to a generated column and index it — that is the supported way to get both flexibility and speed. Validate JSON on the way in (ISJSON, or MySQL’s native type), because malformed JSON discovered at read time is far more expensive to deal with.


59. Dynamic SQL, cursors, and set-based thinking

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡🔴 Intermediate–Expert 30 min Replace slow row-by-row loops with one statement · Know the rare times a cursor is right · Build dynamic SQL safely

[!NOTE] 📌 In plain words: This chapter is about how you think when you write SQL. Handle a whole group of rows in one statement (set-based) instead of one row at a time (cursors), and learn to build SQL safely when the exact query is only known while the program runs (dynamic SQL).

🌍 Analogy: Painting a fence. Row-by-row is painting each plank with a separate trip to the paint shop for every plank. Set-based is taking a wide roller and covering the whole fence in one pass.

59.1 🔄 Set-based thinking — the mindset that separates levels

[!NOTE] 📌 In plain words: SQL is a language for describing sets of rows. Programmers arriving from Java, C#, or Python instinctively write loops. In SQL, the loop is almost always the wrong answer.

-- ❌ 🟥 MSSQL — ROW-BY-ROW (procedural thinking): ~20 seconds on 100,000 rows
DECLARE @id INT, @price DECIMAL(10,2);
DECLARE c CURSOR FOR SELECT product_id, unit_price FROM products;
OPEN c;
FETCH NEXT FROM c INTO @id, @price;
WHILE @@FETCH_STATUS = 0
BEGIN
    UPDATE products SET unit_price = @price * 1.10 WHERE product_id = @id;
    FETCH NEXT FROM c INTO @id, @price;
END;
CLOSE c; DEALLOCATE c;
-- ✅ SET-BASED: ~0.2 seconds on the same data. One statement.
UPDATE products SET unit_price = unit_price * 1.10;

[!TIP] 💡 Cursors are often called “Row By Agonizing Row” (RBAR) for a reason. Every iteration is a separate statement with its own overhead. A 100x difference is typical, and it grows with the row count.

How to convert loop thinking into set thinking:

Procedural idea Set-based equivalent
“For each row, update it” One UPDATE with a WHERE
“For each row, look something up” A JOIN
“If X then A else B” CASE
“Accumulate a running total” SUM() OVER (ORDER BY ...)
“Compare a row to the previous one” LAG() / LEAD()
“Find the best row per group” ROW_NUMBER() or APPLY
“Build a list of things” STRING_AGG / GROUP_CONCAT
“Insert if missing, else update” MERGE / ON DUPLICATE KEY UPDATE
“Loop until done” A recursive CTE

59.2 🔁 Cursors — and the rare times they are right

-- 🟥 MSSQL cursor syntax
-- (a stand-in for a real "send an email" procedure, so the loop has something to call)
CREATE OR ALTER PROCEDURE usp_send_reminder @order_id INT, @name NVARCHAR(100)
AS
    PRINT CONCAT('Reminder queued for order ', @order_id, ' (', @name, ')');
GO

DECLARE @order_id INT, @customer_name NVARCHAR(100);

DECLARE order_cursor CURSOR
    LOCAL FAST_FORWARD                    -- 💡 fastest options: forward-only, read-only
FOR
    SELECT o.order_id, c.full_name
    FROM orders o JOIN customers c ON c.customer_id = o.customer_id
    WHERE o.status = 'Pending';

OPEN order_cursor;
FETCH NEXT FROM order_cursor INTO @order_id, @customer_name;

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Genuine per-row work, e.g. calling a procedure that sends an email
    EXEC usp_send_reminder @order_id = @order_id, @name = @customer_name;

    FETCH NEXT FROM order_cursor INTO @order_id, @customer_name;
END;

CLOSE order_cursor;
DEALLOCATE order_cursor;
-- 🟦 MySQL cursor syntax (only inside a stored routine)
DELIMITER $$
-- A stand-in for a real "send an email" procedure, so the loop has something to call
CREATE PROCEDURE usp_send_reminder(IN p_order_id INT, IN p_name VARCHAR(100))
BEGIN
    SELECT CONCAT('Reminder queued for order ', p_order_id, ' (', p_name, ')') AS reminder;
END$$

CREATE PROCEDURE usp_process_pending()
BEGIN
    DECLARE v_done      INT DEFAULT 0;
    DECLARE v_order_id  INT;
    DECLARE v_name      VARCHAR(100);

    DECLARE cur CURSOR FOR
        SELECT o.order_id, c.full_name
        FROM orders o JOIN customers c ON c.customer_id = o.customer_id
        WHERE o.status = 'Pending';

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1;   -- the loop terminator

    OPEN cur;
    read_loop: LOOP
        FETCH cur INTO v_order_id, v_name;
        IF v_done = 1 THEN LEAVE read_loop; END IF;

        CALL usp_send_reminder(v_order_id, v_name);
    END LOOP;
    CLOSE cur;
END$$
DELIMITER ;

CALL usp_process_pending();

[!IMPORTANT] 🎯 The legitimate uses of a cursor:

  • Calling an external procedure or API once per row (sending emails, queueing jobs)
  • Administrative scripts iterating over databases, tables, or indexes
  • Complex sequential logic where each row genuinely depends on the outcome of the previous one
  • Deliberately processing in small batches to avoid long locks

Everything else should be set-based. If you are writing a cursor to transform data, stop and find the UPDATE ... JOIN, the window function, or the MERGE.

[!TIP] 💡 A WHILE loop over batches is not the same as a cursor, and it is often correct. Deleting 50 million rows in 5000-row batches is a loop, but each iteration is a set-based statement. That is good practice, not RBAR.

59.3 ⚙️ Dynamic SQL

[!NOTE] 📌 In plain words: SQL that builds SQL as a string and then executes it. Necessary when the structure — table names, column names, the set of filters — is not known until runtime.

-- 🟥 MSSQL: sp_executesql is the safe way (it passes values as parameters AND reuses plans)
DECLARE @sql NVARCHAR(MAX);
DECLARE @country NVARCHAR(60) = 'Singapore';

SET @sql = N'SELECT customer_id, full_name, city FROM customers WHERE country = @p_country;';

EXEC sp_executesql @sql, N'@p_country NVARCHAR(60)', @p_country = @country;
-- 🟥 MSSQL: a real optional-filter search procedure
CREATE OR ALTER PROCEDURE usp_search_orders
    @customer_id INT          = NULL,
    @status      VARCHAR(20)  = NULL,
    @from_date   DATE         = NULL,
    @to_date     DATE         = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sql NVARCHAR(MAX) = N'
        SELECT order_id, customer_id, order_date, status
        FROM orders
        WHERE 1 = 1';

    IF @customer_id IS NOT NULL SET @sql += N' AND customer_id = @p_customer_id';
    IF @status      IS NOT NULL SET @sql += N' AND status      = @p_status';
    IF @from_date   IS NOT NULL SET @sql += N' AND order_date >= @p_from_date';
    IF @to_date     IS NOT NULL SET @sql += N' AND order_date <  @p_to_date';

    SET @sql += N' ORDER BY order_date DESC;';

    EXEC sp_executesql @sql,
        N'@p_customer_id INT, @p_status VARCHAR(20), @p_from_date DATE, @p_to_date DATE',
        @p_customer_id = @customer_id, @p_status = @status,
        @p_from_date = @from_date, @p_to_date = @to_date;
END;
GO

[!TIP] 💡 Why build the string instead of writing (@status IS NULL OR status = @status)? Because the “catch-all” form produces one plan for all parameter combinations, which is usually terrible for most of them. Dynamic SQL generates a tight plan per combination, each cached separately. The alternative is OPTION (RECOMPILE) on the static version — simpler, but it re-plans every execution.

-- 🟦 MySQL: PREPARE / EXECUTE / DEALLOCATE
SET @sql = 'SELECT customer_id, full_name FROM customers WHERE country = ?';
SET @country = 'Singapore';

PREPARE stmt FROM @sql;
EXECUTE stmt USING @country;
DEALLOCATE PREPARE stmt;

A genuinely useful admin script:

-- 🟥 MSSQL: generate and run an index rebuild for every fragmented index
DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'ALTER INDEX ' + QUOTENAME(i.name)
             + N' ON ' + QUOTENAME(SCHEMA_NAME(t.schema_id)) + N'.' + QUOTENAME(t.name)
             + N' REBUILD;' + CHAR(13)
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') ips
JOIN sys.indexes i ON i.object_id = ips.object_id AND i.index_id = ips.index_id
JOIN sys.tables  t ON t.object_id = i.object_id
WHERE ips.avg_fragmentation_in_percent > 30 AND ips.page_count > 1000 AND i.name IS NOT NULL;

PRINT @sql;         -- ✅ ALWAYS look at it before you run it
-- EXEC sp_executesql @sql;

[!WARNING] ⚠️ Every dynamic SQL statement is a potential injection point. Re-read Chapter 55: parameterize values, QUOTENAME/allow-list names, never glue raw user input into SQL.

[!TIP] 💡 And always PRINT before you EXEC. Dynamic SQL that generates 400 ALTER statements deserves a human read-through before it touches anything.

59.4 🧪 Try it yourself

  1. Write a cursor that raises every price by 10%, then replace it with one UPDATE. Time both.
  2. Convert this to set-based: “for each customer, count their orders and write it to a column.”
  3. Write a safe dynamic search procedure with three optional filters.
  4. Write a dynamic script that generates SELECT COUNT(*) for every table in ShopDB, and print it.
  5. Name two situations where a cursor is genuinely the right tool.

🧭 In practice — dynamic SQL, cursors, and set-based thinking

How to use it. Build SQL as a string only when the structure must vary — an unknown pivot column list, an optional-filter search. Execute it with sp_executesql and parameters (SQL Server) or a prepared statement (MySQL). A cursor walks a result set row by row; almost always, a single set-based statement replaces it. Expected result: the flexibility you needed, without an injection hole and without row-by-row processing.

When to use it. Dynamic SQL for genuinely dynamic structure. Cursors only for genuinely sequential work — administrative loops over databases, or a running calculation that truly cannot be expressed as a set operation.

Where to use it. Search screens and administrative scripts. Scenario: a product search with four optional filters. Building only the clauses the user supplied lets the optimiser choose a good plan for each combination, where one query with (@p IS NULL OR col = @p) repeated four times often produces one bad plan for all of them.

When not to use it. Never concatenate a value into dynamic SQL — parameterise it. Only identifiers need to be built into the string, and those must be validated against an allow-list and quoted (QUOTENAME). Avoid cursors for data processing: a cursor over 100,000 rows does 100,000 round trips of work the engine could do in one set-based statement, and it is the single most common cause of “the database is slow” that turns out to be the code.

Best practices. Think in sets, not loops — that shift is what separates people who write SQL from people who write loops in SQL. When you catch yourself writing a cursor, ask what the equivalent UPDATE ... FROM or MERGE would be. When you must use dynamic SQL, print the generated statement during development so you can read exactly what will run.


60. Collation, character sets, and Unicode

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡🔴 Intermediate–Expert 35 min Store any language without losing characters · Read a collation name · Fix the “collation conflict” error · Choose the right collation before the first row

[!NOTE] 📌 In plain words: A character set decides which characters can be stored. A collation decides how they sort and compare — whether 'amara' = 'AMARA', whether 'café' = 'cafe', and whether 'Zoe' sorts before or after 'ábaco'.

🌍 Analogy: A character set is the alphabet your language uses. A collation is the dictionary rulebook that says how to alphabetise it. Two people can share an alphabet and still disagree on the order — Swedish files Ö at the very end, German files it under O. The database has to be told which rulebook to follow.

[!WARNING] This is the chapter people skip, and then spend a week debugging. Collation causes three classic production failures: data silently destroyed on insert, joins that refuse to run, and indexes that stop being used. All three appear below.

60.1 🔤 Character sets: what can actually be stored

Engine Non-Unicode type Unicode type Recommended today
🟥 MSSQL VARCHAR / CHAR — 1 byte per character, limited to one code page (a small character set for one group of languages) NVARCHAR / NCHAR — UTF-16, 2–4 bytes NVARCHAR, or VARCHAR with a _UTF8 collation (2019+)
🟦 MySQL latin1 charset utf8mb4 charset utf8mb4, always

Here is what actually happens when you store Japanese text in each strategy:

-- 🟥 MSSQL: three columns, three character-handling strategies
CREATE TABLE dbo.collation_demo (
    legacy    VARCHAR(50)  COLLATE SQL_Latin1_General_CP1_CI_AS      NOT NULL,  -- code page 1252
    utf8_col  VARCHAR(50)  COLLATE Latin1_General_100_CI_AS_SC_UTF8  NOT NULL,  -- UTF-8 (2019+)
    unicode   NVARCHAR(50)                                           NOT NULL   -- UTF-16
);

-- NCHAR(26085) + NCHAR(26412) is 日本 ("Japan")
DECLARE @jp NVARCHAR(10) = NCHAR(26085) + NCHAR(26412);
INSERT INTO dbo.collation_demo (legacy, utf8_col, unicode) VALUES (@jp, @jp, @jp);

SELECT legacy, utf8_col, unicode,
       DATALENGTH(legacy)   AS bytes_legacy,
       DATALENGTH(utf8_col) AS bytes_utf8,
       DATALENGTH(unicode)  AS bytes_nvarchar,
       LEN(legacy)          AS chars_legacy,
       LEN(utf8_col)        AS chars_utf8,
       LEN(unicode)         AS chars_nvarchar
FROM dbo.collation_demo;

Result:

legacy utf8_col unicode bytes_legacy bytes_utf8 bytes_nvarchar chars_legacy chars_utf8 chars_nvarchar
?? 日本 日本 2 6 4 2 2 2

[!WARNING] ⚠️ Look at the first column. The data is gone. SQL Server did not raise an error, did not warn, and did not roll back. It replaced every character the code page could not represent with a literal ? — and there is no way to recover it. This is the most damaging collation mistake there is, and it happens silently in production every day.

[!TIP] 💡 DATALENGTH vs LEN. LEN counts characters; DATALENGTH counts bytes. They agree only for single-byte data. When you size a column or estimate storage, DATALENGTH is the one that matters. Notice the UTF-8 column needed 6 bytes for the same two characters UTF-16 stored in 4 — UTF-8 is smaller for Latin text and larger for Chinese, Japanese, and Korean (CJK) text. Pick by what your users actually type.

🔀 MySQL has exactly the same trap under a different name. The old utf8 charset in MySQL is not real UTF-8 — it is a three-byte subset that cannot store emoji or some CJK characters. The real one is utf8mb4.

-- 🟦 MySQL: always utf8mb4, never utf8  (exactly how ShopDB was created in Chapter 4)
CREATE DATABASE IF NOT EXISTS ShopDB
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_0900_ai_ci;

-- Check what you actually have
SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME
FROM information_schema.SCHEMATA
WHERE SCHEMA_NAME = 'ShopDB';

-- Any column still on an older charset is a bug waiting to happen
SELECT TABLE_NAME, COLUMN_NAME, CHARACTER_SET_NAME, COLLATION_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'ShopDB'
  AND CHARACTER_SET_NAME IS NOT NULL
  AND CHARACTER_SET_NAME <> 'utf8mb4';

[!TIP] The rule, in one line: 🟥 MSSQL — use NVARCHAR, or VARCHAR with a _UTF8 collation. 🟦 MySQL — use utf8mb4 for every database, table, column and the client connection. Getting the server right and the connection wrong produces exactly the same ? corruption.

60.2 📖 Reading a collation name

Collation names look like noise until you realise they are just a list of flags. (In the MySQL name, 0900 means version 9.0 of the Unicode Collation Algorithm — UCA — the official sorting rules.)

🟥 MSSQL     Latin1_General_100_CI_AS_SC_UTF8
             └──────┬──────┘ └┬┘ └┬┘└┬┘ └┬┘└─┬─┘
             language/culture  │   │  │   │  encoding
                        version┘   │  │   └── supplementary characters (emoji)
                         case ─────┘  └────── accent

🟦 MySQL     utf8mb4_0900_ai_ci
             └──┬──┘ └─┬┘ └┬┘└┬┘
             charset   │   │  └── case-insensitive
                  UCA version└──── accent-insensitive
Flag Means Effect
CI / _ci Case Insensitive 'amara' = 'AMARA'
CS / _cs Case Sensitive 'amara' <> 'AMARA'
AS / _as Accent Sensitive 'café' <> 'cafe'
AI / _ai Accent Insensitive 'café' = 'cafe'
SC 🟥 Supplementary characters Emoji and rare CJK handled correctly by LEN, SUBSTRING
BIN2 / _bin Binary Compares the raw character numbers. Fastest, and completely literal ('a' ≠ 'A')
-- 🟥 MSSQL: watch the flags actually take effect
SELECT
    CASE WHEN 'Amara' = 'AMARA' THEN 'equal' ELSE 'different' END                        AS default_ci,
    CASE WHEN 'Amara' COLLATE Latin1_General_CS_AS = 'AMARA' COLLATE Latin1_General_CS_AS
         THEN 'equal' ELSE 'different' END                                               AS case_sensitive,
    CASE WHEN N'cafe' = N'caf' + NCHAR(233) THEN 'equal' ELSE 'different' END            AS accent_sensitive,
    CASE WHEN N'cafe' COLLATE Latin1_General_CI_AI = (N'caf' + NCHAR(233)) COLLATE Latin1_General_CI_AI
         THEN 'equal' ELSE 'different' END                                               AS accent_insensitive;

Result:

default_ci case_sensitive accent_sensitive accent_insensitive
equal different different equal

[!TIP] 💡 Accent-insensitive collations are how you build a forgiving search box. A customer who types jose should find José. Latin1_General_CI_AI does that for you with no REPLACE gymnastics.

[!WARNING] ⚠️ Collations contain linguistic surprises. Under Latin1_General_CI_AS, N'straße' = N'strasse' returns equal — German ß expands to ss under the Unicode rules. That is correct behaviour, and it will still astonish you the first time a “duplicate” appears that does not look like one.

60.3 🧭 Finding out what you actually have

-- 🟥 MSSQL: the four levels — server, database, column, expression
SELECT SERVERPROPERTY('Collation')              AS server_collation,
       DATABASEPROPERTYEX('ShopDB','Collation') AS database_collation;

SELECT c.name AS column_name, c.collation_name
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('dbo.customers')
  AND c.collation_name IS NOT NULL;

-- Every collation this server knows about
SELECT name FROM sys.fn_helpcollations()
WHERE name LIKE 'Latin1_General_100_CI_AS%UTF8';

Result (a default install):

server_collation database_collation
SQL_Latin1_General_CP1_CI_AS SQL_Latin1_General_CP1_CI_AS
column_name collation_name
full_name SQL_Latin1_General_CP1_CI_AS
email SQL_Latin1_General_CP1_CI_AS
… …

[!TIP] 💡 Collation is inherited downward: server → database → column → expression, and each level may override the one above. A column with no explicit COLLATE takes the database default; a database created with no COLLATE takes the server default, which was fixed at install time. This is why “our test server sorts differently from production” is such a common bug report — and why the collation belongs in your build script, not in the installer wizard’s memory.

-- 🟦 MySQL: the same four levels
SELECT @@character_set_server,   @@collation_server;
SELECT @@character_set_database, @@collation_database;
SHOW FULL COLUMNS FROM customers;          -- the Collation column
SHOW COLLATION WHERE Charset = 'utf8mb4';

60.4 💥 The collation conflict error

This is the one that stops a migration dead, usually the moment you join a new table to a legacy one.

-- 🟥 MSSQL: a legacy table carrying a different collation
CREATE TABLE dbo.legacy_customers (
    legacy_id INT PRIMARY KEY,
    email     NVARCHAR(150) COLLATE Latin1_General_CS_AS NOT NULL
);
INSERT INTO dbo.legacy_customers VALUES (1, N'amara.silva@example.com');

-- ❌ This fails
SELECT c.customer_id
FROM customers c
JOIN dbo.legacy_customers l ON l.email = c.email;
Msg 468, Level 16, State 9
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS"
and "Latin1_General_CS_AS" in the equal to operation.
-- ✅ 🟥 MSSQL — fix 1 (quick): force one side into the other's collation
SELECT c.customer_id, l.legacy_id
FROM customers c
JOIN dbo.legacy_customers l
  ON l.email = c.email COLLATE Latin1_General_CS_AS;

-- ✅ Fix 2 (quick, and still works when deployed to another database): use the database default
SELECT c.customer_id, l.legacy_id
FROM customers c
JOIN dbo.legacy_customers l
  ON l.email = c.email COLLATE DATABASE_DEFAULT;

-- ✅ Fix 3 (the real fix): make the column match, permanently
ALTER TABLE dbo.legacy_customers
    ALTER COLUMN email NVARCHAR(150) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL;

🔀 MySQL raises the equivalent error — ERROR 1267: Illegal mix of collations — and takes the same three fixes: a COLLATE on one side of the comparison, or ALTER TABLE … CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci to settle it for good.

[!WARNING] ⚠️ ALTER COLUMN with a new collation rewrites the column, and it fails outright if an index, constraint, or computed column depends on it. Drop those first, alter, then recreate them. On a large table this is a maintenance-window operation, not a Tuesday-afternoon one.

60.5 🐌 The performance trap: COLLATE kills your index

This is the quiet one. The query works, returns the right answer, and is a hundred times slower than it should be.

-- 🟥 MSSQL: compare the two plans
SET SHOWPLAN_TEXT ON;
GO
SELECT customer_id FROM customers WHERE email = N'amara.silva@example.com';
GO
SELECT customer_id FROM customers
WHERE email COLLATE Latin1_General_CS_AS = N'amara.silva@example.com';
GO
SET SHOWPLAN_TEXT OFF;
GO

The plans:

✅ Index Seek(OBJECT:(customers.UQ__customer__…), SEEK:(customers.email=[@1]) ORDERED FORWARD)

❌ Index Scan(OBJECT:(customers.UQ__customer__…),
     WHERE:(CONVERT(nvarchar(150),customers.email,0)=CONVERT_IMPLICIT(nvarchar(4000),[@1],0)))

[!WARNING] 💥 COLLATE on the column side is a function on the column. The index is physically sorted in its own collation, so the moment you demand a different one the stored order is the wrong order and the index can no longer jump straight to the row. It is precisely the same failure as WHERE UPPER(email) = … from Chapter 48, and it has the same three cures:

  • Put the COLLATE on the literal or parameter side, never the column side, where you can.
  • Fix the column’s collation permanently so no COLLATE is needed at all.
  • If you genuinely need both orderings, add a persisted computed column in the other collation and index that (Chapter 41).

60.6 🎯 Choosing a collation — the decision table

Situation Choose
A brand-new application, any language 🟥 Latin1_General_100_CI_AS_SC_UTF8 (or NVARCHAR with Latin1_General_100_CI_AS_SC) · 🟦 utf8mb4_0900_ai_ci
Names, emails, search boxes — humans typing Case-insensitive (CI). Users do not capitalise consistently
Passwords, hashes, tokens, API keys, file paths Binary (_BIN2 / _bin). Never fold case on a secret
Codes: SKU, ISO country, currency Case-insensitive is fine, but have the application save them in one consistent case
Forgiving customer search (jose finds José) Accent-insensitive (AI) on that column, or an indexed computed column
A specific locale must sort correctly (Swedish, Turkish, Vietnamese) The matching language collation — Finnish_Swedish_CI_AS, Turkish_CI_AS, Vietnamese_CI_AS
Joining to a system you do not control Match their collation, or normalise once at the boundary

[!WARNING] ⚠️ The Turkish-I problem. In Turkish, the uppercase of i is İ, not I. Under Turkish_CI_AS, 'ID' = 'id' is false. If your schema does case-insensitive lookups on machine identifiers and someone deploys into a Turkish locale, things break in ways that look like magic. This is exactly why binary collations are the correct choice for machine identifiers.

[!IMPORTANT] Decide the collation before the first row goes in. Changing it later means rebuilding every string column, every index that touches one, and re-testing every comparison in the application. It is one of the few database decisions that is genuinely expensive to reverse.

60.7 🧪 Try it yourself

  1. Insert a non-Latin string (use NCHAR(26085) + NCHAR(26412)) into a VARCHAR column with a CP1 collation. Confirm you get ?? back, and that no error was raised.
  2. Compare DATALENGTH and LEN for the same emoji stored under an _SC collation and a non-_SC one.
  3. Reproduce Msg 468, then fix it all three ways.
  4. Prove with SET SHOWPLAN_TEXT ON that COLLATE on an indexed column turns a seek into a scan.
  5. 🟦 MySQL: create a table with the old utf8 charset, insert an emoji, and read the error. Convert it to utf8mb4 and try again.

🧭 In practice — collation, character sets, and Unicode

How to use it. A character set decides which characters can be stored; a collation decides how they sort and compare. In MySQL use utf8mb4 — the older utf8 is only three bytes and cannot store emoji or many characters. In SQL Server, NVARCHAR covers Unicode. Expected result: text that stores, sorts, and compares the way your users expect, in every language you support.

When to use it. When designing any schema that will hold names, addresses, or user-entered text — which is nearly all of them — and when a join between two tables mysteriously fails or runs slowly.

Where to use it. Internationalised systems. Scenario: joining two tables whose text columns have different collations raises a collation-conflict error, or silently forces a conversion that disables the index. This is a routine cause of a join that works in one database and is slow in another.

When not to use it. Do not mix collations within a database without a deliberate reason. Do not choose a case-sensitive collation and then rely on the application to lowercase everything — the two will disagree eventually. And do not use MySQL’s utf8 for anything new; the name is a historical trap.

Best practices. Set the character set and collation once, at database creation, and keep them consistent across every table and column. Understand what your collation does with case and accents, because it decides whether 'Jose' finds 'José' and whether 'ABC' equals 'abc' — both are business decisions, not technical details. Remember that character length and byte length differ, which affects both VARCHAR(n) sizing and any truncation logic.


61. Time zones and global data

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡🔴 Intermediate–Expert 35 min Store time in UTC · Convert between time zones · Filter by a customer’s local day without slowing the query · Survive daylight saving changes

[!NOTE] 📌 In plain words: A timestamp with no time zone attached is only half a fact. 2026-06-15 14:30 is meaningless until someone says where. This chapter is how you store the “where” without poisoning your data.

🌍 Analogy: A photograph with no location tag. You can see what happened, but you cannot place it. And unlike a photo, a mis-tagged timestamp is unrecoverable — once you have a table full of mixed local times, no query on earth can tell you which zone each row meant.

[!IMPORTANT] The single rule that makes all of this manageable: store UTC. Convert to local time at the edge — at display time, in a report, in the application. Every rule below is a consequence of this one.

61.1 🧭 The four ways people store time, ranked

Approach Storage Verdict
Local wall-clock time, zone not recorded DATETIME2 / DATETIME ❌ Broken. Ambiguous twice a year, unsortable across regions, unfixable later
UTC in a plain datetime column 🟥 DATETIME2(0) · 🟦 DATETIME ✅ The default choice. Simple, compact, indexes well, sorts correctly worldwide
UTC plus a zone name column DATETIME2 + a text column for the zone name ✅ Use when you must later reconstruct the user’s local reading of the event
Offset-aware type 🟥 DATETIMEOFFSET · 🟦 TIMESTAMP ⚠️ Useful, with caveats — see 61.4

[!WARNING] ⚠️ An offset is not a time zone. +01:00 tells you the offset at that instant; it does not tell you that the user was in London, and it cannot tell you what the offset will be next July. If you need to answer “what will 9 a.m. local look like for this user in six months?”, you must store the zone name ('GMT Standard Time'), not the offset.

61.2 🕐 Getting the current time, correctly

-- 🟥 MSSQL
SELECT SYSDATETIME()        AS server_local,   -- the server's local clock — avoid
       SYSUTCDATETIME()     AS utc_now,        -- ✅ what you should be storing
       SYSDATETIMEOFFSET()  AS with_offset;    -- local + the server's current offset

Result:

server_local utc_now with_offset
2026-09-09 21:46:42.0836051 2026-09-09 19:46:42.0836051 2026-09-09 21:46:42.0836051 +02:00
-- 🟦 MySQL
SELECT NOW()        AS session_local,   -- honours @@session.time_zone
       UTC_TIMESTAMP() AS utc_now,      -- ✅ what you should be storing
       @@global.time_zone  AS global_tz,
       @@session.time_zone AS session_tz;

[!WARNING] ⚠️ GETDATE() and NOW() return the server’s idea of local time. That is a machine setting a server administrator can change, and it jumps twice a year for daylight saving time (DST). SYSUTCDATETIME() / UTC_TIMESTAMP() never move. Default every audit column to UTC:

-- 🟥 MSSQL
CREATE TABLE dbo.audit_utc_demo (
    id         INT IDENTITY(1,1) PRIMARY KEY,
    created_at DATETIME2(0) NOT NULL DEFAULT SYSUTCDATETIME()
);

-- 🟦 MySQL
CREATE TABLE audit_utc_demo (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    created_at DATETIME NOT NULL DEFAULT (UTC_TIMESTAMP())
);

61.3 🔄 Converting between zones

🟥 MSSQL uses AT TIME ZONE (2016+). It takes the Windows zone names listed in sys.time_zone_info and it handles DST for you.

-- 🟥 MSSQL: one UTC instant, seen from four places
DECLARE @utc DATETIME2(0) = '2026-06-15 14:30:00';

SELECT
    @utc                                                                              AS stored_utc,
    @utc AT TIME ZONE 'UTC'                                                           AS tagged_utc,
    @utc AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time'                        AS ist,
    @utc AT TIME ZONE 'UTC' AT TIME ZONE 'GMT Standard Time'                          AS london,
    CAST(@utc AT TIME ZONE 'UTC' AT TIME ZONE 'Tokyo Standard Time' AS DATETIME2(0))  AS tokyo_local;

Result:

stored_utc tagged_utc ist london tokyo_local
2026-06-15 14:30:00 2026-06-15 14:30:00 +00:00 2026-06-15 20:00:00 +05:30 2026-06-15 15:30:00 +01:00 2026-06-15 23:30:00

[!TIP] 💡 Read that as two steps, because it is two steps. The first AT TIME ZONE 'UTC' labels a plain DATETIME2 (one with no zone attached) as being UTC — it changes no digits, it only attaches an offset. The second AT TIME ZONE converts that offset-aware value into another zone. Skipping the first step is the number-one AT TIME ZONE bug: without it, SQL Server assumes the value is already in the server’s local zone.

-- 🟥 The same instant six months earlier — DST is handled for you
DECLARE @winter DATETIME2(0) = '2026-01-15 14:30:00';
SELECT @winter AT TIME ZONE 'UTC' AT TIME ZONE 'GMT Standard Time' AS london_winter;

Result:

london_winter
2026-01-15 14:30:00 +00:00

[!IMPORTANT] 🎯 That is the whole point. London is +01:00 in June and +00:00 in January, and you did not have to know that. Hard-coding DATEADD(HOUR, 1, …) would have been wrong for half the year.

-- 🟥 What zones does this server know?
SELECT name, current_utc_offset, is_currently_dst
FROM sys.time_zone_info
ORDER BY name;
name current_utc_offset is_currently_dst
Afghanistan Standard Time +04:30 0
Alaskan Standard Time -08:00 1
Arab Standard Time +03:00 0
… … …
-- 🟥 Two more offset tools
SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')                                AS shifted,
       TODATETIMEOFFSET(CAST('2026-06-15 14:30:00' AS DATETIME2(0)), '+05:30')    AS tagged;
Function What it does
TODATETIMEOFFSET(dt, offset) Labels a plain datetime with an offset. Digits unchanged
SWITCHOFFSET(dto, offset) Converts an offset-aware value to a different offset. Same instant, different digits

🔀 MySQL uses CONVERT_TZ. It takes the standard IANA zone names used by Linux and most apps ('Asia/Kolkata'), and it returns NULL — silently — if the zone tables have not been loaded.

-- 🟦 MySQL
SELECT CONVERT_TZ('2026-06-15 14:30:00', 'UTC', 'Asia/Kolkata') AS ist,
       CONVERT_TZ('2026-06-15 14:30:00', 'UTC', 'Europe/London') AS london;

-- ⚠️ Returns NULL? The named zone tables are not loaded. Check first:
SELECT COUNT(*) AS zones_loaded FROM mysql.time_zone_name;

[!WARNING] ⚠️ The MySQL time-zone tables are not populated by default on many builds. Load them once, as an administrator, or CONVERT_TZ will hand you NULL for every named zone while still working for numeric offsets like '+05:30':

# Linux/macOS, run once per server
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

On Windows, download the pre-built time-zone SQL bundle from the MySQL site and load it the same way.

61.4 📐 DATETIMEOFFSET and TIMESTAMP — the caveats

-- 🟥 MSSQL: DATETIMEOFFSET stores the instant AND the offset it was captured at
CREATE TABLE dbo.events_dto (
    event_id     INT IDENTITY(1,1) PRIMARY KEY,
    occurred_at  DATETIMEOFFSET(0) NOT NULL     -- 8 bytes vs 6 for DATETIME2(0)
);

-- Measure it rather than guessing
DECLARE @a DATETIME2(0)     = SYSUTCDATETIME(),
        @b DATETIMEOFFSET(0) = SYSDATETIMEOFFSET(),
        @c DATETIMEOFFSET(7) = SYSDATETIMEOFFSET();
SELECT DATALENGTH(@a) AS datetime2_0, DATALENGTH(@b) AS dto_0, DATALENGTH(@c) AS dto_7;
-- 6 | 8 | 10
  Pro Con
🟥 DATETIMEOFFSET Never ambiguous; the capture offset is preserved 8–10 bytes vs 6; comparisons normalise to UTC anyway; still does not tell you the zone
🟦 TIMESTAMP Auto-converts to the session zone on read Cannot store dates after January 2038; conversion depends on a session variable, so the same row reads differently for different connections
🟦 DATETIME Stores exactly what you gave it, forever No conversion at all — you must guarantee it is UTC

[!WARNING] ⚠️ 🟦 MySQL TIMESTAMP is a trap in disguise. It looks like the “correct” type because it converts automatically — but the conversion depends on @@session.time_zone, which differs per connection. A report run from a cron job on the server and the same report run from a developer’s laptop can legitimately disagree. And the 2038 limit is real. Use DATETIME holding UTC.

61.5 🚀 The SARGability trap (the one that costs you a night)

Converting the column to local time in a WHERE clause is a function on a column — it stops the index being used, exactly as in Chapter 48.

The examples in this section and the next use a small events table: the UTC instant, plus the zone the user was in.

-- 🟥 MSSQL
CREATE TABLE dbo.events_utc (
    event_id     INT IDENTITY(1,1) PRIMARY KEY,
    event_name   NVARCHAR(60) NOT NULL,
    occurred_utc DATETIME2(0) NOT NULL,      -- always UTC
    tz_name      SYSNAME      NOT NULL       -- the zone the user was in
);

INSERT INTO dbo.events_utc (event_name, occurred_utc, tz_name) VALUES
 (N'Checkout', '2026-06-15 23:30:00', 'India Standard Time'),
 (N'Checkout', '2026-06-15 18:45:00', 'Tokyo Standard Time'),
 (N'Checkout', '2026-01-15 23:30:00', 'GMT Standard Time');
-- ❌ 🟥 MSSQL: converts every row in the table before it can filter
SELECT * FROM dbo.events_utc
WHERE CAST(occurred_utc AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time' AS DATE) = '2026-06-16';

Convert the boundaries instead, once, and compare the raw column:

-- ✅ MSSQL: "one local day in Mumbai", as a SARGable UTC range
DECLARE @tz        SYSNAME = 'India Standard Time';
DECLARE @local_day DATE    = '2026-06-16';

DECLARE @from DATETIME2(0) =
    CAST(CAST(@local_day AS DATETIME2(0))                  AT TIME ZONE @tz AT TIME ZONE 'UTC' AS DATETIME2(0));
DECLARE @to   DATETIME2(0) =
    CAST(CAST(DATEADD(DAY, 1, @local_day) AS DATETIME2(0)) AT TIME ZONE @tz AT TIME ZONE 'UTC' AS DATETIME2(0));

SELECT @from AS utc_from, @to AS utc_to;

SELECT event_id, occurred_utc
FROM dbo.events_utc
WHERE occurred_utc >= @from
  AND occurred_utc <  @to;         -- half-open, as always

Result:

utc_from utc_to
2026-06-15 18:30:00 2026-06-16 18:30:00

[!TIP] 💡 This is the half-open range pattern from Chapter 14, plus a zone conversion on the endpoints. Two conversions instead of ten million, and the index still seeks. Every “show me today’s orders in the customer’s local time” report should be written this way.

61.6 🌍 Storing the user’s zone, and reporting in it

When the user’s local reading of an event matters — invoices, opening hours, scheduled jobs, legal deadlines — store the zone name alongside the UTC instant.

-- 🟥 MSSQL: each event in the user's own zone (dbo.events_utc, created in 61.5)
SELECT event_id,
       occurred_utc,
       CAST(occurred_utc AT TIME ZONE 'UTC' AT TIME ZONE tz_name AS DATETIME2(0)) AS local_time,
       CAST(occurred_utc AT TIME ZONE 'UTC' AT TIME ZONE tz_name AS DATE)         AS local_date,
       tz_name
FROM dbo.events_utc
ORDER BY event_id;

Result:

event_id occurred_utc local_time local_date tz_name
1 2026-06-15 23:30:00 2026-06-16 05:00:00 2026-06-16 India Standard Time
2 2026-06-15 18:45:00 2026-06-16 03:45:00 2026-06-16 Tokyo Standard Time
3 2026-01-15 23:30:00 2026-01-15 23:30:00 2026-01-15 GMT Standard Time

[!IMPORTANT] 🎯 Notice rows 1 and 2. Both happened on 15 June UTC, and both are “16 June” to the customer. A daily sales report grouped on occurred_utc would put them in the wrong bucket for every customer east of Greenwich. Grouping on local_date is what the business actually asked for.

[!TIP] 💡 AT TIME ZONE accepts a column, not just a literal — that is what makes the per-user zone pattern possible in a single query. It is not free, though: it is a row-by-row conversion, so keep it in the SELECT list and out of the WHERE clause (61.5).

61.7 🕳️ Daylight saving: the two hours that do not behave

Twice a year, local clock time misbehaves.

Problem What happens What to do
The gap (spring forward) 02:30 local simply does not exist on that date Never schedule at 02:00–03:00 local. AT TIME ZONE maps gap times forward
The overlap (autumn back) 01:30 local happens twice, with two different offsets Only UTC can distinguish them. This is why UTC storage is not negotiable
Rules change Governments move DST dates, sometimes with weeks of notice Keep the OS/zone tables patched. Never hard-code an offset

[!WARNING] ⚠️ A stored offset does not survive a rule change; a stored zone name does. If you save “this recurring meeting is at +01:00”, and the country abolishes DST, every future occurrence is now wrong. If you save “Europe/London, 09:00 local”, it stays correct — because the conversion is done fresh, from current rules, every time you read it.

[!TIP] Recurring events are the exception to “store UTC”. For something that repeats — a 09:00 daily standup, a monthly billing run — store the local wall-clock time plus the zone name, and compute the UTC instant at read time. Storing UTC for a recurring event bakes today’s DST rules into every future occurrence.

61.8 🎯 The time-zone checklist

  • ☐ Every timestamp column stores UTC, and the column name says so (created_utc, occurred_utc)
  • ☐ Defaults use SYSUTCDATETIME() 🟥 / UTC_TIMESTAMP() 🟦, never GETDATE() / NOW()
  • ☐ Application connections do not rely on the server’s local zone for anything
  • ☐ Where the user’s local reading matters, the zone name is stored, not an offset
  • ☐ Recurring schedules store local time + zone name, not a UTC instant
  • ☐ Date-range filters convert the boundaries, never the column
  • ☐ 🟦 MySQL: mysql.time_zone_name is populated, and it is checked after every server rebuild
  • ☐ OS and database time-zone data are patched like any other dependency

61.9 🧪 Try it yourself

  1. Take one UTC instant and render it in five zones with AT TIME ZONE. Repeat with a January date and explain every offset that changed.
  2. Write a “yesterday, in the customer’s local time” report over orders, with the filter fully SARGable.
  3. Add a tz_name column to customers, populate it, and produce a daily order count grouped by each customer’s local date.
  4. Prove the DST overlap problem: find the UTC instants that both map to 01:30 local on the autumn changeover in Europe/London.
  5. 🟦 MySQL: run CONVERT_TZ with a named zone. If it returns NULL, load the zone tables and try again.

🧭 In practice — time zones and global data

How to use it. Store instants in UTC, in a type that holds them precisely, and convert to local time only when displaying. SQL Server has DATETIMEOFFSET and AT TIME ZONE; MySQL has CONVERT_TZ and the time-zone tables (which must be loaded). Expected result: two events can always be correctly ordered, regardless of where they happened.

When to use it. As soon as users, servers, or data span more than one time zone — and in practice, from the start, because a system that begins in one country rarely stays there.

Where to use it. Any system with a global audience or cloud hosting. Scenario: an order placed at 01:30 during the end of daylight saving. In local time that hour occurs twice, so two orders can carry the same timestamp and no query can tell which came first. In UTC the instants are distinct and ordering is exact.

When not to use it. Do not store local times without an offset. Do not store a time zone as a fixed offset (+05:30) either — offsets change with daylight saving and occasionally by legislation; store the IANA zone name (Europe/London) and let the database resolve the offset for the date in question. Do not assume the server’s time zone; it is configuration, and it changes.

Best practices. Convert at the edges: UTC everywhere inside, local time only at display. Keep the time-zone data updated — governments change the rules, and a stale time-zone database silently produces wrong local times. For recurring events such as “9 a.m. every weekday”, store the local wall-clock time and the zone rather than a UTC instant, because the correct UTC moment shifts twice a year.


62. Temporal tables, history, and change tracking

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🔴 Expert 35 min Keep every past version of a row automatically · Query a table as it looked at any moment · Find what changed since the last sync

[!NOTE] 📌 In plain words: A normal table only knows the present. These features let the database remember every past version of every row, and let you query the table as it looked at any moment — without writing a single trigger.

🌍 Analogy: Version history in a document editor. The document still shows today’s text, but “restore an earlier version” is one click away, and nobody had to remember to save a copy.

[!TIP] 💡 You already met the manual version of this in Chapter 39 (audit triggers) and Chapter 53 (Slowly Changing Dimensions). This chapter is the engine doing it for you, correctly, at no maintenance cost.

62.1 🕰️ MSSQL temporal tables — history for free

-- 🟥 MSSQL 2016+: a system-versioned temporal table
CREATE TABLE dbo.product_prices (
    product_id   INT           NOT NULL PRIMARY KEY,
    unit_price   DECIMAL(10,2) NOT NULL,
    updated_by   NVARCHAR(60)  NOT NULL DEFAULT SYSTEM_USER,

    valid_from   DATETIME2(2) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    valid_to     DATETIME2(2) GENERATED ALWAYS AS ROW END   HIDDEN NOT NULL,
    PERIOD FOR SYSTEM_TIME (valid_from, valid_to)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.product_prices_history));

That is the whole setup. Now change some data:

-- 🟥 MSSQL
INSERT INTO dbo.product_prices (product_id, unit_price) VALUES (1, 1899.00), (2, 1099.00);

UPDATE dbo.product_prices SET unit_price = 1749.00 WHERE product_id = 1;
GO
WAITFOR DELAY '00:00:01';          -- see the warning below on why this is here
UPDATE dbo.product_prices SET unit_price = 1699.00 WHERE product_id = 1;
GO
-- 🟥 Every version that has ever existed
SELECT product_id, unit_price, valid_from, valid_to
FROM dbo.product_prices FOR SYSTEM_TIME ALL
ORDER BY product_id, valid_from;

Result:

product_id unit_price valid_from valid_to
1 1899.00 2026-09-09 19:46:57.49 2026-09-09 19:46:58.50
1 1749.00 2026-09-09 19:46:58.50 2026-09-09 19:46:59.52
1 1699.00 2026-09-09 19:46:59.52 9999-12-31 23:59:59.99
2 1099.00 2026-09-09 19:46:57.49 9999-12-31 23:59:59.99

[!TIP] 💡 9999-12-31 means “still current”. Rows in the history table have a real valid_to; the live row’s valid_to is the end of time. The periods are half-open — valid_to of one version is exactly valid_from of the next, so no instant is counted twice. Same discipline as date ranges in Chapter 14.

[!WARNING] ⚠️ The period columns are in UTC, always, regardless of the server’s local zone. That is deliberate and correct — see Chapter 61.

[!TIP] 💡 HIDDEN means “excluded from SELECT *“ — not “invisible”. SELECT * FROM dbo.product_prices returns only your three business columns, so adding versioning to an existing table does not break application code that used SELECT *. Name them explicitly and they appear.

[!WARNING] ⚠️ Two updates can collapse into one version, and both reasons surprise people.

  1. Precision. The period columns above are DATETIME2(2) — a 10 ms tick. Updates within the same tick can produce a zero-duration history version. It remains in the history table, but FOR SYSTEM_TIME filters it out. Higher precision reduces timestamp ties; it does not guarantee distinct times.
  2. Transactions. Every row version written inside one transaction gets the transaction’s start time. Two updates in one explicit transaction can therefore create an intermediate history version with valid_from = valid_to:
-- 🟥 MSSQL
BEGIN TRANSACTION;
    UPDATE dbo.product_prices SET unit_price = 1650.00 WHERE product_id = 1;   -- retained as a zero-duration history version
    UPDATE dbo.product_prices SET unit_price = 1600.00 WHERE product_id = 1;
COMMIT;
-- FOR SYSTEM_TIME omits the zero-duration intermediate version.
-- Query dbo.product_prices_history directly to inspect it.

Temporal queries reconstruct transaction-time states; direct history queries can also reveal zero-duration versions. Neither records attempted changes that roll back or the business reason for a change. See Microsoft’s temporal query semantics.

62.2 🔎 Querying the past

-- 🟥 What was the price at a specific moment?
DECLARE @t DATETIME2(2) = DATEADD(SECOND, -2, SYSUTCDATETIME());

SELECT product_id, unit_price
FROM dbo.product_prices FOR SYSTEM_TIME AS OF @t
ORDER BY product_id;
Clause Returns
FOR SYSTEM_TIME AS OF @t The table exactly as it looked at instant @t — one row per key
FOR SYSTEM_TIME FROM @a TO @b Versions active in the range; excludes ones that started exactly at @b
FOR SYSTEM_TIME BETWEEN @a AND @b Same, but includes versions that started exactly at @b
FOR SYSTEM_TIME CONTAINED IN (@a, @b) Only versions that both opened and closed inside the range
FOR SYSTEM_TIME ALL Everything, current and historical
-- 🟥 A range query
DECLARE @from DATETIME2(2) = DATEADD(MINUTE, -5, SYSUTCDATETIME());
DECLARE @to   DATETIME2(2) = SYSUTCDATETIME();

SELECT product_id, unit_price, valid_from, valid_to
FROM dbo.product_prices
FOR SYSTEM_TIME BETWEEN @from AND @to
ORDER BY product_id, valid_from;

[!WARNING] ⚠️ FOR SYSTEM_TIME will not accept a function call inline. Writing BETWEEN DATEADD(MINUTE,-5,SYSUTCDATETIME()) AND SYSUTCDATETIME() fails with “Incorrect syntax near ‘DATEADD’“. Assign to variables (or use literals) first, exactly as above. It catches everybody once.

[!IMPORTANT] 🎯 AS OF is how you answer questions nobody planned for: “What price did this customer actually see?”, “Reproduce the 3 a.m. report.”, “Who changed this, and what was it before?” — with a WHERE clause instead of a restore from backup.

62.3 🧭 Managing a temporal table

-- 🟥 Which tables are versioned?
SELECT t.name, t.temporal_type_desc, h.name AS history_table
FROM sys.tables t
LEFT JOIN sys.tables h ON h.object_id = t.history_table_id
WHERE t.temporal_type <> 0;
name temporal_type_desc history_table
product_prices SYSTEM_VERSIONED_TEMPORAL_TABLE product_prices_history
-- 🟥 Add versioning to an EXISTING table
ALTER TABLE dbo.suppliers
    ADD valid_from DATETIME2(2) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL
            CONSTRAINT df_suppliers_valid_from
            DEFAULT CONVERT(DATETIME2(2), '1900-01-01 00:00:00.00'),
        valid_to   DATETIME2(2) GENERATED ALWAYS AS ROW END   HIDDEN NOT NULL
            CONSTRAINT df_suppliers_valid_to
            DEFAULT CONVERT(DATETIME2(2), '9999-12-31 23:59:59.99'),
        PERIOD FOR SYSTEM_TIME (valid_from, valid_to);

ALTER TABLE dbo.suppliers
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.suppliers_history));

-- 🟥 Keep only two years of history (2017+)
ALTER TABLE dbo.suppliers
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.suppliers_history,
                                 HISTORY_RETENTION_PERIOD = 2 YEARS));
ALTER DATABASE ShopDB SET TEMPORAL_HISTORY_RETENTION ON;

-- Confirm it took
SELECT name, temporal_type_desc, history_retention_period, history_retention_period_unit_desc
FROM sys.tables WHERE name = 'suppliers';
-- suppliers | SYSTEM_VERSIONED_TEMPORAL_TABLE | 2 | YEAR

-- 🟥 Turning it off, and dropping cleanly
ALTER TABLE dbo.product_prices SET (SYSTEM_VERSIONING = OFF);   -- history becomes a normal table
DROP TABLE dbo.product_prices;
DROP TABLE dbo.product_prices_history;

[!WARNING] ⚠️ Use a constant in the past for valid_from, not SYSUTCDATETIME(). Defaulting the start of period to “now” on a table that already has rows fails with “Msg 13542 … there are open records with start of period set to a value in the future.” The existing rows have to be treated as having existed since before the versioning started, so '1900-01-01' (or any safely past constant) is the correct default.

[!WARNING] ⚠️ You cannot DROP a table while system versioning is on, and SYSTEM_VERSIONING = OFF leaves the history table behind as an ordinary table. Any teardown script must do all three steps in order, which is why the demo scripts in this guide guard with IF EXISTS (… temporal_type = 2) ALTER TABLE … SET (SYSTEM_VERSIONING = OFF) before dropping.

What temporal tables give you What they do not give you
Prior row versions while versioning is enabled Who changed it — set updated_by on every update; a SYSTEM_USER default only fills inserts
Correct behaviour under bulk loads and MERGE Why it changed — add a reason column if the business needs one
Point-in-time reads with normal SQL A record of who read data — only changes are recorded
History you can index (it is a real table) Free storage — a frequently changed table can generate a lot of history

[!TIP] 💡 Index the history table. It is a normal table and it grows fastest of anything in your schema. A clustered index on (key_column, valid_to) is the usual starting point, and 🟥 MSSQL supports a clustered columnstore index on it — often a 10× space saving for history you rarely read row-by-row.

62.4 📡 Change Tracking — “what changed since I last looked?”

Temporal tables answer “what did it look like then?”. Change Tracking answers a different question: “which rows do I need to sync?” — the question every cache, search index, and ETL job actually asks.

-- 🟥 MSSQL: enable at database level, then per table
ALTER DATABASE ShopDB SET CHANGE_TRACKING = ON
    (CHANGE_RETENTION = 3 DAYS, AUTO_CLEANUP = ON);

ALTER TABLE dbo.products ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = ON);
GO

-- In this isolated lab, capture a valid baseline before the demonstration update.
DECLARE @last_version BIGINT = CHANGE_TRACKING_CURRENT_VERSION();
UPDATE dbo.products SET unit_price = unit_price + 0 WHERE product_id = 1;

DECLARE @min_version BIGINT = CHANGE_TRACKING_MIN_VALID_VERSION(OBJECT_ID('dbo.products'));
IF @min_version IS NULL OR @last_version < @min_version
    THROW 50001, 'Invalid change-tracking baseline; reseed before enumerating changes', 1;

SELECT CHANGE_TRACKING_CURRENT_VERSION() AS current_version;
SELECT ct.product_id, ct.SYS_CHANGE_OPERATION, ct.SYS_CHANGE_VERSION
FROM CHANGETABLE(CHANGES dbo.products, @last_version) AS ct;

Result:

current_version   product_id SYS_CHANGE_OPERATION SYS_CHANGE_VERSION
1   1 U 1

[!TIP] 💡 The consumer pattern: store the version from a consistent completed synchronization. On the next run, validate it against the table’s minimum valid version, capture the next version, enumerate changes and read corresponding rows consistently before advancing the saved checkpoint. You get only the keys that changed, plus I / U / D for insert, update, delete. Join back to the base table for the current values.

[!WARNING] ⚠️ CHANGETABLE is checked when the batch is compiled, before anything runs. Enabling change tracking and querying CHANGETABLE in the same batch fails with “Change tracking is not enabled on table…”. Separate them with GO (or into two commands from the application).

[!WARNING] ⚠️ Validate the baseline before enumerating changes. Cleanup can make a stored version older than CHANGE_TRACKING_MIN_VALID_VERSION(OBJECT_ID(...)); CHANGETABLE does not reliably raise an error for an obsolete baseline, and its results must not be treated as complete. Reinitialize if the baseline is invalid. A production consumer should validate, capture its next version and read changes/base rows in a consistent snapshot transaction; snapshot isolation must be enabled first. See Microsoft’s consumer pattern.

62.5 ⚖️ Which history mechanism should you use?

Need 🟥 MSSQL 🟦 MySQL
Full row history, point-in-time reads Temporal tables Trigger-written history table, or an SCD Type 2 design
“What changed since version N” for sync/ETL Change Tracking (keys only, lightweight) Tools that read the binary log (Debezium, Maxwell)
Full before/after values streamed to a pipeline Change Data Capture (CDC) Binlog with binlog_format = ROW
Who did what, for compliance SQL Server Audit Enterprise Audit plugin, or the general query log
A handful of columns on one table A simple updated_at / updated_by pair Same

[!WARNING] ⚠️ Check your edition before designing around CDC. Change Data Capture requires SQL Server Agent and is not available on Express. Change Tracking is available on every edition including Express, which is one reason it is the more portable choice.

🔀 MySQL has no built-in system versioning. The three realistic options are: a history table maintained by AFTER INSERT/UPDATE/DELETE triggers (Chapter 39); an SCD Type 2 design where the application closes the old row and inserts a new one (Chapter 53); or a tool that reads changes from the binary log. The trigger route is the easiest to get running and the easiest to get subtly wrong — missing event handlers leave gaps: the following example handles updates only, not inserts or deletes. MySQL LOAD DATA fires insert triggers; TRUNCATE does not fire delete triggers.

-- 🟦 MySQL: the trigger-maintained history pattern, done properly
CREATE TABLE product_prices (
    product_id   INT            NOT NULL PRIMARY KEY,
    unit_price   DECIMAL(10,2)  NOT NULL,
    updated_at   DATETIME(6)    NOT NULL DEFAULT (UTC_TIMESTAMP(6))   -- when this version began
) ENGINE=InnoDB;

CREATE TABLE product_prices_history (
    history_id   BIGINT AUTO_INCREMENT PRIMARY KEY,
    product_id   INT            NOT NULL,
    unit_price   DECIMAL(10,2)  NOT NULL,
    valid_from   DATETIME(6)    NOT NULL,
    valid_to     DATETIME(6)    NOT NULL,
    changed_by   VARCHAR(100)   NOT NULL,
    operation    CHAR(1)        NOT NULL,     -- I / U / D
    INDEX ix_hist_key (product_id, valid_from)
) ENGINE=InnoDB;

DELIMITER $$
-- Stamp the start of every new version
CREATE TRIGGER trg_prices_stamp_upd
BEFORE UPDATE ON product_prices
FOR EACH ROW
BEGIN
    SET NEW.updated_at = UTC_TIMESTAMP(6);
END$$

-- Close off the OLD version into history, ending exactly where the new one begins
CREATE TRIGGER trg_prices_history_upd
AFTER UPDATE ON product_prices
FOR EACH ROW
BEGIN
    INSERT INTO product_prices_history
        (product_id, unit_price, valid_from, valid_to, changed_by, operation)
    VALUES (OLD.product_id, OLD.unit_price, OLD.updated_at, NEW.updated_at, CURRENT_USER(), 'U');
END$$
DELIMITER ;

[!TIP] 💡 Note what the trigger writes: the OLD row, closed off at “now”. The current row stays in the base table. That keeps the base table small and every “as of” query becomes a UNION ALL of the base table and the history — which is precisely what MSSQL’s temporal tables do internally.

62.6 🎯 When to use which

Situation Reach for
“Prove what the price was on 3 March” 🟥 Temporal table · 🟦 SCD Type 2 / trigger history
Keep a search index or cache in sync 🟥 Change Tracking · 🟦 binlog reader
Feed a data warehouse with before/after values 🟥 CDC · 🟦 binlog reader
Regulatory audit of who read or wrote data SQL Server Audit / MySQL Enterprise Audit — not triggers
You just want updated_at on a row A column with a default. Do not over-engineer

[!CAUTION] Do not hand-roll history with triggers if a built-in exists. Hand-written audit triggers need explicit coverage for every event and ingestion path. SQL Server BULK INSERT needs FIRE_TRIGGERS; MySQL LOAD DATA fires insert triggers. Both engines omit delete triggers for TRUNCATE. SQL Server statement triggers must handle all rows in inserted/deleted (Chapter 39). Built-in history and change features also require permissions, retention and consumer checks.

62.7 🧪 Try it yourself

  1. Make products a temporal table. Change a price three times, then reconstruct the price at each intermediate moment with AS OF.
  2. Write a query that lists every product whose price changed in the last 7 days, with the old and new values side by side (hint: LAG over FOR SYSTEM_TIME ALL).
  3. Try to DROP a system-versioned table without turning versioning off. Read the error, then do it properly.
  4. Enable Change Tracking on orders, make three changes, and write the consumer query that a nightly ETL job would run.
  5. Deliberately let a CHANGETABLE version expire past retention and observe what the consumer sees.
  6. 🟦 MySQL: extend the update-only history example with insert and delete handlers. Verify that LOAD DATA fires insert triggers, and explain why TRUNCATE still needs separate operational controls.

🧭 In practice — temporal tables and change tracking

How to use it. SQL Server system-versioned temporal tables keep a full history automatically: add period columns and a history table, then query the past with FOR SYSTEM_TIME AS OF '2026-03-01'. MySQL has no equivalent, so history is built with triggers or an application-maintained audit table. Expected result: “what did this row look like in March?” becomes a query rather than a restore.

When to use it. For auditing, regulatory history, and any “as at” report — and for the surprisingly common support question “who changed this, and when?”

Where to use it. Regulated and financial systems. Scenario: a price-history requirement. A temporal table captures every change made by any route — application, admin screen, or a person running SQL — with no application code at all, which is exactly what makes it defensible to an auditor.

When not to use it. Do not turn it on for high-churn tables without planning for growth: history can dwarf the current table, and it needs a retention policy from day one. Do not rely on it for who made the change — system-versioning records what and when, not the user; that still needs an application-supplied column or a trigger.

Best practices. Decide retention and archiving before enabling it, and measure the storage. Remember that a schema change to the current table must propagate to the history table. Where MySQL is the target, be honest that trigger-based history is application-maintained and can be bypassed by a direct TRUNCATE — which is precisely the weakness the exercise in Chapter 39 asks you to explain.


Part index Prerequisites Previous Next Full course