- Learn
- Computer Science & IT
- Programming
- Database Design and Advanced SQL
- SQL Views and Stored Procedures
SQL Views and Stored Procedures: Database Security
IntermediateLesson 7 of 8 in Database Design and Advanced SQL Course
What you will learn
- Package queries under a name with views, change data through simple views safely, and store expensive results with materialized views.
- Create, query and manage viewsWrite CREATE VIEW statements, query a view like a table, and replace or drop a view while knowing what it does and does not store.
- Change data through updatable viewsDecide when INSERT, UPDATE and DELETE can run against a view, and use WITH CHECK OPTION so that changed rows stay inside the view.
- Store query results with materialized viewsCreate and refresh materialized views, judge when stored results are worth being slightly out of date, and compare how database systems support them.
- Create, query and manage views
- Keep reusable logic in the database as functions that return values and procedures that carry out tasks, using parameters, control flow and error handling.
- Write user-defined functionsCreate functions that return one value or a set of rows, call them inside queries, and describe how they behave so the database can use them correctly.
- Write stored procedures with parameters and control flowCreate procedures that carry out multistep tasks, pass values in and out, use variables, conditions and loops, and make the whole task succeed or fail as one unit.
- Handle errors and compare procedural dialectsRaise and catch errors in routines, read and translate routine code between PL/pgSQL, T-SQL and MySQL, and decide which logic belongs in the database.
- Write user-defined functions
- Write triggers that run automatically when data changes, choose their timing and level, and keep their effects predictable.
- Write row-level triggers with OLD and NEWCreate BEFORE and AFTER triggers that react to each changed row, read its old and new values, and decide when a trigger is the right tool.
- Use statement-level and INSTEAD OF triggers safelyHandle statement-level triggers and their multi-row data, make views writable with INSTEAD OF triggers, and avoid hidden, recursive or slow trigger logic.
- Write row-level triggers with OLD and NEW
- Set up users and roles, grant only the privileges each task needs, expose data through views and routines, and limit visible rows with row-level security.
- Set up users and roles with least privilegeCreate login identities and roles in PostgreSQL, MySQL and SQL Server, organize privileges through roles, and give every account only what its task needs.
- Grant and revoke privilegesUse GRANT and REVOKE on tables, columns, schemas and routines, pass on grant rights with care, and check what a user can actually do.
- Expose data safely through views and routinesGive users selected columns, rows or actions without rights on the base tables, and choose between definer rights and invoker rights.
- Restrict rows with row-level securityWrite row-level security policies that limit which rows each user or tenant can see and change, and close the common gaps.
- Set up users and roles with least privilege
- Explain how SQL injection turns input into code, write parameterized queries, and secure dynamic SQL with allow-lists, least privilege and safe error handling.
- Explain how SQL injection worksRecognize code that builds SQL from untrusted input, trace how crafted input changes the statement, and describe what attackers can gain.
- Write parameterized queriesSend values separately from the SQL text with placeholders in common programming languages, and avoid the mistakes that quietly bring concatenation back.
- Secure dynamic SQL and add defense in depthKeep SQL built inside stored routines safe, take identifiers from allow-lists, and limit the damage of any remaining flaw with validation, least privilege and careful error handling.
- Explain how SQL injection works
SQL Views and Stored Procedures study guide
1Build and use views
Views give repeated queries a name and a stable interface. You will trace where a view’s rows come from, decide which displayed values can be changed, and use check options to keep writes inside a view’s filter. Materialized views introduce a different choice: save the result for quick reads, then choose when to refresh it. The examples connect those choices to customer reports and order updates.
1.1 Create, query and manage views
A view saves a query under a name. You can read it like a table, filter it, join it, and aggregate its columns. A plain view stores the query definition; its rows come from the underlying base tables when you query it.
Give a report a stable name
The shop wants every report to exclude canceled orders. Its view joins customers to orders and groups the remaining orders by customer:
CREATE VIEW customer_order_totals AS
SELECT c.customer_id, c.name,
COUNT(o.order_id) AS order_count,
SUM(o.total) AS total_spent
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status <> 'canceled'
GROUP BY c.customer_id, c.name;
Aliases such as order_count make computed columns clear to callers. SQL Server requires a name for a computed view column. PostgreSQL can supply names such as count, but those names make a poor report interface.
Ana Silva has orders of 40.00 and 25.50; Ben Okafor has 120.00 and 9.75; Dana Novak has 15.25. Chen Wei has only a canceled order of 60.00. Reading the view gives Ana 2 orders and 65.50, Ben 2 and 129.75, and Dana 1 and 15.25. Chen has no surviving joined row, so Chen does not appear. To include customers with no qualifying orders, use a left join with the status condition in its ON clause. Count the order key; the unmatched customer then has a count of 0 and a NULL sum.
Read current data
SELECT name, total_spent
FROM customer_order_totals
WHERE total_spent > 50
ORDER BY total_spent DESC;
This returns Ben, then Ana. The outer ORDER BY supplies the sorting guarantee. An order specified inside a view does not guarantee the order of a later query's output.
After Dana receives a paid order of 30.00, the view shows 2 orders and 45.25 without a refresh. The result follows the data visible to the reading statement under the transaction's snapshot rules. Saving the query does not itself remove the join or aggregation work, so a plain view is not a result cache or a speed guarantee.
Views also keep business rules in one place, hide selected columns or rows, and give applications a stable interface while table design changes. A common table expression exists for one statement; a saved view can serve many statements and authorized users. A PostgreSQL temporary view lasts only for its session.
Change the interface carefully
Use CREATE OR REPLACE VIEW in PostgreSQL and MySQL. PostgreSQL requires existing column names, types, and order to stay the same; extra columns may be appended. Use ALTER VIEW ... RENAME COLUMN to rename a column. Removing a column or changing its type requires dropping and rebuilding the view and handling its dependencies. SQL Server offers ALTER VIEW and CREATE OR ALTER VIEW.
List columns explicitly. In PostgreSQL and MySQL, SELECT * is expanded when the view is created; a column added to the table later does not simply appear in the saved view.
DROP VIEW customer_order_totals; removes the view, leaving the tables. PostgreSQL blocks dropping a table that a view depends on unless CASCADE also removes the dependent objects. SQL Server's ordinary views can instead become invalid after a table is dropped; WITH SCHEMABINDING prevents changes that would break a bound view.
Key Takeaways
- A plain view saves a query and reads base-table data visible to the current statement.
- Name computed columns and sort in the outer query.
- Join type and filter placement determine whether unmatched customers appear.
- A saved view is reusable; a CTE belongs to one statement.
- View changes must preserve or deliberately rebuild dependent interfaces.
1.2 Change data through updatable views
An updatable view lets a data change pass through to a base table. The database must be able to identify the stored row being changed. A view's displayed value is not necessarily a writable value: a sum or calculation may have no single base column to update.
Follow a change to its table
CREATE VIEW paid_orders AS
SELECT order_id, customer_id, status, total
FROM orders
WHERE status = 'paid';
UPDATE paid_orders
SET total = 26.00
WHERE order_id = 102;
If order 102 is paid, the update changes its total in orders. There is no separate copy inside the view. A delete targeting a shipped order through this view changes 0 rows because that order is not visible through it.
In PostgreSQL, automatic updating requires exactly one table or updatable view in the FROM list. The top level must have no WITH, DISTINCT, grouping, HAVING, limiting, offset, or set operations. Aggregates, window functions, and set-returning functions in the select list also prevent automatic updating. Plain references to base columns are writable; a computed column in an otherwise eligible view remains read-only.
For example, adding total * 1.21 AS total_with_tax does not create a stored tax-inclusive total to edit. Change total, and the next query calculates the displayed amount. The grouped customer_order_totals view cannot accept an update to total_spent: changing a customer's sum does not specify which orders should change.
Keep changed rows visible
Without a check option, this succeeds for a paid order:
UPDATE paid_orders
SET status = 'shipped'
WHERE order_id = 102;
The base row remains, but disappears from paid_orders. An insert with a different status can likewise create a row that the inserting view cannot show. A view's WHERE clause selects the rows an update can target; by itself, it does not require the updated row to stay selected.
CREATE OR REPLACE VIEW paid_orders AS
SELECT order_id, customer_id, status, total
FROM orders
WHERE status = 'paid'
WITH CHECK OPTION;
Now an insert or update through this view must leave the row paid. Attempting the status change raises an error and leaves order 102 unchanged. A direct update to orders is not governed by the view's check option. Access control matters if users must always follow this route.
Check layered views and required columns
For views built on other views, LOCAL checks the current view's condition plus check options already imposed by lower views. CASCADED also checks lower views' filtering conditions even when they have no check option. PostgreSQL and MySQL use cascaded checking when LOCAL or CASCADED is omitted.
Insertability needs more than a traceable row. If the base table requires a non-NULL value with no default, the insert must provide it. Omitting that column from the view does not remove the table's requirement. MySQL also rejects inserts through views that contain computed columns; each product's exact rules matter.
An INSTEAD OF trigger can supply custom write behavior for a view that is not automatically updatable. In PostgreSQL, check options do not enforce conditions on trigger-updatable views, so the trigger must perform those checks itself. SQLite views need such triggers for writes.
Key Takeaways
- An eligible view forwards writes to its base table; computed values stay read-only.
- WITH CHECK OPTION rejects view inserts and updates that would leave its permitted rows.
- A view cannot target a row it hides.
- Check options apply to writes through the view, not direct writes to its table.
- CASCADED also checks underlying view conditions; LOCAL preserves lower views’ own check options.
- An insert must still satisfy the base table’s required columns.
1.3 Store query results with materialized views
A materialized view stores query results. It trades extra storage and refresh work for quick reads of a precomputed result. Its defining question is how old the result may be before it becomes unhelpful.
Store an aggregate once
CREATE MATERIALIZED VIEW monthly_sales AS
SELECT date_trunc('month', order_date) AS month,
COUNT(*) AS order_count,
SUM(total) AS revenue
FROM orders
WHERE status <> 'canceled'
GROUP BY 1;
PostgreSQL executes the query and stores one result row per month. Reading monthly_sales reads those stored rows; it does not regroup all orders each time. An index can further help queries against the stored result, just as on a table.
In the shop data, the saved result contains March 2026 with 4 orders and 200.75, and April with 1 order and 9.75. A new April order of 30.00 changes orders, but the materialized view still reports 1 order and 9.75. A plain view over the same query already reports 2 orders and 39.75. The difference is the stored snapshot, not a disagreement in the aggregation rule.
REFRESH MATERIALIZED VIEW monthly_sales;
The refresh reruns the defining query and replaces the old contents. April now shows 2 orders and 39.75. PostgreSQL does not schedule this automatically. The application or a scheduled job must decide when to refresh. Update the base tables, then refresh; PostgreSQL materialized views do not accept ordinary INSERT, UPDATE, or DELETE changes to their result rows.
Keep readers working during refresh
A normal refresh prevents other sessions from reading the materialized view until it finishes. For a dashboard that must remain available, prepare a qualifying unique index and refresh concurrently:
CREATE UNIQUE INDEX monthly_sales_month_uq
ON monthly_sales (month);
REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_sales;
The unique index must use column names and include all rows. An expression index or an index with a WHERE clause does not meet that requirement. The materialized view must already be populated; CONCURRENTLY cannot perform its first population. Readers can keep using the stored result while the refresh proceeds.
Choose by freshness and workload
| Choice | What a read uses | What follows a base-table change |
|---|---|---|
| Plain PostgreSQL view | The saved query over visible table data | The next query sees data according to its snapshot |
| PostgreSQL materialized view | Stored result rows | A later refresh updates the result |
| SQL Server indexed view | Stored indexed result | Eligible table writes maintain the result |
An hourly sales dashboard can accept a result from the last refresh. A screen deciding whether an order can ship needs current operational data. Repeated expensive joins or grouping over mostly unchanged data are good candidates for materialization; a cheap query over rapidly changing data may gain little after refresh cost is counted.
SQL Server uses an indexed view: a schema-bound view with a unique clustered index, subject to its indexed-view rules. Maintenance happens with base-table writes and adds work to them. MySQL has no native materialized view; teams use summary tables refreshed by scheduled events or maintained with triggers. Oracle supports materialized views with options such as scheduled or on-commit refresh.
Key Takeaways
- A materialized view stores results until a refresh replaces them.
- Choose a refresh schedule from the report’s acceptable age.
- Concurrent refresh needs populated data and an all-row, column-based unique index.
- SQL Server indexed views maintain results on writes; MySQL commonly uses summary tables.
2Write stored functions and procedures
Stored routines keep a calculation or database task in one reusable place. Functions return values or rows to a query; procedures coordinate work through their own calls. You will build a checked transfer, follow its success and failure paths, and compare the transaction and error rules in PostgreSQL, SQL Server, and MySQL. Parameter modes and set-based statements help keep these routines clear and useful.
2.1 Write user-defined functions
A user-defined function is saved database code that returns a value or rows to an SQL statement. Use one when many queries need the same calculation or parameter-driven result. Its return type and behavior form part of its interface.
Return a scalar value
CREATE FUNCTION line_total(
qty integer, unit_price numeric, discount_pct numeric
)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT round(qty * unit_price * (1 - discount_pct / 100), 2)
$$;
LANGUAGE sql means the body is SQL. The paired dollar-quote markers enclose the body without making you double every single quote inside it. LANGUAGE plpgsql adds variables, branching, and loops when a SQL expression alone is not enough.
SELECT line_total(3, 12.50, 10); returns 33.75. Three items cost 37.50 before the discount; the 10% discount leaves 90%, giving 33.75. A query can call the function for each order-item row:
SELECT order_id,
line_total(quantity, unit_price, discount_pct) AS total
FROM order_items;
This is a scalar function: each call supplies one value. Keeping the formula in the function avoids slightly different discount calculations in separate reports.
Return rows with an argument
CREATE FUNCTION orders_for_customer(p_customer_id integer)
RETURNS TABLE (order_id integer, total numeric)
LANGUAGE sql
STABLE
AS $$
SELECT o.order_id, o.total
FROM orders o
WHERE o.customer_id = p_customer_id
$$;
Call this table function in FROM: SELECT * FROM orders_for_customer(2);. In the shop data, it returns orders 103 and 106 with totals 120.00 and 9.75. Unlike a view, it accepts a customer argument. Qualifying columns with o. and using the parameter prefix p_ also makes the intended comparison clear.
Describe behavior truthfully
PostgreSQL's volatility label tells its planner which assumptions are safe:
| Label | Promise | Example |
|---|---|---|
IMMUTABLE | The same arguments always give the same result | The discount calculation |
STABLE | The same arguments give the same result within one statement; no data changes | Reading a customer's orders |
VOLATILE | Results or database state may change between calls | Random values or data-changing functions |
VOLATILE is the default. A table-reading function must not be called immutable just because its arguments stay the same. Rows can change, and an incorrect label can let the planner reuse an obsolete value.
Arithmetic with NULL gives NULL, so line_total(3, NULL, 10) returns NULL. Marking a function STRICT skips its body and returns NULL whenever any argument is NULL. If the business rule treats a missing discount as zero, handle that inside the body with COALESCE(discount_pct, 0); strict behavior would prevent that default from being calculated.
In SQL Server, scalar functions use @ parameters, declare a return type, and are called with a schema name such as dbo.LineTotal. T-SQL functions cannot change permanent-table data. MySQL stored functions return one value, not a result set; with default binary logging, declarations such as DETERMINISTIC, NO SQL, or READS SQL DATA are also required unless configuration changes the rule.
Key Takeaways
- A scalar function returns one value; a table function returns rows and can accept arguments.
- SQL bodies handle queries and expressions; PL/pgSQL adds procedural control flow.
- Volatility labels are promises to the planner, not performance settings.
- STRICT returns NULL without running the body when any argument is NULL.
- Use COALESCE when a missing input should become a business default.
2.2 Write stored procedures with parameters and control flow
A stored procedure carries out a task as its own statement. PostgreSQL and MySQL use CALL; SQL Server uses EXEC. A procedure can coordinate several changes, but its transaction behavior must make those changes a safe unit.
Build a checked transfer
The following PostgreSQL procedure assumes accounts.account_id is a primary key and balance is non-NULL. Parameters identify the source, destination, and amount. The local variable holds the source balance.
CREATE PROCEDURE transfer(p_from integer, p_to integer, p_amount numeric)
LANGUAGE plpgsql AS $$
DECLARE
v_balance numeric;
BEGIN
IF p_amount IS NULL OR p_amount <= 0 THEN
RAISE EXCEPTION 'Amount must be positive';
END IF;
SELECT balance INTO v_balance
FROM accounts WHERE account_id = p_from FOR UPDATE;
IF v_balance IS NULL THEN
RAISE EXCEPTION 'Unknown source account';
END IF;
IF v_balance < p_amount THEN
RAISE EXCEPTION 'Insufficient funds';
END IF;
UPDATE accounts SET balance = balance - p_amount
WHERE account_id = p_from;
UPDATE accounts SET balance = balance + p_amount
WHERE account_id = p_to;
IF NOT FOUND THEN
RAISE EXCEPTION 'Unknown destination account';
END IF;
END;
$$;
The positive-amount check prevents a negative input from reversing the transfer. SELECT ... INTO assigns the balance. FOR UPDATE locks the source row until the transaction ends, so a competing withdrawal cannot also act on the old balance. If the source is missing, the variable is NULL; an ordinary comparison with NULL would not enter the insufficient-funds branch.
The destination check is equally necessary. An UPDATE matching no row succeeds with a row count of zero. PostgreSQL's FOUND reports whether the preceding update changed a row. Raising an exception here prevents a withdrawal with no corresponding deposit.
Trace success and failure
Accounts 1 and 2 start at 500.00 and 120.00. CALL transfer(1, 2, 150.00); leaves 350.00 and 270.00. Their combined balance remains 620.00. A later attempt to transfer 400.00 from account 2 raises an error before either update.
There is no internal COMMIT. An uncaught error therefore undoes the call's changes, including a withdrawal followed by a missing-destination error. A top-level PostgreSQL procedure can end transactions when called outside an explicit transaction block, but each internal commit makes earlier work permanent. A later error cannot undo committed work. MySQL and SQL Server need an explicit transaction around multistep changes when autocommit would otherwise commit each statement separately.
Use parameters and control flow
IN supplies an input, OUT returns a result, and INOUT does both. PostgreSQL 14 and later return procedure OUT parameters as a result row; a SQL CALL supplies NULL in those positions. MySQL can pass an output into a session variable, then read it: CALL count_orders(2, @n); SELECT @n;.
PL/pgSQL declares variables before BEGIN, assigns with := or SELECT ... INTO, and branches with IF ... THEN ... ELSIF ... ELSE ... END IF. Loops handle genuinely dependent steps. For a price rise across a category, one statement is clearer and usually faster:
UPDATE products SET price = round(price * 1.10, 2)
WHERE category = 'tea';
Key Takeaways
- A procedure runs as a statement and coordinates a task.
- Validate amounts, missing rows, and balances before treating a transfer as successful.
- A zero-row UPDATE is not itself an error.
- Keep related changes in one transaction; internal commits cannot be undone by later errors.
- Lock the source row before using its balance for a withdrawal.
- Prefer set-based changes when rows can be handled together.
- IN supplies a value, OUT returns one, and INOUT does both.
2.3 Handle errors and compare procedural dialects
An error should tell the caller whether a database task succeeded. Handling an error is useful when you can recover or clean up; swallowing it can make a failed operation look complete. Transaction rules and error syntax differ across database products.
Raise and pass on failures
| Database | Raise an application error | Pass the current error on |
|---|---|---|
| PostgreSQL | RAISE EXCEPTION 'Insufficient funds'; | RAISE; |
| SQL Server | THROW 50001, 'Insufficient funds', 1; | THROW; |
| MySQL | SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient funds'; | RESIGNAL; |
SQL Server custom error numbers start at 50000. In PostgreSQL, % markers in the error message are replaced by following arguments. The application receives the raised failure through its database library.
A PL/pgSQL block can catch a named condition with EXCEPTION WHEN unique_violation THEN .... Database changes made inside that block are rolled back before its handler runs. After a successful recovery, execution can continue. If the handler cannot complete the requested task, re-raise the error so the caller does not report success.
Make a SQL Server task atomic
This T-SQL body assumes non-NULL balances and unique account keys. It owns the transaction for this task:
SET XACT_ABORT ON;
BEGIN TRY
IF @Amount IS NULL OR @Amount <= 0
THROW 50001, 'Amount must be positive', 1;
BEGIN TRANSACTION;
UPDATE dbo.Accounts SET Balance = Balance - @Amount
WHERE AccountId = @From AND Balance >= @Amount;
IF @@ROWCOUNT <> 1
THROW 50002, 'Source unavailable or funds too low', 1;
UPDATE dbo.Accounts SET Balance = Balance + @Amount
WHERE AccountId = @To;
IF @@ROWCOUNT <> 1
THROW 50003, 'Unknown destination', 1;
COMMIT;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
The withdrawal condition makes a missing source or low balance produce zero changed rows. Test @@ROWCOUNT immediately: it describes the preceding statement. A missing destination also raises an error. The catch block rolls back an open transaction and passes the failure outward. Many SQL Server runtime errors otherwise stop only one statement; the procedure can continue unless its control flow and transaction settings prevent that.
A MySQL procedure uses a transaction and an exit handler declared after its variables:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
The body starts the transaction with START TRANSACTION and commits only after all required changes succeed. Logging alone is not recovery; a normal return would mislead the caller.
Translate the language, not just keywords
PostgreSQL uses dollar-quoted bodies, a named language, and := for procedural assignment. T-SQL variables have @ names. GO, used in SQL Server client scripts, separates batches and is not a T-SQL statement. The mysql command-line client's DELIMITER // keeps semicolons inside a routine body from ending the creation command early; it is a client instruction too. SQLite has no stored procedures and implements custom functions in host code.
Stored routines centralize rules shared by applications and reduce network round trips. They can also expose a narrow authorized action. The costs include product-specific code, deployment and testing work, and extra load on the database server. Data-integrity rules often belong near the data; wider application workflows need not all move into routines.
Key Takeaways
- Catch an error only when recovery or cleanup has a purpose.
- Re-raise a failure when the requested task still failed.
- SQL Server and MySQL multistep work needs explicit transaction and error handling.
- Client commands such as GO and DELIMITER are distinct from server SQL.
- Choose database logic for shared data rules while accounting for testing and portability costs.
3Automate rules with triggers
Triggers make database work happen when a row or statement changes data. Their timing, level, and return behavior determine whether they can clean a value, record history, or replace a write through a view. You will follow an email cleanup, a price audit, and a soft delete, then handle the multi-row statements that make one-row assumptions fail. Trigger costs and recursion shape where this automation belongs.
3.1 Write row-level triggers with OLD and NEW
A trigger runs automatically when a table event occurs. Its timing says whether it runs before or after a change; its level says whether it runs for each row or once for the statement. Choose both deliberately, because they determine which data the trigger can use.
Read the old and new row
| Event | OLD | NEW |
|---|---|---|
| Insert | No previous row | The incoming row |
| Update | Values before the update | Values after the update |
| Delete | The row being removed | No replacement row |
A PostgreSQL trigger uses a function returning trigger, then a declaration attaching that function to an event. Here a before trigger cleans the email before storage:
CREATE FUNCTION normalize_email()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.email := lower(trim(NEW.email));
RETURN NEW;
END;
$$;
CREATE TRIGGER customers_normalize_email
BEFORE INSERT OR UPDATE OF email ON customers
FOR EACH ROW EXECUTE FUNCTION normalize_email();
Inserting ' Ana.Silva@Example.COM ' stores 'ana.silva@example.com'. A before insert or update row trigger returns NEW to continue with that row. Returning NULL skips the row's operation. A before delete trigger returns OLD to continue the deletion. An after row trigger's return value is ignored; it usually returns NULL.
Record actual price changes
An audit function can insert the product key, old price, new price, timestamp, and current user into price_history. Attach it after updates so it observes the finished row change:
CREATE FUNCTION log_price_change()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO price_history
(product_id, old_price, new_price, changed_at, changed_by)
VALUES (OLD.product_id, OLD.price, NEW.price, now(), current_user);
RETURN NULL;
END;
$$;
CREATE TRIGGER products_price_audit
AFTER UPDATE OF price ON products
FOR EACH ROW
WHEN (OLD.price IS DISTINCT FROM NEW.price)
EXECUTE FUNCTION log_price_change();
UPDATE OF price selects statements that assign the price column, including assignments that leave the value unchanged. The WHEN test then checks whether the value actually changed. IS DISTINCT FROM treats NULL versus a value as different and two NULLs as equal. A test with <> would evaluate to NULL if either price were NULL, missing that change.
A 10% rise on three teas priced 4.00, 5.50, and 7.20 produces 4.40, 6.05, and 7.92. The row trigger runs three times and records three changes. The audit inserts share the updating statement's transaction: rolling it back also removes its history rows.
Use the simplest rule that works
Use CHECK (price >= 0) for a nonnegative price, a foreign key for a referenced row, and UNIQUE for unique values. Constraints make those rules visible in the table definition. A trigger is useful for an audit trail, data cleanup, or logic that needs another table.
A before trigger can adjust or reject incoming data. An after trigger suits follow-up work on a completed change. Raising an exception in either makes the triggering statement fail and undoes its changes.
MySQL triggers are always row-level. A before trigger can assign NEW.email with SET; OLD remains read-only. MySQL does not run these triggers for row changes performed by foreign-key cascade actions. SQL Server's DML triggers instead receive sets of rows, so their bodies need a different design.
Key Takeaways
- Choose timing and row or statement level before writing a trigger.
- OLD and NEW exist only for the row versions relevant to the event.
- A PostgreSQL BEFORE row trigger returns the row to continue, or NULL to skip it.
- Use IS DISTINCT FROM when a change involving NULL must count.
- Audit changes and the triggering statement share a transaction.
- Prefer constraints for rules they can express directly.
3.2 Use statement-level and INSTEAD OF triggers safely
One SQL statement can affect many rows. A statement-level trigger runs once for the whole statement, including a statement that changes no rows. It must process sets of changed rows instead of assuming there is one old row and one new row.
Process every affected row
PostgreSQL defaults to FOR EACH STATEMENT when no level is given. Its OLD and NEW row variables are not populated at statement level. An eligible after trigger can instead declare transition tables, such as REFERENCING NEW TABLE AS new_rows, and query all new rows together.
SQL Server DML triggers are statement-level. The inserted and deleted pseudo-tables hold the new and old row sets. Assigning one identifier from inserted to a scalar variable can lose the other rows. For stock adjustments, first total the quantities by product:
UPDATE p
SET p.stock = p.stock - i.qty
FROM dbo.Products p
JOIN (
SELECT product_id, SUM(quantity) AS qty
FROM inserted
GROUP BY product_id
) i ON i.product_id = p.product_id;
If an insert adds two lines for the same product, both quantities contribute to its reduction. Without grouping, multiple matches do not reliably perform multiple subtractions against one target row. SQL Server supports AFTER and INSTEAD OF timing, but no before DML triggers.
Give a view a custom delete action
An INSTEAD OF trigger replaces the requested action. A soft delete can hide a product while retaining its stored row:
CREATE VIEW current_products AS
SELECT product_id, name, price
FROM products WHERE deleted_at IS NULL;
CREATE FUNCTION hide_product()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
UPDATE products SET deleted_at = now()
WHERE product_id = OLD.product_id;
RETURN OLD;
END;
$$;
CREATE TRIGGER current_products_delete
INSTEAD OF DELETE ON current_products
FOR EACH ROW EXECUTE FUNCTION hide_product();
With four products, deleting product 4 through the view leaves three visible products and four stored rows. The trigger substitutes an update for the physical delete. Granting direct delete access to the base table would let a caller bypass this behavior.
PostgreSQL requires INSTEAD OF triggers to be row-level and attached to views. SQLite also supports them on views. SQL Server allows them on tables or views; MySQL does not support them.
Keep hidden work predictable
A trigger can cause another trigger to run. An after-update trigger that updates its own table can fire itself repeatedly. In PostgreSQL, prevent a loop with conditions that actually stop the repeat, a suitable event-column list, or a deliberate trigger-depth check. SQL Server limits nesting to 32 levels; its recursive-trigger setting also affects direct recursion of after triggers.
Do not rely on portable trigger ordering. PostgreSQL uses alphabetical names for triggers of the same kind; MySQL supports FOLLOWS and PRECEDES; SQL Server can designate first and last after triggers. Independent trigger actions are easier to maintain than chains whose correctness depends on order.
A million-row update runs a row-level trigger a million times. Keep its work short and document it beside the table definition. TRUNCATE does not fire delete triggers; PostgreSQL has a separate truncate event. SQL Server bulk inserts need FIRE_TRIGGERS to run insert triggers. A rule must account for the operations that can reach its table.
Key Takeaways
- Statement-level triggers process a row set and can run when zero rows change.
- Group repeated product keys before a set-based stock update.
- An INSTEAD OF trigger supplies custom write behavior for a view.
- Prevent recursive firing with a condition that stops the repeated action.
- Document trigger work, costs, and operations that bypass the chosen event.
4Control who can do what in a database
Access control connects an identity to a permitted action and a permitted set of data. You will organize privileges through roles, follow schema and object grants, and check rights inherited through several paths. Views and routines can provide narrow interfaces, while row-level policies restrict tenants’ rows. Each layer needs the correct execution context so a convenient administrative account does not bypass the intended boundary.
4.1 Set up users and roles with least privilege
Database security starts with two questions: who connected, and what may that identity do? Authentication checks the identity. Authorization grants or refuses actions on database objects. A successful login does not mean unrestricted access.
Separate people from job privileges
A role groups privileges for a task, such as reporting or order entry. Give that role to people who perform the task. When a person's job changes, role membership can change without rebuilding every object grant.
In PostgreSQL, users and group roles are the same kind of object. A role with LOGIN can connect; a role without it can group privileges:
CREATE ROLE reporting NOLOGIN;
CREATE ROLE mia LOGIN;
GRANT reporting TO mia;
Configure Mia's credential through the deployment's secure credential process. With ordinary default inheritance, Mia can use privileges held by reporting. Membership and object access remain separate: granting a role to Mia does not itself grant that role any table rights.
MySQL identifies an account by name and host. An account such as 'mia'@'%' matches any host, while a specific host narrows where it connects from. MySQL 8 roles must be active before their grants apply:
CREATE ROLE 'reporting';
GRANT 'reporting' TO 'mia'@'%';
SET DEFAULT ROLE 'reporting' TO 'mia'@'%';
The last command sets the role for later logins. In Mia's current session, SET ROLE 'reporting'; activates it immediately. SET ROLE DEFAULT activates the configured defaults. A granted but inactive role explains many apparently missing permissions.
SQL Server separates a server login from a database user mapped to that login. A database role then groups those users:
CREATE USER mia FOR LOGIN mia;
CREATE ROLE reporting;
ALTER ROLE reporting ADD MEMBER mia;
The server login must already exist. Built-in roles such as db_datareader and db_owner are broad: one reads every user table and view; the other gives control across the database. A narrow application task rarely needs that scope.
Keep ownership away from application traffic
An object's owner normally created it and controls its definition. In PostgreSQL, ownership carries alter and drop authority that an ordinary table grant cannot supply. Members able to act as the owner and superusers can also exercise powerful control. An application should not connect as the table owner or a superuser.
For a shop, separate three jobs:
| Role | Needed work |
|---|---|
shop_app | Read products; read, insert, and update orders |
reporting | Read selected summary views |
shop_owner | Own objects and apply schema changes |
This is least privilege: give each account only the rights its work requires. The application need not delete orders or drop tables to serve a product page. If its query path is compromised, a restricted account limits the reachable damage.
Keep identities accountable
Use separate accounts for separate people and applications. Shared credentials make an audit entry hard to attribute and force unrelated services to share one set of powers. Keep credentials in protected configuration or a secrets store, not source code. Remove unused identities and review their memberships; dropping a role may first require resolving the objects it owns and the privileges that depend on it.
Key Takeaways
- Authentication checks identity; authorization controls actions.
- Grant task privileges to roles, then grant membership to the people or applications that need them.
- MySQL role membership needs activation before its privileges apply.
- Separate application connections from schema owners and administrators.
4.2 Grant and revoke privileges
A privilege authorizes an action on an object. GRANT adds it; REVOKE removes a grant. To decide whether access is truly present or gone, trace every route by which the role can receive it.
Grant the whole access path
GRANT USAGE ON SCHEMA shop TO shop_app;
GRANT SELECT ON shop.products TO shop_app;
GRANT SELECT, INSERT, UPDATE ON shop.orders TO shop_app;
The application can look up objects in shop, read products, and create or change orders. It cannot delete an order using these grants. PostgreSQL requires both schema USAGE and the relevant object privilege; a table grant alone does not provide the schema lookup right. CREATE on a schema is different: it permits making objects in that schema.
Table privileges include SELECT, INSERT, UPDATE, DELETE, and REFERENCES; PostgreSQL also has privileges such as TRIGGER and TRUNCATE. Routines use EXECUTE. ALL PRIVILEGES means every applicable privilege on the named object, not ownership of it.
Column grants can narrow a task:
GRANT SELECT (customer_id, name, country_code)
ON shop.customers TO support;
GRANT UPDATE (status) ON shop.orders TO warehouse;
Support can select name, but SELECT * fails if it includes ungranted columns such as email. Warehouse staff can assign a status but cannot change totals through that grant. Queries may also need read privileges on columns they inspect.
Distinguish existing and future objects
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO reporting;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA shop
GRANT SELECT ON TABLES TO reporting;
The first statement covers objects that already exist. The second sets a rule for future tables created by shop_owner. It does not repair old tables or cover tables created by a different role. Use such a broad read grant only if every covered table belongs in the reporting scope.
PUBLIC means every role, including future roles. New PostgreSQL routines grant it EXECUTE by default. Revoke unwanted routine access with the exact signature, for example REVOKE EXECUTE ON FUNCTION shop.refund_order(integer) FROM PUBLIC;. Databases commonly grant PUBLIC CONNECT and TEMPORARY. New schemas have no PUBLIC grants by default, but the built-in public schema has its own defaults. PostgreSQL 15 removed PUBLIC's default CREATE there for new databases; upgraded databases retain existing permissions.
Follow dependent and inherited grants
If Alice gives Bob select access with WITH GRANT OPTION, Bob can grant it to Carol. Revoking Bob's grant can fail because Carol's depends on it. In PostgreSQL, CASCADE removes dependent grants. REVOKE GRANT OPTION FOR SELECT ... FROM bob CASCADE removes Bob's ability to pass on the privilege and dependent grants while preserving his own select privilege.
Removing a direct grant from Mia leaves access obtained through reporting or PUBLIC intact. PostgreSQL has no per-user DENY that subtracts someone from a PUBLIC grant. To exclude one identity while preserving others’ reads, replace the broad grant with grants to an explicit set of intended readers. Check effective table access with has_table_privilege('mia', 'shop.orders', 'SELECT'), and test schema access and real operations under her role too.
MySQL's SHOW GRANTS ... USING 'reporting' expands a granted role's privileges; CURRENT_ROLE() identifies active roles. Grants through GRANT and REVOKE need no FLUSH PRIVILEGES. SQL Server adds DENY, which generally overrides an ordinary permission received through a role; a column-level grant can override a table-level deny, and owners and sysadmin accounts are exempt from ordinary deny checks.
Key Takeaways
- Schema USAGE and object privileges serve different parts of the access path.
- Column grants can allow a narrow query while SELECT * fails.
- Existing-object grants and creator-specific default privileges solve different problems.
- PUBLIC and inherited role grants contribute to effective access.
- Revoking grant option can preserve personal access while removing dependent onward grants.
- Check actual operations as the intended role after changing permissions.
4.3 Expose data safely through views and routines
A view can expose selected data, and a routine can expose a selected action. Their security value depends on whose privileges run the underlying work and whether callers have a broader route to the tables.
Expose a limited directory
CREATE VIEW shop.customer_directory
WITH (security_barrier = true) AS
SELECT customer_id, name, country_code
FROM shop.customers
WHERE is_active;
GRANT USAGE ON SCHEMA shop TO support;
GRANT SELECT ON shop.customer_directory TO support;
Support staff can read active customers' directory fields. They receive no select right on shop.customers from this view grant. Keep direct and inherited base-table access out of the support role, or staff can bypass the directory and read hidden columns.
By default, PostgreSQL checks underlying table privileges using the view owner's rights. MySQL's default SQL SECURITY DEFINER gives a similar result. SQL Server can follow an ownership chain when the view and its tables have the same owner.
PostgreSQL 15 and later also support WITH (security_invoker = true). An invoker view uses the caller's base-table privileges and RLS context. It is useful as a query interface when callers should keep their own access restrictions. It does not confer the owner's table rights.
The security_barrier option serves a different purpose. It keeps a security view's filter ahead of user-supplied functions that could leak excluded values. For example, an outer function that reports every value it receives must not inspect hidden rows before the filter removes them. Invoker rights and barrier behavior are separate choices.
Expose a checked action
PostgreSQL functions and procedures normally run as SECURITY INVOKER. A SECURITY DEFINER routine instead uses its owner's privileges. A teller can receive only the right to execute a checked transfer while having no direct update access to accounts.
For a transfer routine in a trusted bank schema, its definition can include:
SECURITY DEFINER
SET search_path = bank, pg_temp
The trusted schema must not allow callers to create objects in it. Put pg_temp last so a caller's temporary objects cannot take precedence over trusted relations. Qualify sensitive object names too. A definer routine must still validate the amount, accounts, balance, and any caller-specific action restrictions; owner rights do not make its inputs trustworthy.
Create and restrict the routine in one transaction:
REVOKE EXECUTE ON PROCEDURE bank.transfer(integer, integer, numeric)
FROM PUBLIC;
GRANT EXECUTE ON PROCEDURE bank.transfer(integer, integer, numeric)
TO teller;
The surrounding creation transaction prevents a period in which PUBLIC could call the newly created routine. Tellers also need schema usage, but receive no direct account update grant. They can perform only the actions the routine deliberately permits.
Account for dialect defaults
MySQL routines default to definer rights, and its triggers always use the definer context. SQL Server procedures can use ownership chaining for static SQL or an explicit EXECUTE AS context. Dynamic SQL breaks the normal ownership chain and checks its objects in the current execution context. Keep elevated routines small and use bound values for dynamic SQL; concatenation inside a powerful routine would let unsafe input act with that power.
Key Takeaways
- Grant a protective interface without also granting access that bypasses it.
- PostgreSQL views default to owner table rights; routines default to caller rights.
- security_invoker selects caller rights; security_barrier protects filter ordering.
- A SECURITY DEFINER routine needs a trusted search path, restricted EXECUTE, and checked inputs.
- Dynamic SQL and each product’s execution context affect permission checks.
4.4 Restrict rows with row-level security
Row-level security (RLS) adds database-enforced rules about which rows an authorized role may read or change. A table grant still decides whether the role may use the table. The policy narrows the rows available to that permitted operation.
Filter an existing row and check a new row
ALTER TABLE tickets ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON tickets
USING (
tenant_id = current_setting('app.tenant_id', true)::integer
)
WITH CHECK (
tenant_id = current_setting('app.tenant_id', true)::integer
);
USING selects existing rows for reads, updates, and deletes. Rows that fail it are silently excluded. WITH CHECK tests rows produced by inserts and updates; a failing new row raises an error. With an all-command or update policy that omits a check expression, PostgreSQL reuses USING for the new-row check.
Tickets 1, 2, and 4 belong to tenant 7; tickets 3 and 5 belong to tenant 9. For an ordinary application role with tenant context 7, a count returns 3. Updating ticket 3 changes 0 rows because it is hidden. Inserting a new ticket for tenant 9 fails. Changing a visible ticket's tenant from 7 to 9 also fails the new-row check.
Combine policies without opening a gap
Policies may target a command and named roles. Applicable permissive policies combine with OR, so another permissive policy can widen access. Restrictive policies combine with AND and further narrow the permissive result. A restrictive policy alone does not create permission: there must be a permissive path as well.
Enabling RLS without an applicable policy denies normal row access. RLS does not govern whole-table actions such as TRUNCATE; their privileges must be controlled separately.
PostgreSQL superusers and roles with BYPASSRLS bypass policies. Owners normally bypass them too; ALTER TABLE tickets FORCE ROW LEVEL SECURITY; subjects the owner to policies, but does not remove superuser or bypass-role exemptions. Test with the ordinary application role, not an administrative connection.
Keep tenant context trustworthy
With a connection pool, a session setting can outlive the request that set it. Give each request's transaction its own context:
BEGIN;
SET LOCAL app.tenant_id = '7';
SELECT ticket_id, title FROM tickets;
COMMIT;
The local setting ends with the transaction. The policy uses current_setting(..., true) so an unset value returns NULL; no tenant comparison becomes true. The form without true raises an error when the setting is absent. Both avoid silently choosing another tenant.
A custom setting is not authentication. A client able to issue arbitrary SQL can change it. This design depends on a trusted application choosing the tenant after authenticating the request, with callers unable to control the database session directly. Parameters and least privilege still matter.
Recognize product differences and limits
SQL Server uses an inline table-valued function in a security policy. Filter predicates hide rows; block predicates reject writes. Its RLS policy applies even to dbo. MySQL has no built-in RLS; a restricted definer view can filter using a trusted identity mapping. Inside that view, CURRENT_USER() identifies the definer, so a client-identity mapping uses USER() instead.
Unique and foreign-key checks can reveal hidden-row existence through errors. RLS controls row access, not every possible information signal. Index the tenant column used in frequent policy filters so the added condition can be served efficiently.
Key Takeaways
- Table privileges authorize operations; RLS narrows their rows.
- USING hides existing rows; WITH CHECK rejects invalid new row states.
- Permissive policies combine with OR, and restrictive policies narrow with AND.
- Test using an ordinary role and account for owner and administrator bypass.
- Use transaction-local trusted tenant context with pooled connections.
- RLS does not filter TRUNCATE or eliminate information from integrity-check errors.
5Prevent SQL injection
Injection prevention starts at the point where a program turns input into an SQL statement. You will trace how concatenation changes a predicate, replace it with separately bound values, and handle structural choices such as report columns through controlled mappings. The same rules apply inside routines and to values read back from storage. Validation and restricted privileges then protect different parts of the system.
5.1 Explain how SQL injection works
SQL injection happens when untrusted input changes a statement's structure. The vulnerable boundary is the construction of SQL text: a value intended as data becomes syntax that the database executes.
Trace the change in meaning
A search builds its SQL by concatenation:
sql = "SELECT customer_id, name FROM customers WHERE email = '" + email + "'"
For ana@example.com, the value fits inside the intended text literal. For the input x' OR '1'='1, the resulting SQL is:
SELECT customer_id, name FROM customers
WHERE email = 'x' OR '1'='1';
The inserted quote ends the email literal. The OR adds a condition that is true for every row, so all four customers are returned. The problem is not that the email is unusual; the program allowed the input to define part of the SQL grammar.
Comments can remove a later condition. In a concatenated login query, a name such as admin' -- can end the username value and comment out the password comparison. PostgreSQL, SQL Server, and SQLite recognize -- as a line comment; MySQL requires following whitespace for that comment form. A different comment rule changes the crafted input, not the underlying vulnerability.
Recognize other vulnerable forms
A numeric field can be injected without any quote. If the program appends an identifier to WHERE order_id = , input such as 0 OR 1=1 changes the condition. Escaping apostrophes cannot protect this unquoted position.
A union can append results from another accessible table. A search selecting two text columns, name, email, could be altered to union two compatible text columns from a staff table. The combined queries must have the same number of columns and compatible types. A PostgreSQL integer output column does not automatically accept a staff username. These requirements limit a particular input but do not make string construction safe.
Refusing multiple statements in one library call only prevents stacked statements. Python's sqlite3.execute() rejects several statements at once, yet a single altered predicate or union still changes one statement's meaning.
Follow data beyond the first insert
Second-order injection starts with a value stored safely and used unsafely later. A parameterized registration insert can store a name containing a quote and comment marker. If a later account-maintenance routine concatenates that stored name into an update, the data again crosses into SQL syntax. Reading a value from your own database does not make it safe to interpolate.
Blind injection reveals information through observable behavior without returning the requested rows directly. A true-or-false condition may alter a page, produce an error, or change response timing. Hiding detailed errors reduces exposed information, but leaves a vulnerable SQL construction path intact.
Inputs include form fields, URL parameters, headers, uploaded data, API values, and stored values from earlier operations. The database account's privileges limit what an altered statement can reach. A highly privileged application account expands the possible damage from one query path to unrelated tables or schema operations. Fix the code/data boundary and restrict the account's reach.
Key Takeaways
- Injection occurs when input changes SQL structure during text construction.
- Quoted strings and unquoted numeric positions can both be vulnerable.
- Single-statement restrictions do not prevent an altered predicate or union.
- Safely stored data can cause second-order injection when later concatenated.
- Blind injection uses behavior or timing, so hidden results do not repair the flaw.
5.2 Write parameterized queries
A parameterized query keeps SQL structure separate from values. Write the statement with placeholders, then pass the values through the library's parameter argument. The library handles their types and representation as data.
Bind a value separately
Python's sqlite3 uses a question-mark placeholder:
cur.execute(
"SELECT customer_id, name FROM customers WHERE email = ?",
(email,)
)
The comma makes (email,) a one-item tuple. Without it, (email) is just the original string. If the value is x' OR '1'='1, the database searches for that exact email text. It does not add an OR condition. An ordinary name such as Liam O'Brien also stays a single value without a syntax error.
Do not put quotes around the placeholder. WHERE name = '?' contains a literal question mark, not the value position the library should fill. Formatting a value into SQL before calling execute() is also unsafe:
# Unsafe: formatting already put the value inside SQL text.
cur.execute("SELECT * FROM customers WHERE email = '%s'" % email)
Preparation cannot repair a statement whose structure was already changed by interpolation.
Match the library's placeholder style
| Library | Value placeholder | Binding approach |
|---|---|---|
Python sqlite3 | ? or :name | Separate sequence or mapping |
Python psycopg | %s or %(name)s | Separate sequence or mapping |
Node.js pg | $1, $2 | Separate values array |
| Java JDBC | ? | Typed setters such as setString |
.NET SqlCommand | @email | Named parameter objects |
| PHP PDO | ? or :email | Bound or separately supplied values |
In psycopg, %s is a library placeholder even for a numeric value; Python's % string-formatting operator must not fill it. In Node.js pg, client.query('SELECT name FROM customers WHERE email = $1', [email]) separates the value array from the SQL string.
Bind patterns and collections correctly
For a substring search, bind the whole pattern:
cur.execute("SELECT name FROM products WHERE name LIKE ?", ("%tea%",))
The wildcards belong in the value, not around a quoted placeholder. Parameterization prevents SQL injection, but % and _ inside a pattern still have their ordinary matching meaning. If a user should search for a literal percent sign, escape it according to the chosen LIKE escape convention before binding the pattern.
For a list, use one placeholder per item and supply the corresponding values. IN (?, ?, ?) expects three values; one string containing commas is still one string. PostgreSQL can instead bind an array to WHERE order_id = ANY($1).
Keep identifiers out of value parameters
A placeholder cannot stand for a table name, column name, operator, keyword, or clause. Binding a chosen column name to ORDER BY ? supplies a constant value, not the identifier to sort by. Choose identifiers and directions from a program-owned allow-list, then bind any remaining values.
SQL-level PREPARE and EXECUTE offer the same separation, with each product's syntax. ORMs commonly bind their normal query values, but raw SQL still needs explicit safe binding. Reusing prepared statements may save planning work; their security benefit comes from preserving the boundary between code and data.
Key Takeaways
- Pass values through the parameter argument; do not format them into SQL first.
- Leave placeholders unquoted and use the library’s correct style.
- LIKE patterns and list values still need the right shape after binding.
- Parameters represent values, so identifiers and keywords need a separate allow-list.
- Raw SQL in an ORM must preserve the same code/data separation.
5.3 Secure dynamic SQL and add defense in depth
Dynamic SQL is SQL constructed as text and then executed. Some tasks need it, such as choosing a report column. It needs the same code/data separation as application queries, including when the construction happens inside a stored routine.
Bind values in dynamic statements
A PostgreSQL routine can use EXECUTE ... USING:
EXECUTE 'SELECT count(*) FROM orders WHERE status = $1'
INTO v_count USING p_status;
The status remains a value. Concatenating p_status between quote characters would instead let it change the statement. A stored procedure is safe through its value parameters only when it uses them safely in every statement it builds.
When a table name genuinely varies, choose it from an allow-list and quote it as an identifier:
IF p_table IS NULL OR p_table NOT IN ('orders', 'archived_orders') THEN
RAISE EXCEPTION 'Unsupported report table';
END IF;
EXECUTE format(
'SELECT count(*) FROM shop.%I WHERE status = $1', p_table
) INTO v_count USING p_status;
%I handles one identifier; the fixed shop schema is separate. %L can quote a literal, but binding values keeps their role clearer. Identifier quoting prevents a name from becoming several SQL tokens. The allow-list also limits which legitimate objects the caller may choose.
SQL Server uses parameterized sp_executesql:
EXEC sp_executesql
N'SELECT COUNT(*) FROM dbo.Orders WHERE Status = @s',
N'@s nvarchar(20)', @s = @Status;
QUOTENAME quotes a SQL Server identifier. Dynamic SQL does not use ordinary ownership chaining; its table permissions are checked in the current execution context, which is the caller's unless changed with EXECUTE AS. MySQL procedures can prepare text containing ? placeholders and execute it with separately supplied values.
Map choices to fixed SQL
For sorting, keep the permitted fragments in the program:
sort_columns = {'name': 'name', 'date': 'order_date', 'total': 'total'}
directions = {'asc': 'ASC', 'desc': 'DESC'}
column = sort_columns[sort_key]
direction = directions[direction_key]
order_clause = f"ORDER BY {column} {direction}"
Reject unknown keys before using the mapped fragments. A request for total descending produces ORDER BY total DESC; text that is not a map key never enters the SQL. Interpolation here uses only the program's own constants. Search text, dates, and amounts elsewhere in the statement still travel as bound values.
Add controls with distinct jobs
Validation checks type, length, format, and range. Converting an order identifier to an integer rejects text that is not an integer; it does not replace parameter binding for the query. Real names contain apostrophes, so banning quotes would reject valid users while missing unquoted injection paths.
Hand-written escaping is fragile because quote rules vary by product and settings, and one omitted call reopens the flaw. Use binding for values and approved identifier-quoting tools for allowed names.
Least privilege limits reachable tables and actions after any remaining flaw. Keep applications away from owner and superuser identities, and expose only necessary views or routine execution rights. Return a generic failure to the user and record database details in protected server logs. Review both application and routine code wherever a variable is inserted into SQL text: each value needs binding, and each structural choice needs a controlled mapping.
Key Takeaways
- Stored procedures need safe dynamic SQL just as applications do.
- Bind dynamic values and quote allowed identifiers with the product’s identifier tool.
- An allow-list limits legitimate structural choices as well as blocking injected syntax.
- Validation, least privilege, and careful errors add distinct layers of protection.
- Never replace parameter binding with hand-written escaping.
SQL Views and Stored Procedures examples
1Build a report interface and choose its freshness
14 steps
- 1IntroductionStart with the report’s promise
A sales report needs two promises: what counts as a sale, and how current its numbers are. A view can keep the canceled-order rule in one place. A materialized view can save the result when repeated aggregation is expensive.
Follow a live customer report first. Then try a write through a filtered view and decide whether an hourly dashboard can use stored results.
- 2ExplanationName the shared query
A plain view saves a query definition. Its base tables keep the actual order rows. The view can be selected, filtered, or joined like a table, without storing a separate report copy.
The shop’s
customer_order_totalsgroups qualifying orders by customer and names its outputsorder_countandtotal_spent. Those aliases become the interface other queries use. - 3ExampleTrace which orders survive
The view uses an inner join and excludes canceled orders. Ana’s 40.00 and 25.50 both survive, so her result is 2 orders and 65.50. Ben’s 120.00 and 9.75 give 2 and 129.75.
Chen has only a canceled order. No joined row for Chen survives, so there is no customer group to display. A count of zero requires a different join design; it does not appear automatically.
- 4ExampleRead and order the result
The reading query chooses the report order:
SELECT name, total_spent FROM customer_order_totals WHERE total_spent > 50 ORDER BY total_spent DESC;Ben appears before Ana. Dana’s initial 15.25 does not pass the filter. The outer
ORDER BYprovides the guarantee; relying on an order written inside the view does not guarantee the caller’s output order. - 5ChallengeKeep customers with no orders
A membership report must retain people with no accepted submissions. Where should the accepted-status test go in a left join, and what should it count?
---reveal---
Put the status test in the join’s
ONcondition and count the submission key. The unmatched member remains, but that key is NULL, so its count is zero. A status test inWHEREwould remove the unmatched member;COUNT(*)would count its placeholder row. - 6TipPreserve a usable interface
List a view’s columns explicitly. PostgreSQL and MySQL expand a star when the view is created, so adding a table column later does not extend that saved interface.
PostgreSQL replacement keeps existing column names, types, and order and can append columns. Renaming uses
ALTER VIEW ... RENAME COLUMN. Rebuilding a changed interface also means accounting for objects that depend on it. - 7ExplanationFind the stored value behind a write
A simple view over one table can forward writes when the database can identify the base row. A plain column reference such as
totalhas a destination; a grouped sum over several orders does not identify which stored order should change.The shop’s
paid_ordersview selects order columns where the status is paid. Updating its total changes the matching row inorders, not a second copy. - 8ExampleAdd a rule for the new state
Without a check option, changing a paid order’s status to shipped succeeds and makes the row disappear from
paid_orders. Its old state was visible, so the update could target it.Adding
WITH CHECK OPTIONchanges the test: the produced row must still pass the paid filter. The same status update now fails, and the old row remains unchanged. The check is on the write through this view. - 9ChallengeSeparate a view write from a table write
A paid-only view has a check option. An authorized caller changes a paid order to shipped directly through
orders. Does the view’s check option reject this write?---reveal---
No. The view’s check option controls writes through that view. The table update uses a separate access path, so the row can become shipped and disappear from the view. To require a restricted interface, also remove permissions that bypass it.
- 10ExplanationSave the report result
A materialized view keeps query-result rows. The monthly report can read a small stored aggregate without regrouping all orders each time.
The saved April result is 1 order and 9.75. Inserting an April order of 30.00 does not change that stored row immediately. A plain view would read the new visible source data; the materialized view waits for its next refresh.
- 11ExampleRefresh with readers in mind
REFRESH MATERIALIZED VIEW monthly_sales;replaces the stored result. April now shows 2 orders and 39.75.A normal refresh blocks reads while it runs. For
CONCURRENTLY, first have populated data and a unique index on columns identifying every result row, such asmonth. A partial index cannot qualify because it does not include all rows. The application or a job must schedule the refresh. - 12ChallengeChoose the right stored result
An aggregate dashboard is expensive to compute, is read repeatedly, and may be up to one hour old. What view design and maintenance fit those requirements?
---reveal---
Use a materialized view with an hourly refresh plan. If reads must continue during refresh, prepare a qualifying unique index and use concurrent refresh after initial population. A plain view stays tied to visible source data but does not itself avoid repeating the aggregation work.
- 13ChallengeCombine freshness and write rules
A team wants hourly stored totals but also wants staff to correct individual paid orders. Should staff update the aggregate result to make that correction?
---reveal---
No. Change the identified base order, directly or through an eligible checked paid-orders view, then refresh the stored report. An aggregate does not identify one stored order value, and PostgreSQL materialized views do not accept ordinary result-row updates.
- 14RecapChoose from the required behavior
For a reusable live query, choose a plain view. For a stored expensive report, choose a materialized view and a refresh plan. For a write interface, identify the base rows and decide whether changed rows must stay inside its filter.
Before changing a view’s columns or dropping its tables, inspect dependencies. Before promising a sorted report, put the sorting in the query that returns it.
2Make a routine succeed or fail as one task
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDefine what completion means
- 2ExampleReturn one calculation
- 3ExplanationChoose result shape and stability
- 4ChallengeLet a missing discount use its default
- 5ExplanationValidate before moving value
- 6ExampleFollow the successful balance changes
- 7ExampleDetect the silent missing destination
- 8ChallengeTrace a rejected transfer
- 9TipChoose a set operation when rows are independent
- 10ExplanationGive errors a deliberate route
- 11ExampleTranslate the transaction protection
- 12ChallengeRepair a misleading handler
- 13ConnectionKeep client commands outside routine logic
- 14ChallengeNotice a permanent earlier change
- 15RecapInspect the routine’s contract
3Follow automatic changes from row to row set
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLocate the automatic work
- 2ExampleClean an email before storage
- 3ExplanationRead the correct row version
- 4ExampleAudit three price changes
- 5ChallengeChoose a constraint or a trigger
- 6ExplanationTreat a statement as a set
- 7ExampleGroup quantities before updating stock
- 8ExampleReplace deletion with a marker
- 9ChallengePredict both counts
- 10TipStop work from triggering itself forever
- 11ChallengeChoose an audit that survives rollback correctly
- 12RecapReview the event boundary
4Build and test a narrow access path
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk who, which action, and which rows
- 2ExplanationSeparate the account from its task role
- 3ExampleReserve ownership for schema work
- 4ChallengeActivate the role you granted
- 5ExampleGrant schema lookup and object access
- 6ExplanationFollow every route to effective access
- 7ChallengeRemove access without affecting the team
- 8ExplanationChoose whose table rights a view uses
- 9ExampleOffer a checked action with owner rights
- 10ChallengeFind the route around a directory
- 11ExplanationEnable tenant row policies
- 12ExampleCheck a visible row’s replacement state
- 13Key InsightKnow which policies widen access
- 14TipTest with the account that will use the data
- 15ChallengePredict three different row outcomes
- 16ConnectionKeep context within its trust boundary
- 17ChallengeReview two independent escape routes
- 18RecapTest the full permitted path
5Repair SQL construction from input to execution
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFind where data becomes query text
- 2ExampleRead the constructed statement
- 3ExplanationFollow other input paths
- 4ChallengeFind the unsafe step in stored-data reuse
- 5ExamplePass the value separately
- 6Key InsightPreparing after interpolation is too late
- 7ExampleBind a pattern or list with the right shape
- 8ChallengeKeep search data distinct from a sort column
- 9ExplanationControl the fragments that must vary
- 10ExampleBind inside a PostgreSQL routine too
- 11ChallengeDistinguish quoting from permission
- 12ConnectionAdd layers with different jobs
- 13ChallengeReview a repaired report end to end
- 14RecapInspect each construction boundary
SQL Views and Stored Procedures practice questions
Set 1: Practice 1: Follow the database operation10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
job_id, status from one table, filters for status = 'open', and ends with WITH CHECK OPTION. Job 82 is open. What happens to UPDATE open_jobs SET status = 'closed' WHERE job_id = 82;?Show answerHide answer
Question 3 of 10
Show answerHide answer
STABLE allows the function to read table data while promising consistency within a statement. IMMUTABLE would promise the same answer beyond that statement, even after the reference data changes. STRICT describes NULL arguments, not how table reads affect result stability.Question 4 of 10
FOUND, raises an uncaught exception, and never commits internally. What happens to the withdrawal?Show answerHide answer
FOUND check changes the outcome.Question 5 of 10
WHEN (OLD.price IS DISTINCT FROM NEW.price). How many audit rows does its one-insert body write?Show answerHide answer
IS DISTINCT FROM includes the NULL-to-value transition. Counting only four would apply the NULL behavior of <>, while counting eight would ignore the condition entirely.Question 6 of 10
(product_id, quantity) of (11, 2), (11, 3), and (12, 4). What stock reductions should a set-based trigger apply?Show answerHide answer
inserted by product gives 5 and 4. Taking a single row from inserted loses part of the statement. Summing all lines without grouping would incorrectly apply the combined quantity to each product.Question 7 of 10
Show answerHide answer
Question 8 of 10
analytics.results but no USAGE on schema analytics. It has no other access paths. What additional grant permits a simple SELECT from that table?Show answerHide answer
USAGE supplies the missing step. CREATE allows making new schema objects, so it does not substitute for schema lookup or address the stated failure.Question 9 of 10
WHERE parcel_id = . Why does rejecting multiple statements leave this query vulnerable?Show answerHide answer
Question 10 of 10
name or created_at and search names safely. How should it construct the query?Show answerHide answer
LIKE pattern must be bound separately. Binding a sort column as a value does not turn that value into a column reference, even though the search binding is safe.Set 2: Practice 2: Diagnose a failed assumption10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
SELECT * FROM devices exposes device_id, label. A serial_code column is later added to the table. What does a subsequent SELECT from the unchanged view expose?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
IF v_balance < p_amount, then deposits into an existing destination. Why can this create an incorrect balance?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
REVOKE GRANT OPTION FOR SELECT ON reports FROM leo CASCADE;. What access remains?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
%I to quote a table name supplied by the caller, and binds every filter value. The owner can read sensitive and public tables. How should the routine also limit the caller’s choice?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
WHERE tag = ?. The tag value is the string green,blue. How does binding that one value affect an equality comparison?Show answerHide answer
Save this lesson to see this answer.
Set 3: Practice 3: Choose a safe design10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
region = 'east' without a check option. An automatically updatable view over it filters active = true with LOCAL CHECK OPTION. A visible row is updated through the upper view to region west while staying active. What happens?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
report_day with WHERE total > 0. Why does this index not permit concurrent refresh?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
deleted_at is non-NULL. Its INSTEAD OF DELETE trigger sets that timestamp. Five rows exist, all initially visible. A DELETE through the view targets two rows. What are the resulting visible and stored row counts?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
(id, tenant_id, active): (31, 7, true), (32, 7, false), (33, 9, true), (34, 9, false). An ordinary role has SELECT, two permissive policies (tenant 7 and all rows), and a restrictive active-only policy. Which ticket IDs can it read?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Practice 4: Trace interacting rules10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
category_id column. The base column is NOT NULL and has no default. An insert supplies every column exposed by the view. Why does it fail?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
price = price on four rows. Its body inserts one history row on each firing. How many history rows result?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
sales to an analyst role. Later, a deployment role creates a new table there, and the analyst cannot read it. How should both current and future access be fixed for that creator?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Practice 5: Review a database security design10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
(site_id, day), with several days for each site. What preparation supports concurrent refresh?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
WHERE record_id = ANY($1). The application has three integer identifiers to search for. What should it supply as that parameter value?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
(id, tenant_id, active) of (51, 4, true), (52, 4, false), (53, 8, true). Its ordinary owner has no BYPASSRLS or superuser status. A permissive tenant-4 policy and restrictive active-only policy apply. After FORCE ROW LEVEL SECURITY, which IDs can the owner read?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
AFTER trigger
Allow-list
Audit trail
Authentication
Authorization
B
Base table
Batch separator
GO between routine definitions.BEFORE trigger
Blind injection
Bound value
C
Cascaded check option
Check option
Column alias
order_count identifies the aggregate that a report can select and filter.Common table expression
Computed column
Concurrent refresh
D
Default privileges
Defense in depth
Definer rights
Dependency
orders can block dropping that table in PostgreSQL.Dollar quoting
Dynamic SQL
E
Effective privileges
Exception
Exception handler
G
Grant option
I
Identifier quoting
Indexed view
INOUT parameter
Input parameter
Input validation
INSTEAD OF trigger
Invoker rights
L
Least privilege
LIKE wildcard
Local check option
M
Materialized view
O
Object owner
OLD and NEW
Output parameter
Ownership chaining
P
Parameterized query
Permissive policy
Placeholder
? in sqlite3 remains unquoted and receives a separately supplied value.Prepared statement
Privilege
PUBLIC
R
Refresh
Restrictive policy
Rethrow
Role
Row lock
Row-level security
Row-level trigger
S
Scalar function
Schema USAGE
Search path
Second-order injection
Security barrier
Set-based operation
Soft delete
SQL injection
Statement-level trigger
Stored procedure
Stored routine
Strict function
T
Table function
Tautology
Tenant context
Transition table
new_rows lets a trigger aggregate newly inserted quantities.Trigger
Trigger recursion
U
Updatable view
USING policy expression
V
View
Volatility label
STABLE permits a lookup function to read tables within a statement.W
WITH CHECK policy expression
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.