Developer Guides, Cheat Sheets & Tools
SQL course - Part 8: DATABASE OBJECTS
| Part index | Prerequisites | Previous | Next | Full course |
๐๏ธ PART 8 โ DATABASE OBJECTS
36. Views
| ๐๏ธ Level | โฑ๏ธ Time | ๐ฏ After this chapter you canโฆ |
|---|---|---|
| ๐ข๐ก BeginnerโIntermediate | 25 min | Save a query as a view ยท Hide columns people must not see ยท Use views that stay up to date ยท Avoid the view traps |
[!NOTE] ๐ In plain words: A view is a saved query that behaves like a table. It stores no data of its own โ every time you query it, the underlying query runs.
๐ Analogy: A view is a window in a wall. You are not moving the furniture; you are creating a fixed frame through which people see a particular part of the room. Change the furniture and the window shows the new arrangement automatically.
36.1 โ๏ธ Creating and using views
-- โ
Works in BOTH
CREATE VIEW v_order_summary AS
SELECT
o.order_id,
o.order_date,
o.status,
c.full_name AS customer_name,
c.country,
COUNT(oi.product_id) AS item_count,
SUM(oi.quantity) AS total_units,
ROUND(SUM(oi.unit_price * oi.quantity * (1-oi.discount)), 2) AS order_value
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.order_date, o.status, c.full_name, c.country;
Now anyone can ask complex questions with simple SQL:
SELECT * FROM v_order_summary WHERE country = 'Singapore' ORDER BY order_value DESC;
SELECT status, COUNT(*), SUM(order_value) FROM v_order_summary GROUP BY status;
Modifying and dropping:
-- ๐ฅ MSSQL
CREATE OR ALTER VIEW v_order_summary AS -- 2016 SP1+: creates or replaces
SELECT order_id, order_date, status FROM orders;
GO
DROP VIEW IF EXISTS v_order_summary;
-- ๐ฆ MySQL
CREATE OR REPLACE VIEW v_order_summary AS SELECT order_id, order_date, status FROM orders;
DROP VIEW IF EXISTS v_order_summary;
36.2 ๐ฏ The five real reasons to use a view
โ Hide complexity. A 60-line join becomes SELECT * FROM v_order_summary. Analysts who do not know how your tables fit together can still answer questions.
โก Enforce security. Grant access to the view, not the table. Users see only the columns and rows you allow.
-- โ
Works in BOTH: staff can see customers WITHOUT contact details
CREATE VIEW v_customers_public AS
SELECT customer_id, full_name, city, country, loyalty_tier, signup_date
FROM customers;
-- email and phone are simply not exposed
-- ๐ฅ MSSQL: grant the view โ and NO permission on the customers table itself
-- (run this as its own batch: CREATE VIEW must be alone in its batch, so put GO after the view)
CREATE ROLE support_role;
GRANT SELECT ON v_customers_public TO support_role;
-- ๐ฆ MySQL: the same grant
CREATE ROLE 'support_role';
GRANT SELECT ON ShopDB.v_customers_public TO 'support_role';
โข Row-level security โ each user sees only their own rows.
-- ๐ฅ MSSQL: each sales rep sees only their own orders
CREATE VIEW v_my_orders AS
SELECT o.*
FROM orders o
JOIN employees e ON e.employee_id = o.employee_id
WHERE e.first_name + ' ' + e.last_name = SUSER_SNAME(); -- ๐ฅ MSSQL
[!WARNING] โ ๏ธ A view is a convenience, not a security boundary. If the user also has
SELECTonorders, they simply query the table directly and see everything. This only works if you grant access to the view alone and revoke it on the base table. For a guarantee the engine enforces no matter how the table is queried, use Row-Level Security (Chapter 54.6).
โฃ A stable name while the tables underneath change. If you rename a column, update the view and every application keeps working.
โค Consistent business logic. Define โrevenueโ once, in a view, and every report computes it identically. Nothing is worse than two dashboards disagreeing because one forgot the discount.
-- โ
Works in BOTH: the single source of truth for "active customers"
CREATE VIEW v_active_customers AS
SELECT * FROM customers
WHERE customer_id IN (
SELECT customer_id FROM orders WHERE order_date >= '2026-01-01'
);
36.3 โ๏ธ Updatable views
Some views accept INSERT, UPDATE, and DELETE, which pass through to the base table.
-- โ
Works in BOTH โ this view IS updatable: simple, one table, no aggregation
CREATE VIEW v_uk_customers AS
SELECT customer_id, full_name, email, city, country
FROM customers
WHERE country = 'UK';
-- โ
Works in BOTH (๐ in MSSQL run it as a separate batch: CREATE VIEW must be alone in its batch)
UPDATE v_uk_customers SET city = 'Manchester' WHERE customer_id = 2; -- โ
works
A view is NOT updatable if it contains any of:
| โ Blocker | Why |
|---|---|
GROUP BY or aggregates |
One view row maps to many table rows |
DISTINCT |
Same reason |
UNION |
Which branch would you update? |
| A join (usually) | Ambiguous which table to modify |
| Window functions | Computed across rows |
TOP / LIMIT (usually) |
Ambiguous |
[!WARNING] โ ๏ธ The disappearing row problem. Update a row through a filtered view so it no longer matches the filter, and it vanishes from the view:
UPDATE v_uk_customers SET country = 'France' WHERE customer_id = 2; -- The row still exists in customers, but has left the view.The fix โ
WITH CHECK OPTION, which refuses updates that would push a row out of the view:-- โ Works in BOTH CREATE VIEW v_uk_customers_checked AS SELECT customer_id, full_name, email, city, country FROM customers WHERE country = 'UK' WITH CHECK OPTION; -- Through this view, that UPDATE fails with an error instead of silently hiding the row.
36.4 โก Materialized views โ views that store data
A normal view runs its query every time. A materialized view stores the result and refreshes it periodically. This trades freshness for speed.
-- ๐ฅ MSSQL: "indexed views". Add a unique clustered index to a view and
-- SQL Server physically stores and auto-maintains the results.
CREATE VIEW v_category_sales
WITH SCHEMABINDING -- ๐ required
AS
SELECT
p.category_id,
COUNT_BIG(*) AS line_count, -- ๐ COUNT_BIG, not COUNT
SUM(oi.quantity) AS total_units
FROM dbo.order_items AS oi
JOIN dbo.products AS p ON p.product_id = oi.product_id
GROUP BY p.category_id;
GO
CREATE UNIQUE CLUSTERED INDEX ix_v_category_sales ON v_category_sales(category_id);
[!WARNING] โ ๏ธ MSSQL indexed views have strict rules:
WITH SCHEMABINDING, two-part names (dbo.table),COUNT_BIG(*)instead ofCOUNT(*), no outer joins, no subqueries, noDISTINCT. In exchange, the engine maintains them automatically on every write โ always fresh, but every insert into the base table now costs more.
-- ๐ฆ MySQL has NO materialized views. Imitate one with a real table + a scheduled refresh.
CREATE TABLE mv_category_sales (
category_id INT PRIMARY KEY,
line_count INT NOT NULL,
total_units INT NOT NULL,
refreshed_at DATETIME NOT NULL
);
-- Refresh procedure, called by a scheduled EVENT (see Chapter 57)
DELIMITER $$
CREATE PROCEDURE refresh_mv_category_sales()
BEGIN
TRUNCATE TABLE mv_category_sales;
INSERT INTO mv_category_sales (category_id, line_count, total_units, refreshed_at)
SELECT p.category_id, COUNT(*), SUM(oi.quantity), NOW()
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
GROUP BY p.category_id;
END$$
DELIMITER ;
| ย | Normal view | Materialized view |
|---|---|---|
| Storage | None | Stores the result |
| Freshness | โ Always current | โ ๏ธ As of the last refresh |
| Read speed | Same as the underlying query | โก Very fast |
| Write cost | None | โ ๏ธ Slows down base-table writes, or needs a refresh job |
| Best for | Simplification, security | Expensive aggregates read far more often than written |
36.5 โ ๏ธ View pitfalls
[!WARNING] โ ๏ธ
SELECT *in a view definition does not auto-update. In MSSQL, columns added to the base table afterwards do not appear in the view until you refresh it withsp_refreshview. Worse, dropping a column can make the view return wrong data under the old column names. Always list columns explicitly in a view.
[!TIP] ๐ก Naming convention: prefix views with
v_orvw_. Six months later,v_order_summaryimmediately tells the reader โthis is a view, do not expect an index on it.โ
36.6 ๐ฏ When to create a view (and when not to)
| Use a view whenโฆ | Do not use a view whenโฆ |
|---|---|
| A complex join is written repeatedly | You only need it once |
| Analysts need simple access to a hard schema | You need parameters โ use an inline TVF (a function that returns a table, Chapter 38) or a procedure |
| You must hide columns (salaries, emails) from a role | You are relying on it as a security boundary without revoking table access |
| A business definition (โrevenueโ) must be identical everywhere | The logic changes per caller |
| You want a stable name while the schema underneath changes | You would be building a view on a view on a view |
| A rollup is read constantly and written rarely | You actually need it fast โ use an indexed view or summary table |
[!CAUTION] ๐ Common mistake: nesting views.
v_reportselects fromv_sales, which selects fromv_orders. Each level looks tidy, but the database must unpick the whole stack into one giant query, speed drops sharply, and nobody can trace which table a column came from. Keep views one level deep.
36.7 ๐งช Try it yourself
- Create
v_product_catalogjoining products, categories, and suppliers with friendly names. - Create
v_low_stockshowing products at or below their reorder level, and query it. - Create a filtered, updatable view with
WITH CHECK OPTIONand prove it blocks a bad update. - Try to update through a view containing
GROUP BY. Read the error.
๐งญ In practice โ views
How to use it.
CREATE VIEW v AS SELECT ...stores the query, not the data. Select from it like a table. SQL Server can add an index to a view withSCHEMABINDING(an indexed view), which does materialise it; MySQL has no equivalent. Expected result: a named, reusable query that hides joins and filters from its callers.When to use it. To give a stable, simple interface over a complicated or changing schema, and to expose a restricted subset of a table โ a
v_customers_publicview without the phone number.Where to use it. Between the database and its consumers. Scenario: a reporting team queries
v_order_summaryinstead of joining four tables and remembering to exclude cancelled orders. When the schema changes, you fix the view once rather than every report.When not to use it. A view is not a performance feature โ a plain view runs its query every time, so stacking views on views quietly builds an enormous statement the optimiser must untangle. Do not use views to fake stored data; if you need the result materialised, use an indexed view (SQL Server), a summary table, or a scheduled refresh. Avoid
ORDER BYinside a view: it is meaningless once an outer query touches it.Best practices. Keep views one layer deep where you can, and never
SELECT *inside one โ the column list is captured when the view is created, so a laterALTER TABLEleaves the view stale or wrong. Grant permissions on the view rather than the base tables when you are using it as a security boundary; otherwise the restriction is decorative.
37. Stored procedures
| ๐๏ธ Level | โฑ๏ธ Time | ๐ฏ After this chapter you canโฆ |
|---|---|---|
| ๐ก Intermediate | 40 min | Save multi-step tasks in the database ยท Pass values in and out ยท Use IF and loops ยท Write a safe, complete order procedure |
[!NOTE] ๐ In plain words: A stored procedure is a named, saved program inside the database. You call it by name, pass it parameters, and it runs a whole sequence of SQL statements.
๐ Analogy: A view is a saved question. A stored procedure is a saved task โ it can ask several questions, make decisions, change data, handle errors, and report back.
37.1 ๐ฅ MSSQL stored procedures
CREATE OR ALTER PROCEDURE usp_get_customer_orders
@customer_id INT,
@from_date DATE = NULL, -- optional, with a default
@status VARCHAR(20) = NULL
AS
BEGIN
SET NOCOUNT ON; -- ๐ก hides the "(n rows affected)" messages
SELECT
o.order_id,
o.order_date,
o.status,
ROUND(SUM(oi.unit_price * oi.quantity * (1 - oi.discount)), 2) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = @customer_id
AND (@from_date IS NULL OR o.order_date >= @from_date)
AND (@status IS NULL OR o.status = @status)
GROUP BY o.order_id, o.order_date, o.status
ORDER BY o.order_date DESC;
END;
GO
-- Calling it
EXEC usp_get_customer_orders @customer_id = 1;
EXEC usp_get_customer_orders @customer_id = 3, @from_date = '2026-04-01';
EXEC usp_get_customer_orders @customer_id = 3, @status = 'Delivered';
Output parameters and return values:
CREATE OR ALTER PROCEDURE usp_place_order
@customer_id INT,
@employee_id INT,
@new_order_id INT OUTPUT -- ๐ sends a value back
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (@customer_id, @employee_id, CAST(GETDATE() AS DATE), 'Pending');
SET @new_order_id = SCOPE_IDENTITY();
RETURN 0; -- 0 = success, by convention
END;
GO
DECLARE @order_id INT;
EXEC usp_place_order @customer_id = 1, @employee_id = 3, @new_order_id = @order_id OUTPUT;
SELECT @order_id AS created_order_id;
37.2 ๐ฆ MySQL stored procedures
DELIMITER $$
CREATE PROCEDURE usp_get_customer_orders(
IN p_customer_id INT,
IN p_from_date DATE,
IN p_status VARCHAR(20)
)
BEGIN
SELECT
o.order_id,
o.order_date,
o.status,
ROUND(SUM(oi.unit_price * oi.quantity * (1 - oi.discount)), 2) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = p_customer_id
AND (p_from_date IS NULL OR o.order_date >= p_from_date)
AND (p_status IS NULL OR o.status = p_status)
GROUP BY o.order_id, o.order_date, o.status
ORDER BY o.order_date DESC;
END$$
DELIMITER ;
-- Calling it
CALL usp_get_customer_orders(1, NULL, NULL);
CALL usp_get_customer_orders(3, '2026-04-01', NULL);
[!WARNING] โ ๏ธ What is
DELIMITER $$? MySQL normally treats;as โend of statementโ. A procedure body is full of semicolons, so MySQL would try to execute it halfway through.DELIMITER $$temporarily changes the terminator to$$, letting you define the whole body, then you change it back. Every MySQL procedure needs this, and forgetting it is the number-one MySQL procedure error.
[!WARNING] โ ๏ธ Keep emoji out of MySQL routine bodies โ even in comments. MySQL stores a routineโs definition as
utf8mb3, so a four-byte character such as ๐ insideBEGIN โฆ ENDmakesCREATE PROCEDUREfail with ERROR 4089: Definition of stored routine โฆ contains an invalid utf8mb3 character string.
MySQL parameter modes:
| Mode | Meaning |
|---|---|
IN (default) |
Value passed in, read-only |
OUT |
Value passed back to the caller |
INOUT |
Both |
DELIMITER $$
CREATE PROCEDURE usp_place_order(
IN p_customer_id INT,
IN p_employee_id INT,
OUT p_new_order_id INT
)
BEGIN
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (p_customer_id, p_employee_id, CURDATE(), 'Pending');
SET p_new_order_id = LAST_INSERT_ID();
END$$
DELIMITER ;
CALL usp_place_order(1, 3, @new_id);
SELECT @new_id;
37.3 ๐ง Variables, control flow, and loops
-- ๐ฅ MSSQL
CREATE OR ALTER PROCEDURE usp_apply_loyalty_discount
@order_id INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @tier VARCHAR(10);
DECLARE @discount DECIMAL(4,3);
SELECT @tier = c.loyalty_tier
FROM orders o JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_id = @order_id;
IF @tier IS NULL
BEGIN
RAISERROR('Order %d not found.', 16, 1, @order_id);
RETURN;
END;
SET @discount =
CASE @tier
WHEN 'Platinum' THEN 0.15
WHEN 'Gold' THEN 0.10
WHEN 'Silver' THEN 0.05
ELSE 0.00
END;
UPDATE order_items SET discount = @discount WHERE order_id = @order_id;
SELECT @order_id AS order_id, @tier AS tier, @discount AS applied_discount;
END;
GO
-- ๐ฆ MySQL
DELIMITER $$
CREATE PROCEDURE usp_apply_loyalty_discount(IN p_order_id INT)
BEGIN
DECLARE v_tier VARCHAR(10);
DECLARE v_discount DECIMAL(4,3);
SELECT c.loyalty_tier INTO v_tier
FROM orders o JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_id = p_order_id;
IF v_tier IS NULL THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Order not found.';
END IF;
SET v_discount = CASE v_tier
WHEN 'Platinum' THEN 0.15
WHEN 'Gold' THEN 0.10
WHEN 'Silver' THEN 0.05
ELSE 0.00 END;
UPDATE order_items SET discount = v_discount WHERE order_id = p_order_id;
SELECT p_order_id AS order_id, v_tier AS tier, v_discount AS applied_discount;
END$$
DELIMITER ;
Control flow reference:
| Construct | ๐ฅ MSSQL | ๐ฆ MySQL |
|---|---|---|
| Declare | DECLARE @x INT; |
DECLARE x INT; (top of block only) |
| Assign | SET @x = 1; / SELECT @x = col ... |
SET x = 1; / SELECT col INTO x ... |
| If | IF ... BEGIN ... END ELSE BEGIN ... END |
IF ... THEN ... ELSEIF ... ELSE ... END IF; |
| Loop | WHILE ... BEGIN ... END |
WHILE ... DO ... END WHILE; |
| Other loops | (none) | REPEAT ... UNTIL ... END REPEAT;, LOOP ... END LOOP; |
| Exit a loop | BREAK / CONTINUE |
LEAVE label / ITERATE label |
| Raise an error | THROW / RAISERROR |
SIGNAL SQLSTATE '45000' |
37.4 ๐ผ A complete real-world procedure
This one does real work: it checks the customer, checks and locks the stock, creates the order, reduces the stock, and handles errors โ all as one all-or-nothing unit.
-- ๐ฅ MSSQL
CREATE OR ALTER PROCEDURE usp_create_order
@customer_id INT,
@employee_id INT,
@product_id INT,
@quantity INT,
@new_order_id INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON; -- ๐ก auto-rollback on any runtime error
BEGIN TRY
BEGIN TRANSACTION;
-- 1. Validate the customer
IF NOT EXISTS (SELECT 1 FROM customers WHERE customer_id = @customer_id)
THROW 50001, 'Customer does not exist.', 1;
-- 2. Check stock, locking the row so nobody else takes it
DECLARE @stock INT, @price DECIMAL(10,2);
SELECT @stock = units_in_stock, @price = unit_price
FROM products WITH (UPDLOCK, ROWLOCK)
WHERE product_id = @product_id;
IF @stock IS NULL
THROW 50002, 'Product does not exist.', 1;
IF @stock < @quantity
THROW 50003, 'Insufficient stock.', 1;
-- 3. Create the order header
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (@customer_id, @employee_id, CAST(GETDATE() AS DATE), 'Pending');
SET @new_order_id = SCOPE_IDENTITY();
-- 4. Add the line item
INSERT INTO order_items (order_id, product_id, unit_price, quantity, discount)
VALUES (@new_order_id, @product_id, @price, @quantity, 0);
-- 5. Reduce stock
UPDATE products
SET units_in_stock = units_in_stock - @quantity
WHERE product_id = @product_id;
COMMIT TRANSACTION;
SELECT @new_order_id AS order_id, 'Created' AS result;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
DECLARE @msg NVARCHAR(2048) = ERROR_MESSAGE();
DECLARE @sev INT = ERROR_SEVERITY();
RAISERROR(@msg, @sev, 1);
END CATCH;
END;
GO
-- ๐ฆ MySQL
DELIMITER $$
CREATE PROCEDURE usp_create_order(
IN p_customer_id INT,
IN p_employee_id INT,
IN p_product_id INT,
IN p_quantity INT,
OUT p_new_order_id INT
)
BEGIN
DECLARE v_stock INT DEFAULT NULL;
DECLARE v_price DECIMAL(10,2);
-- Any SQL exception rolls everything back and re-raises
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM customers WHERE customer_id = p_customer_id) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Customer does not exist.';
END IF;
SELECT units_in_stock, unit_price INTO v_stock, v_price
FROM products WHERE product_id = p_product_id FOR UPDATE; -- row lock
IF v_stock IS NULL THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Product does not exist.';
END IF;
IF v_stock < p_quantity THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock.';
END IF;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (p_customer_id, p_employee_id, CURDATE(), 'Pending');
SET p_new_order_id = LAST_INSERT_ID();
INSERT INTO order_items (order_id, product_id, unit_price, quantity, discount)
VALUES (p_new_order_id, p_product_id, v_price, p_quantity, 0);
UPDATE products SET units_in_stock = units_in_stock - p_quantity
WHERE product_id = p_product_id;
COMMIT;
END$$
DELIMITER ;
[!TIP] ๐ก Study that procedure. It contains everything professional database code needs: input validation, explicit locking to prevent two customers buying the last item, a transaction so partial work cannot survive, and error handling that leaves no mess behind. This is what โproduction qualityโ looks like.
37.5 ๐ฆ Table-valued parameters โ passing a LIST into a procedure
[!NOTE] ๐ In plain words: How do you pass โthese 12 product IDsโ into a stored procedure? Beginners send a comma-separated string and split it. The proper answer in SQL Server is a table-valued parameter: a parameter that is a table.
๐ Analogy: Instead of sliding a handwritten list under the door and hoping it is read correctly, you hand over a proper filled-in form with one item per line. Nothing to split apart, nothing to misread, no risk of SQL injection.
-- ๐ฅ MSSQL: STEP 1 โ define the table TYPE once
CREATE TYPE dbo.ProductIdList AS TABLE (
product_id INT PRIMARY KEY
);
GO
-- STEP 2 โ a procedure that accepts it (READONLY is mandatory)
CREATE OR ALTER PROCEDURE usp_products_by_ids
@ids dbo.ProductIdList READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT p.product_id, p.product_name, p.unit_price
FROM products AS p
JOIN @ids AS i ON i.product_id = p.product_id
ORDER BY p.product_name;
END;
GO
-- STEP 3 โ call it
DECLARE @list dbo.ProductIdList;
INSERT INTO @list (product_id) VALUES (1), (5), (15);
EXEC usp_products_by_ids @ids = @list;
Result:
| product_id | product_name | unit_price |
|---|---|---|
| 1 | UltraBook Pro 14 | 1499.00 |
| 15 | VisionPanel 32 4K | 749.00 |
| 5 | Zenith Phone 12 | 899.00 |
[!IMPORTANT] ๐ฏ When to use a TVP:
- Passing a variable-length list of IDs from an application (a multi-select filter, a basket, a batch of updates)
- Inserting a few hundred rows in one trip to the server instead of 300 separate
INSERTcalls- Anywhere you were tempted to build a comma-separated string
[!WARNING] โ ๏ธ The three rules that trip people up:
- The parameter must be declared
READONLYโ you cannotINSERT/UPDATE/DELETEinside the procedure.- You cannot
ALTERa table type. To change it you must drop every procedure that uses it, drop the type, recreate both.- The optimizer has no statistics for a TVP and estimates a fixed row count, so plans can be poor for very large lists. For tens of thousands of rows, load into a
#temptable instead.
[!CAUTION] ๐ Common mistake โ the comma-string anti-pattern. Do not do this:
-- โ ๐ฅ MSSQL: string splitting โ slow, injection-prone, and the plan is always bad EXEC usp_products_by_ids @ids = '1,5,15'; -- fails: a string is not a ProductIdListA TVP is type-safe, parameterized, and needs no parsing. If you are on SQL Server 2016+ and genuinely cannot use a TVP,
STRING_SPLIT()is the least-bad fallback โ never string concatenation.
๐ MySQL has no table-valued parameters. The usual workarounds are a JSON parameter unpacked into rows with
JSON_TABLE()(Chapter 58), or writing the list into a temporary table before calling the procedure.
37.6 โ๏ธ Should you use stored procedures?
| โ Arguments for | โ Arguments against |
|---|---|
| Logic lives next to the data โ far fewer network round trips | Business logic split between app and database |
| The server remembers the execution plan and reuses it | Harder to test automatically than application code |
Security: grant EXECUTE without table access |
Harder to version-control and code-review |
| Applications cannot bypass your rules | Two dialects to maintain if you support both engines |
| Batch operations are dramatically faster | Debugging tools are weaker than a modern IDE |
| Applications keep calling the same name even when tables change | More users means a bigger database server โ the most expensive part to grow |
[!TIP] ๐ก The pragmatic middle ground most teams land on: use stored procedures for data-intensive operations (bulk updates, complex reports, multi-step transactions, ETL โ extracting, cleaning, and loading data between systems) where moving the logic to the data saves enormous time. Keep business rules in the application, where they can be tested, versioned, and reviewed properly.
37.7 ๐งญ Inspecting procedures
-- ๐ฅ MSSQL
SELECT name, create_date, modify_date FROM sys.procedures ORDER BY name;
EXEC sp_helptext 'usp_get_customer_orders';
SELECT OBJECT_DEFINITION(OBJECT_ID('usp_get_customer_orders'));
-- ๐ฆ MySQL
SHOW PROCEDURE STATUS WHERE Db = 'ShopDB';
SHOW CREATE PROCEDURE usp_get_customer_orders;
SELECT routine_name, routine_type FROM information_schema.routines
WHERE routine_schema = 'ShopDB';
37.8 ๐งช Try it yourself
- Write
usp_top_customers(@limit INT)returning the top N customers by spend. - Write a procedure that cancels an order: sets the status, restores stock, and marks the payment refunded โ atomically.
- Write a procedure with an
OUTPUT/OUTparameter returning a customerโs lifetime value. - Add error handling that raises a clear message when the customer does not exist. Test it.
๐งญ In practice โ stored procedures
How to use it.
CREATE PROCEDURE name @param TYPE AS BEGIN ... END(SQL Server) orCREATE PROCEDURE name(IN param TYPE) BEGIN ... ENDwithDELIMITER(MySQL). Call withEXECorCALL. Prerequisite: run the whole definition as one batch โ this is the main reason these blocks are easier in SSMS or Workbench than in a scripted harness. Expected result: a named, parameterised unit of work stored in the database.When to use it. For multi-statement operations that must happen together โ placing an order checks stock, inserts the order and its items, and decrements stock, all inside one transaction.
Where to use it. The boundary between an application and its data. Scenario:
usp_place_orderwraps the whole sequence in a transaction withTRY...CATCHandROLLBACK. Every caller gets the same correctness guarantee, and the application cannot forget a step.When not to use it. Do not put your entire business logic in stored procedures by default. They are harder to version, test, review, and debug than application code; they do not diff well; and a codebase split between two languages is harder to reason about. Use them where the database is genuinely the right place โ transactional integrity, heavy set-based work close to the data, or a controlled interface for other teams.
Best practices. Always parameterise โ a procedure that concatenates its arguments into dynamic SQL is not protected against injection simply by being a procedure. Handle errors explicitly (
TRY...CATCHin SQL Server,DECLARE ... HANDLERin MySQL) and make sure every path either commits or rolls back. Keep procedure definitions in source control and deploy them through migrations, exactly like table changes.
38. User-defined functions
| ๐๏ธ Level | โฑ๏ธ Time | ๐ฏ After this chapter you canโฆ |
|---|---|---|
| ๐ก Intermediate | 25 min | Create your own reusable calculations ยท Return a single value or a whole table ยท Avoid the classic function slowdown |
[!NOTE] ๐ In plain words: A function takes inputs and returns a value (or a table). Unlike a procedure, you can use a function inside a query โ in
SELECT,WHERE, orJOIN.
๐ Analogy: A calculator button you invent yourself. Press โadd VATโ with 100, get 115 back โ and you can use that button inside any sum you write.
| ย | Stored procedure | Function |
|---|---|---|
| Called with | EXEC / CALL |
Inside a query expression |
| Returns | Result sets, output params | A single value or a table |
| Can modify data | โ Yes | โ No (it may only read) |
Can be used in SELECT/WHERE |
โ No | โ Yes |
| Can manage transactions | โ Yes | โ No |
38.1 ๐ข Scalar functions
-- ๐ฅ MSSQL
CREATE OR ALTER FUNCTION fn_order_total (@order_id INT)
RETURNS DECIMAL(12,2)
AS
BEGIN
DECLARE @total DECIMAL(12,2);
SELECT @total = SUM(unit_price * quantity * (1 - discount))
FROM order_items
WHERE order_id = @order_id;
RETURN ISNULL(@total, 0);
END;
GO
-- Use it anywhere a value is allowed
SELECT order_id, order_date, dbo.fn_order_total(order_id) AS order_value
FROM orders
WHERE dbo.fn_order_total(order_id) > 1000;
[!WARNING] โ ๏ธ MSSQL requires the schema prefix (
dbo.) when calling a scalar function. Omit it and you get โโfn_order_totalโ is not a recognized built-in function name.โ
-- ๐ฆ MySQL
DELIMITER $$
CREATE FUNCTION fn_order_total(p_order_id INT)
RETURNS DECIMAL(12,2)
NOT DETERMINISTIC -- the same order ID can return a different total after data changes
READS SQL DATA
BEGIN
DECLARE v_total DECIMAL(12,2);
SELECT SUM(unit_price * quantity * (1 - discount)) INTO v_total
FROM order_items WHERE order_id = p_order_id;
RETURN IFNULL(v_total, 0);
END$$
DELIMITER ;
SELECT order_id, fn_order_total(order_id) AS order_value FROM orders;
[!WARNING] โ ๏ธ MySQL requires you to say what kind of function it is โ whether it is deterministic (the same input always gives the same output) and whether it reads or changes data (
DETERMINISTIC,NOT DETERMINISTIC,READS SQL DATA,NO SQL, orMODIFIES SQL DATA) when binary logging is on. Without it you get โYou do not have the SUPER privilege and binary logging is enabled.โ
38.2 ๐ The scalar function performance disaster
[!WARNING] โ ๏ธ This is one of the most important performance lessons in this entire guide.
-- โ ๐ฅ MSSQL: on a 1-million-row table, this calls the function ONE MILLION times.
-- Each call is a separate mini-query. The plan hides the cost entirely.
SELECT order_id, dbo.fn_order_total(order_id) FROM orders;
In MSSQL before 2019, a scalar UDF (user-defined function) also forced the entire query onto a single CPU core, so it could not split the work. A query that should take 2 seconds takes 4 minutes.
-- โ
๐ฅ MSSQL โ FIX 1: rewrite as an inline table-valued function
CREATE OR ALTER FUNCTION fn_order_total_itvf (@order_id INT)
RETURNS TABLE
AS
RETURN (
SELECT SUM(unit_price * quantity * (1 - discount)) AS order_total
FROM order_items
WHERE order_id = @order_id
);
GO
SELECT o.order_id, t.order_total
FROM orders o
CROSS APPLY dbo.fn_order_total_itvf(o.order_id) AS t;
-- โ
FIX 2 (usually best): just write the join. No function at all.
SELECT o.order_id, SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS order_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id;
[!TIP] ๐ก MSSQL 2019 introduced โscalar UDF inliningโ which automatically rewrites many scalar functions into the query. It helps enormously, but only for functions that meet its requirements. The safe rule remains: prefer inline table-valued functions or plain joins.
38.3 ๐ Table-valued functions (MSSQL)
Inline TVF (table-valued function) โ the good kind. A single RETURN (SELECT โฆ); the database merges it into your query, just like a view that accepts parameters.
-- ๐ฅ MSSQL
CREATE OR ALTER FUNCTION fn_customer_orders (@customer_id INT, @since DATE)
RETURNS TABLE
AS
RETURN (
SELECT o.order_id, o.order_date, o.status
FROM orders o
WHERE o.customer_id = @customer_id
AND o.order_date >= @since
);
GO
SELECT * FROM dbo.fn_customer_orders(3, '2026-01-01');
-- Use it per-row with CROSS APPLY
SELECT c.full_name, f.order_id, f.order_date
FROM customers c
CROSS APPLY dbo.fn_customer_orders(c.customer_id, '2026-01-01') AS f;
Multi-statement TVF โ usually the bad kind. It fills a table variable step by step; the optimizer cannot know how many rows will come back and historically guessed 1 row, producing terrible plans.
-- โ ๏ธ ๐ฅ MSSQL: works, but prefer an inline TVF whenever the logic allows it
CREATE OR ALTER FUNCTION fn_customer_summary (@customer_id INT)
RETURNS @result TABLE (
order_count INT,
total_spend DECIMAL(12,2),
last_order DATE
)
AS
BEGIN
INSERT INTO @result
SELECT COUNT(DISTINCT o.order_id),
SUM(oi.unit_price * oi.quantity * (1-oi.discount)),
MAX(o.order_date)
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = @customer_id;
RETURN;
END;
GO
๐ MySQL has no table-valued functions at all. Use a view (for fixed logic), a stored procedure returning a result set, or a derived table.
38.4 ๐ฏ Good uses for functions
-- โ
MSSQL: pure calculation, no table access โ cheap and safe
CREATE OR ALTER FUNCTION fn_add_vat (@amount DECIMAL(10,2), @rate DECIMAL(5,4))
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN ROUND(@amount * (1 + @rate), 2);
END;
GO
SELECT dbo.fn_add_vat(100.00, 0.1500) AS with_vat; -- 115.00
-- โ
MySQL: the same function
DELIMITER $$
CREATE FUNCTION fn_add_vat(p_amount DECIMAL(10,2), p_rate DECIMAL(5,4))
RETURNS DECIMAL(10,2)
DETERMINISTIC
NO SQL
BEGIN
RETURN ROUND(p_amount * (1 + p_rate), 2);
END$$
DELIMITER ;
SELECT fn_add_vat(100.00, 0.1500) AS with_vat; -- 115.00
[!IMPORTANT] ๐ฏ Use a function when: the logic is a pure calculation, it is used in many places, and centralizing it prevents inconsistency. Avoid a function when: it queries tables and will be called once per row of a large result โ write the join instead.
38.5 ๐งช Try it yourself
- Write
fn_days_to_ship(order_id)returning the shipping duration, or NULL if unshipped. - Write a function that returns a customerโs loyalty discount rate.
- In MSSQL, write both a scalar and an inline TVF version of โorder totalโ, then compare execution plans on all 23 orders.
- Explain in one sentence why the scalar version scales worse.
๐งญ In practice โ user-defined functions
How to use it. A scalar function returns one value; a table-valued function returns a result set you can join to. Create with
CREATE FUNCTION, and use it in aSELECT,WHERE, orJOIN. Expected result: a reusable calculation with a name, instead of the same expression copied into forty queries.When to use it. To centralise a business calculation โ a discount rule, a tax band, a working-days-between-dates helper โ so that it is defined in one place.
Where to use it. Shared reporting logic. Scenario: a
fn_net_amount(price, qty, discount)used by six reports guarantees all six agree. Without it, one report rounds at a different point and finance gets two different totals for the same month.When not to use it. This is the one place in the guide where the convenient tool is often the wrong one. A scalar function applied to a column in a
WHEREclause is evaluated per row and prevents index usage, and in older SQL Server versions it also forces the whole query to run single-threaded โ a common cause of a query that is inexplicably a hundred times slower than the same logic written inline. Prefer an inline table-valued function, which the optimiser can expand, or just write the expression.Best practices. Reach for an inline table-valued function first, a scalar function last, and measure before shipping either. SQL Server 2019 added scalar UDF inlining, which fixes many of these cases โ but only when the function qualifies, so check the actual plan rather than assuming. Never hide a query inside a scalar function that is then called per row; that is the classic hidden
N+1inside SQL.
39. Triggers
| ๐๏ธ Level | โฑ๏ธ Time | ๐ฏ After this chapter you canโฆ |
|---|---|---|
| ๐ก๐ด IntermediateโExpert | 30 min | Run code automatically when data changes ยท Build an audit trail ยท Handle many rows at once ยท Decide when NOT to use a trigger |
[!NOTE] ๐ In plain words: A trigger is code that the database runs automatically when someone inserts, updates, or deletes a row. Nobody calls it. It just fires.
๐ Analogy: A motion-sensor light. You do not flip a switch; walking into the room is the switch. Triggers are powerful for the same reason they are dangerous โ things happen that are not visible in the code you are reading.
39.1 โ๏ธ Creating triggers
-- ๐ฅ MSSQL: fires ONCE per statement and sees two built-in tables: inserted (new values) and deleted (old values)
CREATE OR ALTER TRIGGER trg_products_audit
ON products
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO product_price_history (product_id, old_price, new_price, changed_at, changed_by)
SELECT
i.product_id,
d.unit_price,
i.unit_price,
SYSDATETIME(),
SUSER_SNAME()
FROM inserted AS i
JOIN deleted AS d ON d.product_id = i.product_id
WHERE i.unit_price <> d.unit_price; -- only log actual price changes
END;
GO
-- ๐ฆ MySQL: triggers are ROW-level and use OLD / NEW
DELIMITER $$
CREATE TRIGGER trg_products_audit
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
IF OLD.unit_price <> NEW.unit_price THEN
INSERT INTO product_price_history (product_id, old_price, new_price, changed_at, changed_by)
VALUES (NEW.product_id, OLD.unit_price, NEW.unit_price, NOW(), CURRENT_USER());
END IF;
END$$
DELIMITER ;
The supporting table:
-- โ
MSSQL
CREATE TABLE product_price_history (
history_id INT IDENTITY(1,1) PRIMARY KEY,
product_id INT NOT NULL,
old_price DECIMAL(10,2),
new_price DECIMAL(10,2),
changed_at DATETIME2(0) NOT NULL,
changed_by VARCHAR(128) NOT NULL
);
-- โ
MySQL
CREATE TABLE product_price_history (
history_id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT NOT NULL,
old_price DECIMAL(10,2),
new_price DECIMAL(10,2),
changed_at DATETIME NOT NULL,
changed_by VARCHAR(128) NOT NULL
) ENGINE=InnoDB;
39.2 ๐ The critical difference: statement-level vs row-level
[!WARNING] โ ๏ธ This is the single most important thing to understand about triggers across the two engines.
| ย | ๐ฅ MSSQL | ๐ฆ MySQL |
|---|---|---|
| Fires | Once per statement | Once per row |
| Access to data | inserted and deleted tables |
NEW.col and OLD.col values |
| Updating 1000 rows | Trigger runs 1 time, sees 1000 rows | Trigger runs 1000 times |
-- ๐ฅ MSSQL: THIS IS A BUG โ it only handles ONE row correctly
CREATE TRIGGER trg_bad ON products AFTER UPDATE AS
BEGIN
DECLARE @id INT;
SELECT @id = product_id FROM inserted; -- โ if 50 rows changed, @id gets ONE arbitrary one
UPDATE something SET x = 1 WHERE id = @id;
END;
GO
DROP TRIGGER trg_bad; -- demonstration only: never leave this trigger behind
[!TIP] ๐ก The MSSQL rule: always write triggers that handle all rows at once (set-based). Assume
insertedanddeletedcontain many rows. Never use a variable to hold โtheโ row, and never use a cursor. WriteINSERT ... SELECT ... FROM insertedinstead.
39.3 โฑ๏ธ Trigger timing
| Timing | ๐ฅ MSSQL | ๐ฆ MySQL | What it can do |
|---|---|---|---|
| Before the change | INSTEAD OF |
BEFORE INSERT/UPDATE/DELETE |
Validate, modify values, cancel |
| After the change | AFTER (= FOR) |
AFTER INSERT/UPDATE/DELETE |
Audit, cascade, notify |
-- ๐ฆ MySQL BEFORE trigger: modify the value on its way in
DELIMITER $$
CREATE TRIGGER trg_customers_normalize
BEFORE INSERT ON customers
FOR EACH ROW
BEGIN
SET NEW.email = LOWER(TRIM(NEW.email));
SET NEW.full_name = TRIM(NEW.full_name);
IF NEW.signup_date IS NULL THEN
SET NEW.signup_date = CURDATE();
END IF;
END$$
DELIMITER ;
๐ MSSQL has no
BEFOREtrigger. ItsINSTEAD OFtrigger replaces the operation entirely โ you must perform the insert yourself inside the trigger. It is most useful for making a non-updatable view updatable.
-- ๐ฅ MSSQL INSTEAD OF: give a view a custom insert behaviour
-- โ ๏ธ The trigger can only read columns the VIEW exposes. `inserted` has the
-- view's shape, not the table's โ so the view must contain every column
-- the trigger needs. This view deliberately includes email.
CREATE OR ALTER VIEW v_customer_signup AS
SELECT customer_id, full_name, email, city, country
FROM customers;
GO
CREATE OR ALTER TRIGGER trg_v_customer_signup_insert
ON v_customer_signup
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO customers (full_name, email, city, country)
SELECT
LTRIM(RTRIM(i.full_name)),
LOWER(LTRIM(RTRIM(i.email))), -- normalized on the way in
i.city,
i.country
FROM inserted AS i;
END;
GO
-- The insert names the view; the trigger rewrites it against the base table
INSERT INTO v_customer_signup (full_name, email, city, country)
VALUES (' Nadia Haddad ', ' NADIA.HADDAD@Example.COM ', 'Beirut', 'Lebanon');
SELECT full_name, email FROM customers WHERE country = 'Lebanon';
-- โ 'Nadia Haddad' | 'nadia.haddad@example.com'
[!CAUTION] ๐ Common mistake: writing an
INSTEAD OFtrigger that reads a column the view does not select.insertedanddeletedtake the shape of the view, not the underlying table, so referencingNOT NULLcolumn the view hides, an insert through that view can never succeed โ either expose the column or give it a default.
39.4 ๐ผ Real-world trigger uses
โ Audit trail โ who changed what, and when
-- ๐ฅ MSSQL: capture every change to orders
CREATE TABLE orders_audit (
audit_id INT IDENTITY(1,1) PRIMARY KEY,
order_id INT NOT NULL,
action VARCHAR(10) NOT NULL,
old_status VARCHAR(20) NULL,
new_status VARCHAR(20) NULL,
changed_at DATETIME2(0) NOT NULL,
changed_by NVARCHAR(128) NOT NULL
);
GO
CREATE OR ALTER TRIGGER trg_orders_audit
ON orders
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
-- INSERT: rows in inserted, none in deleted
INSERT INTO orders_audit (order_id, action, old_status, new_status, changed_at, changed_by)
SELECT i.order_id, 'INSERT', NULL, i.status, SYSDATETIME(), SUSER_SNAME()
FROM inserted i
WHERE NOT EXISTS (SELECT 1 FROM deleted d WHERE d.order_id = i.order_id);
-- UPDATE: rows in both
INSERT INTO orders_audit (order_id, action, old_status, new_status, changed_at, changed_by)
SELECT i.order_id, 'UPDATE', d.status, i.status, SYSDATETIME(), SUSER_SNAME()
FROM inserted i
JOIN deleted d ON d.order_id = i.order_id
WHERE i.status <> d.status;
-- DELETE: rows in deleted, none in inserted
INSERT INTO orders_audit (order_id, action, old_status, new_status, changed_at, changed_by)
SELECT d.order_id, 'DELETE', d.status, NULL, SYSDATETIME(), SUSER_SNAME()
FROM deleted d
WHERE NOT EXISTS (SELECT 1 FROM inserted i WHERE i.order_id = d.order_id);
END;
GO
[!TIP] ๐ก How to tell which operation fired the trigger in MSSQL:
- Rows in
insertedonly โINSERT- Rows in both โ
UPDATE- Rows in
deletedonly โDELETE
โก Keeping a calculated value up to date
-- ๐ฆ MySQL: keep stock in sync when order items change
DELIMITER $$
CREATE TRIGGER trg_order_items_stock_out
AFTER INSERT ON order_items
FOR EACH ROW
BEGIN
UPDATE products
SET units_in_stock = units_in_stock - NEW.quantity
WHERE product_id = NEW.product_id;
END$$
CREATE TRIGGER trg_order_items_stock_return
AFTER DELETE ON order_items
FOR EACH ROW
BEGIN
UPDATE products
SET units_in_stock = units_in_stock + OLD.quantity
WHERE product_id = OLD.product_id;
END$$
DELIMITER ;
โข Enforcing a rule a CHECK constraint cannot express
-- ๐ฆ MySQL: block orders from customers with unpaid old orders
DELIMITER $$
CREATE TRIGGER trg_orders_credit_check
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
DECLARE v_unpaid INT;
SELECT COUNT(*) INTO v_unpaid
FROM orders o
LEFT JOIN payments p ON p.order_id = o.order_id AND p.status = 'Captured'
WHERE o.customer_id = NEW.customer_id
AND o.order_date < DATE_SUB(CURDATE(), INTERVAL 60 DAY)
AND p.payment_id IS NULL;
IF v_unpaid > 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Customer has unpaid orders older than 60 days.';
END IF;
END$$
DELIMITER ;
Keep stock examples separate: the stock-maintenance trigger and the order procedure in Chapter 37 are alternative implementations. Installing both can decrement stock twice. MySQL foreign-key cascades do not activate child triggers, so a delete-restock trigger must not depend on cascaded deletes.
39.5 โ ๏ธ Why experienced engineers are cautious with triggers
| Problem | Why it hurts |
|---|---|
| Invisible | A simple UPDATE fires code nobody reading the statement can see |
| Hard to debug | You cannot step through them; failures surface far from the cause |
| Performance | Every write pays the trigger cost, forever |
| Cascading chains | Trigger A updates a table, firing trigger B, firing trigger Cโฆ |
| Recursion | A trigger on products that updates products can loop |
| Bulk operations | TRUNCATE does not fire delete triggers. SQL Server BULK INSERT needs FIRE_TRIGGERS; MySQL LOAD DATA fires insert triggers |
| Transaction scope | An error inside a trigger rolls back the whole outer transaction |
[!WARNING] โ ๏ธ Check each ingestion path. SQL Server
BULK INSERTskips insert triggers unlessFIRE_TRIGGERSis specified; MySQLLOAD DATA INFILEactivates insert triggers. Neither engine fires delete triggers forTRUNCATE. Test the actual operation and permissions used by your loader. See the MySQL trigger reference and SQL Server BULK INSERT options.
[!TIP] ๐ก Modern alternatives to consider first:
- Auditing: MSSQL temporal tables (
SYSTEM_VERSIONING, which keep every old version of each row automatically), Change Data Capture, or tools that read MySQLโs binary log โ all more reliable than hand-written triggers.- Derived values: computed/generated columns (Chapter 41) or a scheduled recalculation.
- Validation:
CHECKconstraints and foreign keys, which the optimizer understands and cannot be bypassed.- Business rules: the application or a stored procedure, where they are testable and visible.
39.6 ๐งญ Managing triggers
-- ๐ฅ MSSQL
SELECT t.name AS trigger_name, OBJECT_NAME(t.parent_id) AS table_name, t.is_disabled
FROM sys.triggers t WHERE t.parent_class = 1;
DISABLE TRIGGER trg_products_audit ON products;
ENABLE TRIGGER trg_products_audit ON products;
DROP TRIGGER IF EXISTS trg_products_audit;
-- ๐ฆ MySQL
SHOW TRIGGERS FROM ShopDB;
SELECT trigger_name, event_manipulation, event_object_table, action_timing
FROM information_schema.triggers WHERE trigger_schema = 'ShopDB';
DROP TRIGGER IF EXISTS trg_products_audit;
-- MySQL has no DISABLE; you must drop and recreate
39.7 ๐ฏ When a trigger is the right answer
| Requirement | Trigger? | Better option |
|---|---|---|
| Audit every change to a table | โ ๏ธ Works | Temporal tables ๐ฅ / CDC / binlog โ cannot be bypassed by bulk loads |
| Keep a derived column in sync | โ No | A computed/generated column (Ch 41) |
| Enforce โprice must be โฅ 0โ | โ No | A CHECK constraint โ the optimizer understands it |
| Enforce โchild must existโ | โ No | A foreign key |
| Enforce a rule spanning other tables | โ Yes | (a CHECK cannot see other tables) |
| Normalize input (lowercase an email) | โ
BEFORE trigger ๐ฆ |
Or do it in the application |
| Make a joined view updatable | โ
INSTEAD OF trigger ๐ฅ |
ย |
| Send an email / call an API | โ Never | Write to a queue table; process it outside |
39.8 ๐งช Try it yourself
- Build the
product_price_historytable and its trigger, then change a price and check the log. - In MSSQL, update 5 products at once and verify your trigger logged all 5, not 1.
- Write a
BEFORE INSERTtrigger (MySQL) that lowercases emails. Test it. - Write a trigger that prevents deleting a product that has ever been ordered.
- Explain in one sentence why a
TRUNCATEwould defeat your audit trigger.
๐งญ In practice โ triggers
How to use it.
CREATE TRIGGER ... AFTER INSERT ON tableruns code automatically whenever data changes. SQL Server exposes the changed rows as theinsertedanddeletedpseudo-tables; MySQL exposesNEWandOLDper row. Expected result: a side effect โ usually an audit row โ that no application can forget to perform.When to use it. For auditing and for integrity rules that a constraint cannot express โ recording every price change, or enforcing a rule that spans several tables.
Where to use it. Audit and compliance. Scenario: a trigger on
productswrites the old and new price to a history table on everyUPDATE. Because it lives in the database, it captures changes made by the website, an admin tool, and someone running SQL by hand โ which is exactly what an auditor asks about.When not to use it. Avoid triggers for business logic. They are invisible: a developer reading the application sees an
UPDATEand has no way to know that three other tables changed, a row was rejected, or a slow operation ran inside their transaction. Never call an external service or send mail from a trigger; it runs inside the transaction and will hold locks or fail the whole statement. Cascading triggers that fire other triggers are genuinely hard to debug.Best practices. In SQL Server, write triggers to handle sets, not single rows: a trigger fires once per statement, so
UPDATE products SET price = price * 1.1fires it once with 18 rows ininserted. AssigningSELECT @id = product_id FROM insertedsilently captures one arbitrary row and loses the rest โ the single most common trigger bug there is. Keep triggers short, and document their existence prominently, because nothing else will.
40. Temporary tables and table variables
| ๐๏ธ Level | โฑ๏ธ Time | ๐ฏ After this chapter you canโฆ |
|---|---|---|
| ๐ก Intermediate | 20 min | Store in-between results ยท Choose between #temp, @table, and a CTE ยท Break a huge query into simple steps |
[!NOTE] ๐ In plain words: Sometimes a query is too complex for one statement. Temporary tables let you store in-between results, work with them, and throw them away when your connection ends.
๐ Analogy: Scrap paper while doing a long sum. You write the half-way answers down, use them for the next step, and throw the paper away when you are finished.
40.1 ๐ฅ MSSQL temporary tables
-- LOCAL temp table: visible only to YOUR session, dropped when it ends
CREATE TABLE #customer_spend (
customer_id INT PRIMARY KEY,
full_name NVARCHAR(100),
total_spend DECIMAL(12,2),
order_count INT
);
INSERT INTO #customer_spend (customer_id, full_name, total_spend, order_count)
SELECT
c.customer_id,
c.full_name,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)),
COUNT(DISTINCT o.order_id)
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;
-- ๐ก You can index a temp table โ a big advantage over CTEs
CREATE INDEX ix_temp_spend ON #customer_spend(total_spend DESC);
-- Use it repeatedly, cheaply
SELECT TOP 5 * FROM #customer_spend ORDER BY total_spend DESC;
SELECT AVG(total_spend) FROM #customer_spend;
SELECT * FROM #customer_spend WHERE order_count >= 3;
DROP TABLE #customer_spend;
-- Shortcut: SELECT INTO creates the temp table for you
SELECT c.customer_id, c.full_name, SUM(oi.quantity) AS units
INTO #quick_temp
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.full_name;
| Object | Who can see it | How long it lives |
|---|---|---|
#table |
Your session only | Until the session ends or you drop it |
##table |
All sessions (global) | Until the creating session ends |
@table (table variable) |
The current batch only | Ends with the batch |
40.2 ๐ฅ MSSQL table variables
DECLARE @top_products TABLE (
product_id INT PRIMARY KEY,
product_name NVARCHAR(120),
units_sold INT
);
INSERT INTO @top_products
SELECT TOP 5 p.product_id, p.product_name, SUM(oi.quantity)
FROM products p
JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY p.product_id, p.product_name
ORDER BY SUM(oi.quantity) DESC;
SELECT * FROM @top_products;
| ย | #temp table |
@table variable |
|---|---|---|
| Statistics | โ Yes โ good plans | โ No โ historically estimated as 1 row |
| Indexes | โ Can add any index | โ ๏ธ Only constraints declared inline |
| Transactions | โ Participates, rolls back | โ Survives a rollback |
| Re-planning (recompiles) | Can trigger it | Less often |
| Best for | More than ~100 rows | Small sets (under ~100 rows) |
[!TIP] ๐ก The practical rule: small result โ table variable; large or joined-heavily โ
#temptable with an index. The old advice that โtable variables live in memoryโ is a myth โ both live intempdb(SQL Serverโs shared scratch database). The real difference is statistics.
40.3 ๐ฆ MySQL temporary tables
-- Session-scoped, auto-dropped at disconnect
CREATE TEMPORARY TABLE tmp_customer_spend (
customer_id INT PRIMARY KEY,
full_name VARCHAR(100),
total_spend DECIMAL(12,2),
order_count INT
) ENGINE=InnoDB;
INSERT INTO tmp_customer_spend
SELECT
c.customer_id, c.full_name,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)),
COUNT(DISTINCT o.order_id)
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;
CREATE INDEX ix_tmp_spend ON tmp_customer_spend(total_spend);
SELECT * FROM tmp_customer_spend ORDER BY total_spend DESC LIMIT 5;
DROP TEMPORARY TABLE IF EXISTS tmp_customer_spend;
-- Or create it directly from a query
CREATE TEMPORARY TABLE tmp_quick AS
SELECT category_id, COUNT(*) AS n FROM products GROUP BY category_id;
[!WARNING] โ ๏ธ The MySQL temporary-table limitation that surprises everyone: you cannot reference the same temporary table twice in one query. This fails:
-- ๐ฆ MySQL CREATE TEMPORARY TABLE tmp_a (x INT); SELECT * FROM tmp_a WHERE x IN (SELECT x FROM tmp_a); -- ERROR 1137The workaround is to create a second temporary table with the same content, or use a CTE.
[!WARNING] โ ๏ธ A MySQL temporary table can hide a real table with the same name. If you have a real
orderstable and createTEMPORARY TABLE orders, every subsequent query in that session silently hits the temporary one. Always prefix temp tables withtmp_.
40.4 ๐งญ Choosing the right tool
Do you need the result more than once in the SAME query?
โโ No โ just use a derived table or subquery
โโ Yes โ
Is the intermediate result small (under ~100 rows)?
โโ Yes โ CTE (readable) or table variable (MSSQL)
โโ No โ
Do you need an index or statistics on it?
โโ Yes โ temp table (#temp / CREATE TEMPORARY TABLE)
โโ No โ CTE is fine
Do you need it across multiple statements or procedures?
โโ Yes โ temp table
[!TIP] ๐ก A frequently overlooked win: breaking one monstrous 200-line query into three steps with
#temptables often runs faster than the single query, because the optimizer knows the real row count at each step, instead of piling guess upon guess across ten joins.
40.5 ๐งช Try it yourself
- Build a temp table of customer lifetime values, index it, and query it three different ways.
- In MSSQL, compare
#tempvs@tablefor the same 1000-row dataset and inspect both plans. - In MySQL, try referencing a temporary table twice in one query and read the error.
- Split a complex 4-join report into two temp-table steps and compare the timings.
๐งญ In practice โ temporary tables and table variables
How to use it. SQL Server:
#temptables live intempdbfor the session;@tablevariables are declared and scoped to the batch. MySQL:CREATE TEMPORARY TABLE. All disappear when the session ends. Expected result: an intermediate result you can index, inspect, and reuse across several statements.When to use it. When a multi-step process needs an intermediate result more than once, and when a CTE would otherwise be re-executed each time it is referenced.
Where to use it. ETL, batch jobs, and complex reports. Scenario: a month-end report filters ten million orders down to forty thousand, then joins that set to four other tables. Materialising the filtered set into a temp table once โ and indexing it โ is far faster than repeating the filter in four places.
When not to use it. Do not use a temp table where a single query or a CTE will do; you are adding a write, a read, and statistics work for nothing. In SQL Server, avoid table variables for large row counts: historically the optimiser assumed one row, producing badly wrong plans. Temp tables get real statistics and are the safer default above a few hundred rows.
Best practices. Index a temp table after you populate it, and only if you will query it more than once. Drop temp tables explicitly in long-running sessions rather than relying on scope. Remember that heavy
tempdbuse is a shared resource on SQL Server โ one badly written report can slow every other query on the instance.
41. Sequences and generated columns
| ๐๏ธ Level | โฑ๏ธ Time | ๐ฏ After this chapter you canโฆ |
|---|---|---|
| ๐ก Intermediate | 20 min | Hand out numbers from a shared counter ยท Let the database calculate columns for you ยท Make an expression searchable with an index |
[!NOTE] ๐ In plain words: Two ways to let the database fill in values for you. A sequence hands out the next number in a series. A generated column calculates its own value from other columns in the same row.
๐ Analogy: A sequence is the ticket machine at a deli counter โ every customer pulls the next number. A generated column is the โtotalโ box on a form that fills itself in as soon as you enter the price and quantity.
41.1 ๐ข Sequences โ shared, independent counters
[!NOTE] ๐ In plain words: A sequence is a number generator that lives outside any table. Several tables can draw from the same sequence, and you can get a number before inserting a row.
-- ๐ฅ MSSQL (2012+)
CREATE SEQUENCE seq_invoice_number
AS BIGINT
START WITH 100000
INCREMENT BY 1
MINVALUE 100000
MAXVALUE 999999999
NO CYCLE
CACHE 50; -- keep 50 numbers ready in memory, for speed (a crash may skip some)
GO
-- Get the next value
SELECT NEXT VALUE FOR seq_invoice_number AS invoice_no;
GO
-- โ ๏ธ This is a DIFFERENT table from the `invoices` used in Chapter 10 โ
-- that one demonstrated IDENTITY. A sequence-driven table needs its own DDL.
CREATE TABLE sales_invoices (
invoice_no BIGINT NOT NULL PRIMARY KEY,
order_id INT NOT NULL,
amount DECIMAL(10,2) NOT NULL,
issued_at DATETIME2(0) NOT NULL DEFAULT SYSDATETIME()
);
GO
-- Use the sequence explicitly in an INSERT
INSERT INTO sales_invoices (invoice_no, order_id, amount)
VALUES (NEXT VALUE FOR seq_invoice_number, 1002, 3757.10);
-- Or wire it up as the column default, so you never mention it again
ALTER TABLE sales_invoices
ADD CONSTRAINT df_invoice_no
DEFAULT (NEXT VALUE FOR seq_invoice_number) FOR invoice_no;
GO
INSERT INTO sales_invoices (order_id, amount) VALUES (1019, 2352.05);
SELECT invoice_no, order_id, amount FROM sales_invoices ORDER BY invoice_no;
GO
-- Manage it
ALTER SEQUENCE seq_invoice_number RESTART WITH 200000;
-- DROP SEQUENCE seq_invoice_number; -- fails while the default still references it
Result:
| invoice_no | order_id | amount |
|---|---|---|
| 100001 | 1002 | 3757.10 |
| 100002 | 1019 | 2352.05 |
[!WARNING] โ ๏ธ You cannot drop a sequence that a
DEFAULTconstraint still references. Drop the constraint first (ALTER TABLE sales_invoices DROP CONSTRAINT df_invoice_no;), then the sequence.
๐ MySQL has no
CREATE SEQUENCE. Imitate it with a small counter table:
-- ๐ฆ MySQL: a table that imitates a sequence
CREATE TABLE sequences (
seq_name VARCHAR(64) PRIMARY KEY,
seq_value BIGINT NOT NULL
) ENGINE=InnoDB;
INSERT INTO sequences VALUES ('invoice_number', 100000);
-- A procedure, not a function: with binary logging on (the MySQL 8 default), a function
-- that modifies data is rejected with ERROR 1418 unless an administrator enables
-- log_bin_trust_function_creators. A procedure has no such restriction.
DELIMITER $$
CREATE PROCEDURE next_sequence_value(IN p_name VARCHAR(64), OUT p_value BIGINT)
BEGIN
UPDATE sequences SET seq_value = LAST_INSERT_ID(seq_value + 1)
WHERE seq_name = p_name;
IF ROW_COUNT() = 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Unknown sequence name';
END IF;
SET p_value = LAST_INSERT_ID();
END$$
DELIMITER ;
CALL next_sequence_value('invoice_number', @next);
SELECT @next AS invoice_no; -- 100001
[!TIP] ๐ก The
LAST_INSERT_ID(expr)trick. Passing a value toLAST_INSERT_ID()stores it for your connection only, in the same step as the update. The row update serializes concurrent increments. The missing-name guard is essential: without it, a zero-row update would leave the connectionโs previous value intact. A caller rollback can undo this counter update, so do not promise permanent, gapless or non-reused numbers outside a defined transaction policy.
| ย | IDENTITY / AUTO_INCREMENT |
Sequence |
|---|---|---|
| Belongs to | One table, one column | The database โ shared by many tables |
| Get a value before inserting | โ No | โ Yes |
| Reuse the same series across tables | โ No | โ Yes |
| MySQL support | โ Built in | โ ๏ธ Imitated with a table |
[!IMPORTANT] ๐ฏ When a sequence genuinely helps: a single document-number series shared by invoices, credit notes, and receipts; or when the application needs the ID before the insert (to build a file name, a URL, or child rows).
41.2 ๐งฎ Computed and generated columns
[!NOTE] ๐ In plain words: A column whose value is calculated from other columns instead of being stored by you. You never insert into it; the database keeps it correct forever.
-- ๐ฅ MSSQL: computed columns
CREATE TABLE order_lines_demo (
order_id INT NOT NULL,
product_id INT NOT NULL,
unit_price DECIMAL(10,2) NOT NULL,
quantity INT NOT NULL,
discount DECIMAL(4,3) NOT NULL DEFAULT 0,
-- VIRTUAL: computed on every read, no storage used
gross_total AS (unit_price * quantity),
-- PERSISTED: physically stored, so reading it costs nothing extra
net_total AS (unit_price * quantity * (1 - discount)) PERSISTED,
CONSTRAINT pk_old PRIMARY KEY (order_id, product_id)
);
-- Computed columns can be indexed (see the rules in the warning below):
CREATE INDEX ix_old_net_total ON order_lines_demo(net_total);
-- ๐ฆ MySQL 5.7+: generated columns
CREATE TABLE order_lines_demo (
order_id INT NOT NULL,
product_id INT NOT NULL,
unit_price DECIMAL(10,2) NOT NULL,
quantity INT NOT NULL,
discount DECIMAL(4,3) NOT NULL DEFAULT 0,
gross_total DECIMAL(12,2) AS (unit_price * quantity) VIRTUAL,
net_total DECIMAL(12,2) AS (unit_price * quantity * (1 - discount)) STORED,
PRIMARY KEY (order_id, product_id)
) ENGINE=InnoDB;
CREATE INDEX ix_old_net_total ON order_lines_demo(net_total);
| ย | VIRTUAL |
PERSISTED / STORED |
|---|---|---|
| Storage used | None | Yes |
| Computed | On every read | On write |
| Can be indexed | โ
Yes, if the calculation is deterministic (MSSQL: and not FLOAT-based) |
โ Yes |
| Write cost | None | Small |
| Best for | Cheap expressions read rarely | Expensive expressions, or ones you filter and sort on |
A genuinely powerful use โ indexing a case-insensitive search key:
-- ๐ฆ MySQL: make LOWER(email) searchable via an index
ALTER TABLE customers
ADD COLUMN email_lower VARCHAR(150)
AS (LOWER(email)) STORED,
ADD INDEX ix_customers_email_lower (email_lower);
-- Now this search can use the index instead of reading the whole table:
SELECT * FROM customers WHERE email_lower = 'amara.silva@example.com';
-- ๐ฅ MSSQL: the same idea
ALTER TABLE customers ADD email_lower AS (LOWER(email)) PERSISTED;
CREATE INDEX ix_customers_email_lower ON customers(email_lower);
[!TIP] ๐ก This is the standard cure for the โa function on a column stops the index being usedโ problem from Chapter 48. SQL Server uses a computed-column index for this shape. MySQL 8.4 also supports functional key parts, for example
CREATE INDEX ix_email_expression ON customers ((LOWER(email))); a named generated column is another option. Avoid creating redundant indexes and check collation/search semantics. See MySQL functional indexes.
[!WARNING] โ ๏ธ SQL Server permits nondeterministic nonpersisted computed expressions, for example one using
GETDATE(). Such a column cannot bePERSISTEDor indexed. Indexable computed columns have determinism, precision, data-type, ownership and SET-option requirements; persistence alone does not make every expression indexable. MySQL generated expressions have their own restrictions. See SQL Server computed columns and index requirements.
41.3 ๐งช Try it yourself
- Add a persisted/stored
line_totalcolumn toorder_itemsand index it. - Create a sequence (MSSQL) or sequence table (MySQL) for invoice numbers and draw five values.
- Add a
full_name_uppercomputed column tocustomersand index it. Verify withEXPLAINthat a search on it seeks rather than scans. - ๐ฅ SQL Server: compare a nonpersisted computed column using
GETDATE()with aPERSISTEDone; explain why the first is allowed and the second rejected.
๐งญ In practice โ sequences and generated columns
How to use it. A sequence (
CREATE SEQUENCE, SQL Server 2012+) is a standalone number generator not tied to a table โ useful when several tables must draw from one series. A generated (computed) column is defined by an expression and can beSTOREDorVIRTUAL. Expected result: numbers and derived values maintained by the database rather than by application code.When to use it. Sequences when one numbering series spans several tables, or when you need the next value before inserting. Generated columns when a value is always derived from others in the same row.
Where to use it. Document numbering and derived search keys. Scenario: a
line_totalgenerated column defined asquantity * unit_pricecan never disagree with its inputs, and in MySQL aSTOREDgenerated column can be indexed โ which lets you index a normalised form of a column (say,LOWER(email)) and get index-backed case-insensitive lookups.When not to use it. Do not use a sequence when a plain
IDENTITY/AUTO_INCREMENTwill do โ it is more moving parts for no gain. Do not assume sequences are gapless; caching means a restart can skip a block of values. AvoidSTOREDgenerated columns for cheap expressions whereVIRTUALcosts nothing, and avoid either for anything non-deterministic.Best practices. If a regulator requires unbroken numbering, neither a sequence nor an auto-increment column gives it to you โ that needs a deliberately serialised counter and a transaction, with the contention that implies. Use generated columns to make invalid states unrepresentable: a total that is computed can never drift from its parts, which removes a whole class of reconciliation bug.
| Part index | Prerequisites | Previous | Next | Full course |