SQL Views and Stored Procedures: Database Security

Learn to build the parts of a database that sit between raw tables and the people who use them. Create views and materialized views, write stored functions, procedures and triggers, and control access with users, roles, GRANT and REVOKE, and row-level security. Finish by preventing SQL injection with parameterized queries, safe dynamic SQL and least privilege. Examples use PostgreSQL, with notes on MySQL and SQL Server.

IntermediateLesson 7 of 8 in Database Design and Advanced SQL Course

What you will learn

  1. Package queries under a name with views, change data through simple views safely, and store expensive results with materialized views.
    • Create, query and manage views
      Write 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 views
      Decide 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 views
      Create and refresh materialized views, judge when stored results are worth being slightly out of date, and compare how database systems support them.
  2. 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 functions
      Create 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 flow
      Create 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 dialects
      Raise 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.
  3. 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 NEW
      Create 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 safely
      Handle statement-level triggers and their multi-row data, make views writable with INSTEAD OF triggers, and avoid hidden, recursive or slow trigger logic.
  4. 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 privilege
      Create 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 privileges
      Use 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 routines
      Give 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 security
      Write row-level security policies that limit which rows each user or tenant can see and change, and close the common gaps.
  5. 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 works
      Recognize code that builds SQL from untrusted input, trace how crafted input changes the statement, and describe what attackers can gain.
    • Write parameterized queries
      Send 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 depth
      Keep 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.

SQL Views and Stored Procedures study guide

5 chapters

1

Build 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
ChoiceWhat a read usesWhat follows a base-table change
Plain PostgreSQL viewThe saved query over visible table dataThe next query sees data according to its snapshot
PostgreSQL materialized viewStored result rowsA later refresh updates the result
SQL Server indexed viewStored indexed resultEligible 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.
2

Write 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:

LabelPromiseExample
IMMUTABLEThe same arguments always give the same resultThe discount calculation
STABLEThe same arguments give the same result within one statement; no data changesReading a customer's orders
VOLATILEResults or database state may change between callsRandom 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
DatabaseRaise an application errorPass the current error on
PostgreSQLRAISE EXCEPTION 'Insufficient funds';RAISE;
SQL ServerTHROW 50001, 'Insufficient funds', 1;THROW;
MySQLSIGNAL 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.
3

Automate 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
EventOLDNEW
InsertNo previous rowThe incoming row
UpdateValues before the updateValues after the update
DeleteThe row being removedNo 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.
4

Control 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:

RoleNeeded work
shop_appRead products; read, insert, and update orders
reportingRead selected summary views
shop_ownerOwn 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.
5

Prevent 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
LibraryValue placeholderBinding approach
Python sqlite3? or :nameSeparate sequence or mapping
Python psycopg%s or %(name)sSeparate sequence or mapping
Node.js pg$1, $2Separate values array
Java JDBC?Typed setters such as setString
.NET SqlCommand@emailNamed parameter objects
PHP PDO? or :emailBound 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

5 Walkthroughs

1

Build a report interface and choose its freshness

14 steps
Follow a customer report from live view to checked writes and stored aggregates.
  1. 1
    IntroductionStart 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.

  2. 2
    ExplanationName 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_totals groups qualifying orders by customer and names its outputs order_count and total_spent. Those aliases become the interface other queries use.

  3. 3
    ExampleTrace 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.

  4. 4
    ExampleRead 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 BY provides the guarantee; relying on an order written inside the view does not guarantee the caller’s output order.

  5. 5
    ChallengeKeep 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 ON condition and count the submission key. The unmatched member remains, but that key is NULL, so its count is zero. A status test in WHERE would remove the unmatched member; COUNT(*) would count its placeholder row.

  6. 6
    TipPreserve 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.

  7. 7
    ExplanationFind 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 total has a destination; a grouped sum over several orders does not identify which stored order should change.

    The shop’s paid_orders view selects order columns where the status is paid. Updating its total changes the matching row in orders, not a second copy.

  8. 8
    ExampleAdd 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 OPTION changes 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.

  9. 9
    ChallengeSeparate 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.

  10. 10
    ExplanationSave 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.

  11. 11
    ExampleRefresh 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 as month. A partial index cannot qualify because it does not include all rows. The application or a job must schedule the refresh.

  12. 12
    ChallengeChoose 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.

  13. 13
    ChallengeCombine 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.

  14. 14
    RecapChoose 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.

2

Make a routine succeed or fail as one task

15 steps
Work through a discount function and a checked transfer, including missing-row and error paths.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDefine what completion means
  2. 2
    ExampleReturn one calculation
  3. 3
    ExplanationChoose result shape and stability
  4. 4
    ChallengeLet a missing discount use its default
  5. 5
    ExplanationValidate before moving value
  6. 6
    ExampleFollow the successful balance changes
  7. 7
    ExampleDetect the silent missing destination
  8. 8
    ChallengeTrace a rejected transfer
  9. 9
    TipChoose a set operation when rows are independent
  10. 10
    ExplanationGive errors a deliberate route
  11. 11
    ExampleTranslate the transaction protection
  12. 12
    ChallengeRepair a misleading handler
  13. 13
    ConnectionKeep client commands outside routine logic
  14. 14
    ChallengeNotice a permanent earlier change
  15. 15
    RecapInspect the routine’s contract
3

Follow automatic changes from row to row set

12 steps
Use cleanup, auditing, and soft deletion to reason about trigger timing and multi-row behavior.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLocate the automatic work
  2. 2
    ExampleClean an email before storage
  3. 3
    ExplanationRead the correct row version
  4. 4
    ExampleAudit three price changes
  5. 5
    ChallengeChoose a constraint or a trigger
  6. 6
    ExplanationTreat a statement as a set
  7. 7
    ExampleGroup quantities before updating stock
  8. 8
    ExampleReplace deletion with a marker
  9. 9
    ChallengePredict both counts
  10. 10
    TipStop work from triggering itself forever
  11. 11
    ChallengeChoose an audit that survives rollback correctly
  12. 12
    RecapReview the event boundary
4

Build and test a narrow access path

18 steps
Trace a support account through roles, object grants, restricted interfaces, and tenant policies.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk who, which action, and which rows
  2. 2
    ExplanationSeparate the account from its task role
  3. 3
    ExampleReserve ownership for schema work
  4. 4
    ChallengeActivate the role you granted
  5. 5
    ExampleGrant schema lookup and object access
  6. 6
    ExplanationFollow every route to effective access
  7. 7
    ChallengeRemove access without affecting the team
  8. 8
    ExplanationChoose whose table rights a view uses
  9. 9
    ExampleOffer a checked action with owner rights
  10. 10
    ChallengeFind the route around a directory
  11. 11
    ExplanationEnable tenant row policies
  12. 12
    ExampleCheck a visible row’s replacement state
  13. 13
    Key InsightKnow which policies widen access
  14. 14
    TipTest with the account that will use the data
  15. 15
    ChallengePredict three different row outcomes
  16. 16
    ConnectionKeep context within its trust boundary
  17. 17
    ChallengeReview two independent escape routes
  18. 18
    RecapTest the full permitted path
5

Repair SQL construction from input to execution

14 steps
Trace an unsafe search, bind values, and control structural choices in application code and routines.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFind where data becomes query text
  2. 2
    ExampleRead the constructed statement
  3. 3
    ExplanationFollow other input paths
  4. 4
    ChallengeFind the unsafe step in stored-data reuse
  5. 5
    ExamplePass the value separately
  6. 6
    Key InsightPreparing after interpolation is too late
  7. 7
    ExampleBind a pattern or list with the right shape
  8. 8
    ChallengeKeep search data distinct from a sort column
  9. 9
    ExplanationControl the fragments that must vary
  10. 10
    ExampleBind inside a PostgreSQL routine too
  11. 11
    ChallengeDistinguish quoting from permission
  12. 12
    ConnectionAdd layers with different jobs
  13. 13
    ChallengeReview a repaired report end to end
  14. 14
    RecapInspect each construction boundary

SQL Views and Stored Procedures practice questions

50 Practice Questions in 5 sets

Set 1: Practice 1: Follow the database operation10 Practice Questions

Question 1 of 10

A plain view lists open service requests. A committed request is closed, and a new statement reads the view with a snapshot that includes this change. What happens to that request in the result?
  1. It stays until a refresh replaces the view’s stored result rows.
  2. It stays until the view is dropped and created with the new data.
  3. It is absent because it no longer meets the saved query’s filter.
  4. It is absent only if the closing statement also updates the view.
Show answerHide answer
Answer: C
A plain view executes its saved query against the data visible to the reading statement. The closed request fails its filter, so it is absent. Waiting for a refresh confuses a plain view with a materialized view, which stores result rows between refreshes.

Question 2 of 10

A PostgreSQL view selects 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;?
  1. The update succeeds and job 82 leaves the view.
  2. The update fails and job 82 remains open.
  3. The update changes only the view’s copy.
  4. The update succeeds but changes zero rows.
Show answerHide answer
Answer: B
The view can target job 82 because its existing state is open, but the new closed state fails the check option. PostgreSQL rejects the update and leaves the row unchanged. Disappearing from the view would be possible without the check option; it is not the result here.

Question 3 of 10

A PostgreSQL function reads a reference table, never changes data, and gives consistent results for the same arguments within one statement. Which volatility label permits table changes between statements without promising permanent results?
  1. STABLE
  2. IMMUTABLE
  3. STRICT
  4. SECURITY DEFINER
Show answerHide answer
Answer: A
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

A PostgreSQL transfer procedure withdraws 45.00, then its destination update matches no row. It checks FOUND, raises an uncaught exception, and never commits internally. What happens to the withdrawal?
  1. It remains because the first update succeeded.
  2. It is undone only by a compensating deposit.
  3. It remains, as zero-row updates raise no error.
  4. It is undone when the procedure call fails.
Show answerHide answer
Answer: D
The procedure turns the zero-row destination update into an explicit failure. With no internal commit, that uncaught failure rolls back the call’s withdrawal too. A zero-row update alone would not cause an error, but the stated FOUND check changes the outcome.

Question 5 of 10

An update assigns a new price to 8 products. Exactly 5 prices change, including one change from NULL to 6.00. An AFTER row trigger has WHEN (OLD.price IS DISTINCT FROM NEW.price). How many audit rows does its one-insert body write?
  1. 5 audit rows
  2. 8 audit rows
  3. 4 audit rows
  4. 1 audit row
Show answerHide answer
Answer: A
The row trigger considers each updated row, and the condition allows the five actual price changes. 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

A SQL Server insert adds shipment lines (product_id, quantity) of (11, 2), (11, 3), and (12, 4). What stock reductions should a set-based trigger apply?
  1. Product 11: 3; product 12: 4.
  2. Product 11: 2; product 12: 4.
  3. Product 11: 5; product 12: 4.
  4. Product 11: 9; product 12: 9.
Show answerHide answer
Answer: C
Both lines for product 11 contribute to its stock reduction, so grouping 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

An analysis service only reads a small set of reporting views. Which database identity best follows least privilege?
  1. A separate application login belonging to the object-owner role.
  2. A separate application login belonging to a narrow reporting role.
  3. A shared administrator login used by the deployment service as well.
  4. A shared analyst login allowed to create and replace all report objects.
Show answerHide answer
Answer: B
The service needs view access through its own accountable identity. A narrow reporting role supplies that job without ownership or administrative powers. A separate login alone is not enough if it also belongs to an owner role, because that membership gives far more authority than reading reports requires.

Question 8 of 10

A PostgreSQL role named reader has SELECT on analytics.results but no USAGE on schema analytics. It has no other access paths. What additional grant permits a simple SELECT from that table?
  1. GRANT CREATE ON SCHEMA analytics TO reader;
  2. GRANT UPDATE ON analytics.results TO reader;
  3. GRANT REFERENCES ON analytics.results TO reader;
  4. GRANT USAGE ON SCHEMA analytics TO reader;
Show answerHide answer
Answer: D
Table access requires permission to look up objects in the schema as well as the table’s select privilege. 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

A driver refuses multiple SQL statements in one call. An application still appends raw request text to WHERE parcel_id = . Why does rejecting multiple statements leave this query vulnerable?
  1. Input must create a second statement before it can alter any row filter.
  2. Input becomes safe if the application also removes every apostrophe.
  3. Input can alter the predicate inside the one permitted statement.
  4. Input can change only table names when statement stacking is disabled.
Show answerHide answer
Answer: C
A concatenated value can add an expression to the existing predicate without starting another statement. Numeric positions need no quote to be altered. Blocking stacked statements limits one attack form, but it does not establish the separation of SQL structure and input values.

Question 10 of 10

A Python sqlite3 report receives a sort choice and a name substring. It must sort by either name or created_at and search names safely. How should it construct the query?
  1. Map the sort choice to a fixed column, and bind the complete LIKE pattern.
  2. Bind the sort choice as a value, and bind the complete LIKE pattern.
  3. Map the sort choice to a fixed column, and interpolate the quoted search text.
  4. Quote both request strings as identifiers, then interpolate them into the query.
Show answerHide answer
Answer: A
The sort choice controls an identifier, so it needs a fixed mapping to approved SQL text. The substring is data, so its complete 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

A populated PostgreSQL materialized view is refreshed each night. An order is added at noon. When does that order enter the view’s stored result, assuming no other refresh runs?
  1. At the next SELECT from the materialized view.
  2. At the next successful nightly refresh.
  3. At the commit of the order insert.
  4. At the next creation of a reporting index.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A PostgreSQL view created with 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?
  1. The existing columns followed by serial_code.
  2. Only serial_code until the view is refreshed.
  3. No columns, as the view becomes invalid.
  4. The existing device_id and label columns.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A MySQL procedure starts a transaction, withdraws funds, then encounters an error. Its exit handler only writes a log entry and returns. What should the handler do when it cannot recover the transfer?
  1. Roll back the transaction and resignal the error.
  2. Commit the transaction and resignal the error.
  3. Roll back the transaction and return success.
  4. Keep the transaction open and return the log identifier.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A transfer reads no source-account row into a PL/pgSQL variable. It tests only IF v_balance < p_amount, then deposits into an existing destination. Why can this create an incorrect balance?
  1. The missing source sets zero, so every positive transfer must be rejected.
  2. The missing source raises an error before the IF statement can execute.
  3. The missing source leaves NULL, so the comparison does not enter the failure branch.
  4. The missing source makes PostgreSQL skip every later UPDATE automatically.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A PostgreSQL BEFORE INSERT row trigger cleans a valid incoming row but then returns NULL. What happens to that row’s insertion?
  1. It is stored with all columns NULL.
  2. It is stored with the cleaned values.
  3. It is stored, then deleted afterward.
  4. It is skipped without being stored.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A PostgreSQL support role reads a security-barrier directory view hiding email addresses. A new role membership also grants SELECT on the underlying customer table, and there is no RLS. What security effect does that membership have?
  1. The barrier filters emails from all support queries, including table queries.
  2. Support can bypass the directory and read emails directly from the table.
  3. The view grant overrides the broader table grant for the same user.
  4. The view becomes invoker-rights automatically and refuses every query.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

RLS is enabled on a PostgreSQL table, but there are no policies. An ordinary non-owner role has SELECT and no bypass attribute. How many rows can it read?
  1. Zero rows.
  2. Every row.
  3. Only rows it inserted.
  4. Only rows with non-NULL keys.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An owner grants Leo SELECT with grant option. Leo grants SELECT to Noor, whose only access depends on that grant. The owner runs REVOKE GRANT OPTION FOR SELECT ON reports FROM leo CASCADE;. What access remains?
  1. Leo loses SELECT; Noor keeps SELECT.
  2. Both keep SELECT but neither can grant it.
  3. Leo keeps SELECT; Noor loses SELECT.
  4. Both lose SELECT and all role memberships.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A PostgreSQL definer routine uses %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?
  1. Accept any quoted table name because quoting also grants authorization.
  2. Check the table name against a fixed set of permitted report tables.
  3. Replace %I with %L so the supplied table becomes a literal value.
  4. Grant callers direct SELECT on every table reachable by the routine.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A sqlite3 query contains WHERE tag = ?. The tag value is the string green,blue. How does binding that one value affect an equality comparison?
  1. It compares tag with either green or blue.
  2. It expands into two separate placeholders.
  3. It compares tag with a pair of SQL identifiers.
  4. It compares tag with one string containing a comma.
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

A PostgreSQL base view filters 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?
  1. The update succeeds and the row leaves both views.
  2. The update fails because LOCAL checks lower filters.
  3. The update succeeds and the row stays in the upper view.
  4. The update fails as filtered columns cannot change.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A populated PostgreSQL materialized view has only a unique index on report_day with WHERE total > 0. Why does this index not permit concurrent refresh?
  1. It is unique, while concurrent refresh requires duplicate index entries.
  2. It is on a column, while concurrent refresh requires an expression index.
  3. It excludes some rows, so it is not a qualifying all-row unique index.
  4. It stores days, while concurrent refresh requires an integer-only index.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A function replaces a NULL discount with zero using COALESCE in its body. A developer marks it STRICT. What happens when it is called with a NULL discount?
  1. It runs COALESCE and applies a zero discount.
  2. It raises an exception for every missing argument.
  3. It turns every argument into zero before running the body.
  4. It returns NULL without running the defaulting expression.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A SQL Server script has GO between two routine definitions. Which component interprets that separator?
  1. The stored procedure’s transaction handler.
  2. The client tool submitting batches.
  3. The server’s row-trigger engine.
  4. The database’s permission-policy evaluator.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A PostgreSQL view hides rows whose 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?
  1. 3 visible rows and 5 stored rows.
  2. 3 visible rows and 3 stored rows.
  3. 5 visible rows and 5 stored rows.
  4. 5 visible rows and 3 stored rows.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A MySQL role has already been granted to Sora. An administrator sets it as Sora’s default role, but Sora’s existing session still lacks its privileges. What can Sora run to activate it now?
  1. FLUSH PRIVILEGES;
  2. REVOKE ALL PRIVILEGES;
  3. SET ROLE DEFAULT;
  4. CREATE ROLE reporting;
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A PostgreSQL definer function owned by bank_owner uses an unqualified accounts name and leaves temporary relations ahead of its trusted schema. PUBLIC can execute it. A caller with no account privileges can create temporary tables. What two changes close unintended calling and object-substitution paths?
  1. Restrict execute access to intended roles and leave temporary relations first in the path.
  2. Keep PUBLIC execution and fix a trusted search path with pg_temp last.
  3. Give all callers account updates and retain the function’s current lookup path.
  4. Restrict execute access to intended roles and fix a trusted search path with pg_temp last.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A PostgreSQL table has tickets (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?
  1. 31 and 33.
  2. 31 only.
  3. 31, 32, 33, and 34.
  4. 31 and 32.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A name is inserted with bound parameters and later read into a monthly report routine. That routine concatenates the name into a WHERE clause. Where does the injection risk arise?
  1. When the parameterized insert stores a quote as ordinary data.
  2. When the stored name is concatenated into the later SQL statement.
  3. Only if the stored name is changed after the report begins.
  4. Only when the report contains multiple SQL statements in one call.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A service validates that a quantity is a positive integer, binds it to an update, and connects as a table owner. What additional change most directly limits damage if another query path still has injection?
  1. Replace bound values with manually escaped quantity strings.
  2. Give the owner role a longer password but retain its query privileges.
  3. Use an application role with only the required object privileges.
  4. Hide every database error while retaining all owner permissions.
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

A report must list every member, including those with no accepted submissions. It uses a view with a left join to submissions. How should it place the accepted-status test and count submissions to preserve those members with a count of zero?
  1. Put the status test in WHERE and count the joined submission key.
  2. Put the status test in ON and count all joined rows with COUNT(*).
  3. Put the status test in WHERE and count all joined rows with COUNT(*).
  4. Put the status test in ON and count the joined submission key.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A simple PostgreSQL view omits a required 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?
  1. Every view that omits a column is read-only.
  2. Inserts through views always need INSTEAD OF triggers.
  3. The base table still needs a category_id value.
  4. A check option supplies NULL to every omitted column.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A report needs a reusable stored query accepting a project identifier and returning several task rows. What PostgreSQL routine form fits that use in FROM?
  1. A scalar function returning one task identifier.
  2. A table-returning function with a project parameter.
  3. A procedure used directly as a FROM expression.
  4. A plain view accepting a CALL argument.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A top-level PostgreSQL procedure lowers A from 260.00 to 200.00 and commits, then raises B from 40.00 to 100.00. Both updates have AFTER audit triggers. A later uncaught error occurs before any second commit. What balances and audit entries persist?
  1. A 200.00, B 40.00; only A’s audit entry.
  2. A 260.00, B 40.00; neither audit entry.
  3. A 200.00, B 100.00; both audit entries.
  4. A 200.00, B 40.00; both audit entries.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A PostgreSQL price-audit trigger runs AFTER UPDATE OF price, with no WHEN condition. A statement sets price = price on four rows. Its body inserts one history row on each firing. How many history rows result?
  1. 0 history rows.
  2. 1 history row.
  3. 4 history rows.
  4. 8 history rows.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An AFTER UPDATE trigger on a PostgreSQL table updates that same table without an event-column restriction or a condition that stops another firing. What change best prevents an endless trigger chain while keeping audit work?
  1. Replace the self-update with an insert into a separate history table.
  2. Rename the trigger so it sorts last alphabetically.
  3. Change its return value from NULL to NEW.
  4. Wrap the same self-update inside a stored procedure call.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A PostgreSQL application login is not a superuser, but is a member of the table-owner role and can act as it. Why is this still too powerful for an order-entry task?
  1. Only LOGIN roles can own tables, so the membership prevents inserts.
  2. Owner authority can alter or drop objects beyond the required data operations.
  3. NOLOGIN owner roles cannot pass any privileges to their members.
  4. Owner membership removes every ordinary table privilege from the application.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

The owner grants SELECT on all existing tables in schema 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?
  1. Repeat the existing-table grant only; it also changes future defaults.
  2. Set another owner’s default privileges only; this also repairs the new table.
  3. Grant schema USAGE only; it automatically supplies SELECT on future tables.
  4. Grant SELECT on the new table and set its creator’s future default privileges.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A search endpoint displays only a fixed success message, yet builds a predicate by concatenating a request value. Database errors are hidden, but query-dependent behavior can still affect response time. Why is the endpoint still vulnerable?
  1. A fixed displayed message makes every concatenated predicate safe.
  2. Hidden errors guarantee that input cannot change the SQL structure.
  3. Injected conditions can expose information through behavior without returning rows.
  4. Injection is possible only if the driver accepts a second SQL statement.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A psycopg search already binds its text value safely. Users now need an exact search for names containing a literal percent sign, not a wildcard. What needs to change?
  1. Escape LIKE metacharacters with an agreed escape convention, then bind the pattern.
  2. Interpolate the text into a quoted literal so percent becomes ordinary text.
  3. Quote the placeholder itself so its bound percent sign loses wildcard meaning.
  4. Bind the pattern twice so the driver treats percent as an identifier character.
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

A dashboard needs stored aggregates and uninterrupted reads during refresh. Its populated PostgreSQL materialized view has no unique index, and the grouped result has one row per (site_id, day), with several days for each site. What preparation supports concurrent refresh?
  1. Create an all-row unique index on site_id alone, then refresh concurrently.
  2. Create an all-row unique index on site_id and day, then refresh concurrently.
  3. Create a nonunique index on site_id and day, then refresh concurrently.
  4. Create a partial unique index on site_id and day, then refresh concurrently.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A SQL Server transfer uses a transaction and TRY...CATCH. After the source update, it runs a diagnostic SELECT, then checks @@ROWCOUNT to decide whether the withdrawal matched an account. What correction makes that check reliable?
  1. Check or save @@ROWCOUNT immediately after the source UPDATE.
  2. Keep the diagnostic SELECT and check @@TRANCOUNT for the affected rows.
  3. Move the same @@ROWCOUNT check after the COMMIT statement.
  4. Replace the check with an assumption that every UPDATE matches one row.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A procedure increases every item in one category by the same percentage. No row depends on another row’s result. What implementation best fits this task?
  1. A cursor that selects and updates each matching row separately.
  2. One CALL per matching row from the application.
  3. One UPDATE with a category filter and the price expression.
  4. A loop that commits after updating each individual item.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A table already requires invoice amounts to be NOT NULL. What additional table mechanism directly requires every amount to be nonnegative?
  1. An AFTER trigger that only logs negative amounts.
  2. A view that sorts invoices by amount.
  3. A role that can update every invoice amount.
  4. A CHECK constraint on the amount column.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A PostgreSQL view initially uses its owner’s table rights. A caller has schema USAGE and SELECT on the view, plus base-table SELECT through reporting. The view becomes security_invoker, then reporting membership is removed. There are no other grants. How do view reads behave after each change?
  1. They fail after the view change, then work after membership removal.
  2. They work after both changes because the owner’s rights remain available.
  3. They fail after both changes because view grants cannot coexist with invoker rights.
  4. They work after the view change, then fail after membership removal.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A pooled PostgreSQL connection retains tenant 12 in a session setting. Tickets 41 and 42 belong to tenant 12; ticket 43 belongs to tenant 18. An ordinary role has table rights and tenant-equality USING/WITH CHECK. A tenant-18 request forgets to set context, updates ticket 41, then inserts a tenant-18 ticket. What happens before any rollback?
  1. Ticket 41 is hidden; the tenant-18 insert succeeds.
  2. Ticket 41 can change; the insert fails its tenant check.
  3. Ticket 41 can change; the tenant-18 insert succeeds.
  4. Ticket 41 is hidden; the insert fails because the role has no table rights.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A PostgreSQL user has table SELECT directly, through reporting, and through PUBLIC. She must lose reads while other reporting members and the other intended PUBLIC readers keep them. Why is revoking her direct grant and reporting membership insufficient, and what design change is needed?
  1. PUBLIC remains; replace its broad read grant with explicit intended-reader grants.
  2. PUBLIC remains; directly revoke her SELECT with CASCADE while retaining the PUBLIC grant.
  3. Reporting remains; revoke the role’s SELECT while retaining PUBLIC for the other readers.
  4. PUBLIC remains; replace her direct table grant with a column-only SELECT grant.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A SQL Server procedure’s owner has SELECT on its table; the caller has only EXECUTE on the procedure. Static SQL works through the same-owner chain. A version with bound dynamic SQL fails, then gains EXECUTE AS OWNER. How should that version behave after the context change, and what happens to the need for binding?
  1. It still needs the caller’s table grant, and values still need binding.
  2. It can use the owner’s table rights, and concatenated values become safe.
  3. It can use the owner’s table rights, and values still need binding.
  4. It can use caller table rights through binding, and the context adds no access.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A Node.js pg query uses WHERE record_id = ANY($1). The application has three integer identifiers to search for. What should it supply as that parameter value?
  1. A comma-separated string of the identifiers.
  2. An array containing the three identifiers.
  3. An SQL fragment listing three placeholders.
  4. A column name holding the identifiers as text.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A PostgreSQL table has rows (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?
  1. 51 and 52.
  2. 51 and 53.
  3. 51, 52, and 53.
  4. 51 only.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

77 Key Terms, each with its definition

A

AFTER trigger
An AFTER trigger runs following the triggering change and can perform related work, while remaining inside the statement’s transaction.
An AFTER trigger adds a history row using the price values from the completed update.
Allow-list
An allow-list defines the accepted choices for an input, allowing structural SQL fragments to come from approved program constants.
A sort allow-list maps a request key to a fixed column reference and rejects unsupported names.
Audit trail
An audit trail records changes and useful context, such as old and new values, a time, and an identity, for later inspection.
The price audit trail shows which values changed and rolls back if their transaction rolls back.
Authentication
Authentication verifies the identity connecting to a database, commonly through a credential, before its permitted actions are evaluated.
Successful authentication does not give an application permission to read every table.
Authorization
Authorization determines which actions an identified user or role may perform on database objects through the applicable access rules.
Authorization lets a reporting role read approved views while refusing changes to orders.

B

Base table
A base table stores the rows that a view reads or changes, providing the underlying data behind the view’s named interface.
Updating a total through a simple view changes the corresponding value in its base table.
Batch separator
A batch separator is a client-tool instruction that divides a script into groups sent to the server, rather than a routine-body statement.
SQL Server tools interpret the batch separator GO between routine definitions.
BEFORE trigger
A BEFORE trigger runs ahead of the stored row change and can validate or adjust incoming values where the database supports that behavior.
A PostgreSQL BEFORE trigger trims and lowercases an incoming customer email address.
Blind injection
Blind injection reveals information through observable behavior, errors, or timing without needing the application to display the requested rows.
A fixed results page can still leak a true-or-false condition through blind injection.
Bound value
A bound value is data supplied through a query’s parameter interface, retaining its data role even when it contains SQL-looking characters.
A bound value containing a comma is one string, not an automatically expanded membership list.

C

Cascaded check option
A cascaded check option enforces the filters of the current view and underlying views, including those without their own check options.
A cascaded check option on an eastern-region view built over an active-rows view prevents moving a row outside either filter.
Check option
A check option requires rows inserted or updated through a view to satisfy its checked filtering conditions after the write.
On a paid-orders view, the check option rejects changing an order to a status that the view excludes.
Column alias
A column alias names a query output column, making a computed value such as a sum usable through a clear, stable interface.
The column alias order_count identifies the aggregate that a report can select and filter.
Common table expression
A common table expression is a named query expression introduced with WITH and available only within its containing statement.
A common table expression helps one report query, while a saved view can serve later queries.
Computed column
A computed column in a view displays an expression’s result instead of a directly writable reference to one stored base column.
A computed column showing a tax-inclusive price is recalculated after its base price changes.
Concurrent refresh
A concurrent refresh updates a PostgreSQL materialized view while allowing reads, using populated data and a qualifying unique index.
A concurrent refresh lets analysts continue reading the stored report during its maintenance.

D

Default privileges
PostgreSQL default privileges set grants for objects created later by a specified creator role, leaving existing objects’ grants unchanged.
Default privileges let future migration-created report tables receive the intended read grants.
Defense in depth
Defense in depth uses controls with distinct jobs so a weakness in one layer does not leave the system with unrestricted exposure.
Defense in depth combines binding, restricted database access, validation, and careful error messages.
Definer rights
Definer rights execute an object’s underlying work using its owner’s privileges, allowing a narrow interface to reach otherwise inaccessible data.
Definer rights let a teller execute a checked transfer without receiving direct account updates.
Dependency
A dependency is a relationship in which one database object needs another object’s definition or existence to keep working.
A view’s dependency on orders can block dropping that table in PostgreSQL.
Dollar quoting
PostgreSQL dollar quoting encloses a string or routine body between matching dollar markers, avoiding doubled internal single quotes.
Dollar quoting keeps a PL/pgSQL body readable when its error messages contain text literals.
Dynamic SQL
Dynamic SQL is a statement built as text and then executed, requiring safe value binding and controlled choices for its variable structure.
A routine uses dynamic SQL when a permitted report table is selected at runtime.

E

Effective privileges
Effective privileges are the combined rights an identity can use through direct grants, applicable role memberships, and PUBLIC access.
Checking effective privileges explains why a user still reads orders after a direct grant is revoked.
Exception
An exception is a raised database error that interrupts ordinary execution and can be caught by a suitable handler or passed to the caller.
An exception stops a transfer when its destination account does not exist.
Exception handler
An exception handler runs code for a caught error, allowing deliberate recovery or cleanup before execution continues or the error is raised again.
An exception handler rolls back an incomplete MySQL transfer and passes its failure outward.

G

Grant option
The grant option lets a privilege recipient pass that privilege to another grantee, creating onward grants that may depend on its survival.
If Bob passed a read grant to Carol, removing Bob’s grant option with a cascade can preserve his reading but remove Carol’s dependent grant.

I

Identifier quoting
Identifier quoting encodes a name as one SQL identifier so its characters cannot become additional syntax, without deciding its authorization.
Identifier quoting keeps a table name intact while an allow-list limits which tables can be chosen.
Indexed view
An indexed view in SQL Server stores an eligible schema-bound view’s result through a unique clustered index and maintains it on writes.
An indexed view makes a repeated aggregate available while adding work to its base-table updates.
INOUT parameter
An INOUT parameter receives an initial input and returns a resulting output through the same parameter position in the routine interface.
A procedure’s INOUT parameter can receive a running total and return its updated value.
Input parameter
An input parameter supplies a value to a routine, such as the account or amount the routine uses to perform its requested task.
A transfer’s input parameter identifies the destination without changing the routine’s definition.
Input validation
Input validation checks whether supplied data has acceptable types, lengths, ranges, and formats before the application uses it.
Input validation can reject an invalid quantity while parameter binding still protects the query.
INSTEAD OF trigger
An INSTEAD OF trigger replaces a requested data change with its own defined action, often providing custom writes through a view.
An INSTEAD OF trigger turns a view delete into a timestamp update on its base table.
Invoker rights
Invoker rights execute underlying work using the caller’s privileges, keeping access tied to the identity that requested the operation.
A PostgreSQL invoker-rights view still requires the caller’s permission to read its base tables.

L

Least privilege
Least privilege gives an identity only the access needed for its task, keeping unnecessary data and administrative actions out of reach.
Least privilege separates an order-entry account from the role that changes table definitions.
LIKE wildcard
A LIKE wildcard is a pattern character, such as percent or underscore, that represents matching text even when the pattern is safely bound.
A literal percent search must escape the LIKE wildcard without replacing safe parameter binding.
Local check option
A local check option enforces its own view’s conditions while retaining checks explicitly required by underlying views.
A local check option need not enforce a lower view’s filter when that lower view has no check option.

M

Materialized view
A materialized view stores query-result rows between refreshes, trading storage and maintenance for repeated reads of precomputed data.
A monthly revenue materialized view can remain unchanged while new orders enter its base table.

O

Object owner
An object owner controls a database object’s definition and privileges, holding authority beyond an ordinary grant to read or change its data.
An application should not act as the object owner merely to make its order queries work.
OLD and NEW
The OLD and NEW trigger records contain the relevant before-change and after-change row versions for row-level data-change events.
An update trigger compares OLD and NEW to see whether a nullable product price actually changed.
Output parameter
An output parameter returns a value from a procedure to its caller, with the exact calling and retrieval syntax varying by database.
An output parameter can return an order count after a procedure completes its query.
Ownership chaining
SQL Server ownership chaining can allow a call through same-owner objects without separately checking the caller’s permissions on each underlying object.
Static SQL can use ownership chaining where a dynamic statement instead checks its execution context.

P

Parameterized query
A parameterized query supplies SQL structure and input values separately, keeping the supplied values from being interpreted as statement syntax.
A parameterized query searches for an apostrophe-containing name as one ordinary text value.
Permissive policy
A permissive policy contributes an allowed condition combined with other applicable permissive policies by OR, so it can widen row access.
A permissive policy allowing all rows can undo the intended narrowing of another tenant policy.
Placeholder
A placeholder marks a value position in SQL for the database library to bind, using the syntax expected by that specific library.
A placeholder such as ? in sqlite3 remains unquoted and receives a separately supplied value.
Prepared statement
A prepared statement fixes a query’s structure for execution with separately supplied values and can sometimes reuse parsing or planning work.
A prepared statement remains unsafe if untrusted values were already interpolated into its text.
Privilege
A privilege is permission to perform a specified operation on a database object, such as reading a table or executing a routine.
A select privilege permits reading a table but does not authorize dropping its definition.
PUBLIC
In PostgreSQL, PUBLIC is the implicit set of every role, including roles created later, and can receive grants that reach all those roles.
Revoking a new routine’s default execute grant from PUBLIC closes access for unintended callers.

R

Refresh
A refresh reruns a materialized view’s defining query and replaces its stored result with the result produced from the source data.
A nightly refresh updates the dashboard’s stored totals after the day’s orders are complete.
Restrictive policy
A restrictive policy adds a condition combined with AND to narrow rows already allowed by permissive policies; it does not alone open access.
A restrictive policy can require active rows as well as the tenant rule from a permissive policy.
Rethrow
A rethrow passes a caught error onward after handling so the caller can still detect that the requested task did not succeed.
A rethrow prevents an application from showing success after a handler merely logs a failure.
Role
A role is a named database identity or privilege grouping whose membership can give users the rights needed for a particular task.
The reporting role supplies analysts with shared read privileges without separate grants per person.
Row lock
A row lock controls concurrent access to a row during a transaction so competing operations cannot freely change it at the same time.
The source-account row lock makes a competing withdrawal wait for the current transfer.
Row-level security
Row-level security enforces policies selecting which table rows an authorized operation may read or change for its requesting identity or context.
Row-level security prevents an ordinary tenant role from reading another tenant’s tickets.
Row-level trigger
A row-level trigger is invoked separately for each affected row, receiving the row versions that exist for its insert, update, or delete event.
Updating three tea prices invokes a row-level trigger three times before conditions exclude any rows.

S

Scalar function
A scalar function returns one value per call and can be used within an SQL expression such as a SELECT output or a condition.
A scalar function computes one discounted total for each order-item row passed to it.
Schema USAGE
PostgreSQL schema USAGE permits lookup of objects in a schema without supplying their separate table or routine operation privileges.
Schema USAGE accompanies the product table’s select grant so the application can query it.
Search path
A PostgreSQL search path is the ordered set of schemas searched for unqualified object names, making trusted ordering critical in elevated routines.
A definer routine in a bank database uses a search path that places its trusted schema before temporary relations.
Second-order injection
Second-order injection occurs when previously stored input is later incorporated unsafely into a new statement and changes that statement’s meaning.
A safe registration insert can still be followed by second-order injection in a concatenated report.
Security barrier
A security barrier protects a PostgreSQL view’s row filter from early evaluation of user functions that could reveal values in excluded rows.
A security barrier keeps a reporting function from inspecting rows before the protective filter.
Set-based operation
A set-based operation handles qualifying rows together in one SQL statement, applying the data rule without a separate loop per row.
One set-based operation increases the prices of all products in the chosen category.
Soft delete
A soft delete marks a stored row as deleted and hides it through an interface, preserving the base row instead of physically removing it.
A soft delete removes a product from the active-products view while retaining its history.
SQL injection
SQL injection occurs when untrusted input becomes SQL syntax and changes a statement’s structure, allowing unintended database operations.
An SQL injection can widen a concatenated search predicate to include records outside the intended match.
Statement-level trigger
A statement-level trigger runs once for a matching statement event regardless of its affected-row count, including an empty result.
A statement-level trigger must handle all lines added by a single multi-row shipment insert.
Stored procedure
A stored procedure performs a database task through its own call statement, often coordinating several operations and output parameters.
A stored procedure checks a transfer before withdrawing from one account and crediting another.
Stored routine
A stored routine is named code kept in the database and executed by its server, with functions and procedures providing different interfaces.
A shared discount stored routine keeps several reports from implementing different formulas.
Strict function
A strict function returns NULL without executing its body whenever any supplied argument is NULL, using PostgreSQL’s STRICT declaration.
A strict function cannot apply a missing-discount default inside a body that never runs.

T

Table function
A table function returns a set of rows and can accept arguments, allowing its result to be used as a parameter-driven query source.
A table function returns the orders belonging to the customer identifier supplied by the caller.
Tautology
A tautology is a condition that is always true, which can make a vulnerable query’s combined predicate accept rows beyond the intended match.
A tautology added through untrusted SQL text can remove the practical effect of an equality filter.
Tenant context
A tenant context is trusted request information identifying the organization whose rows an application should reach in a shared database.
Transaction-local tenant context prevents a pooled connection from retaining the previous request’s identity.
Transition table
A transition table exposes a changed-row set to an eligible PostgreSQL AFTER trigger so its body can process the statement’s rows together.
A transition table named new_rows lets a trigger aggregate newly inserted quantities.
Trigger
A trigger automatically invokes database logic for a declared event, with its timing and level determining when and how often it runs.
A trigger records price history when a product’s price changes through any ordinary update path.
Trigger recursion
Trigger recursion occurs when triggered work causes the trigger to fire again, potentially repeating indefinitely without a stopping condition.
Trigger recursion can arise when an after-update function updates its own source table again.

U

Updatable view
An updatable view allows supported writes to be passed to identifiable base-table rows, with computed output columns remaining read-only.
A paid-orders updatable view lets staff correct an order total in the underlying orders table.
USING policy expression
A PostgreSQL USING policy expression filters existing rows available for reads, updates, and deletes, silently excluding rows that fail it.
A USING policy expression makes an update to an invisible tenant’s ticket affect zero rows.

V

View
A view is a saved, named query that callers can read like a table, with a plain view retrieving rows from its underlying data.
A customer report reads a view so every report uses the same canceled-order filter.
Volatility label
A volatility label tells PostgreSQL how a function’s results and data effects may vary, guiding which planner assumptions are valid.
A volatility label of STABLE permits a lookup function to read tables within a statement.

W

WITH CHECK policy expression
A WITH CHECK policy expression tests the new row state produced by an insert or update and rejects a row that violates the policy.
A WITH CHECK policy expression rejects moving a visible ticket into a different tenant.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started