🌍 SQL & Databases · subject
SQL & Databases Advanced SQL and Programmability Syllabus
The Advanced SQL and Programmability syllabus for SQL & Databases in full: 7 chapters and 26 topics, every one listed below, plus 50 Advanced SQL and Programmability flashcards with answers.
Advanced SQL and Programmability syllabus: all 7 chapters
Expand any chapter to see its topics and sub-topics.
-
Window Functions
5 topics- OVER, PARTITION BY, ORDER BY
- Ranking Functions
- Offset Functions
- Window Frames (ROWS/RANGE)
- Running Totals and Moving Averages
-
Common Table Expressions
3 topics- WITH Clause Basics
- Recursive CTEs
- CTEs vs Subqueries vs Temp Tables
-
Modifying Data
5 topics- INSERT and Bulk Inserts
- UPDATE with Joins
- DELETE and TRUNCATE
- UPSERT
- RETURNING / OUTPUT Clauses
-
Views and Materialized Views
3 topics- Creating and Using Views
- Updatable Views
- Materialized Views and Refresh Strategies
-
Stored Procedures and Functions
4 topics- Procedural Extensions
- Parameters and Return Values
- Control Flow and Loops
- Error Handling and Exceptions
-
Triggers and Automation
3 topics- BEFORE and AFTER Triggers
- Row vs Statement Triggers
- Use Cases and Anti-Patterns
-
Pivoting and Advanced Patterns
3 topics- PIVOT and UNPIVOT
- Conditional Aggregation
- Gaps and Islands
SQL & Databases Advanced SQL and Programmability flashcards — 50 questions with answers
What does the OVER clause do in SQL, and how does it differ from GROUP BY?
OVER defines a window (set of rows) over which a window function operates. Unlike GROUP BY, it does not collapse rows: each input row is retained and gets a computed value alongside it.
In a window function, what is the role of PARTITION BY?
PARTITION BY divides the rows into groups (partitions); the window function restarts and is computed independently within each partition. Without it, the entire result set is one partition.
Within OVER(), what does adding ORDER BY change for a window function?
ORDER BY defines the logical order of rows inside each partition, which determines ranking, offsets, and the default running window frame (from start of partition to the current row).
Compare the three ranking functions ROW_NUMBER, RANK, and DENSE_RANK on tie handling.
ROW_NUMBER gives every row a unique sequential number (ties broken arbitrarily). RANK assigns equal rank to ties then skips numbers (1,1,3). DENSE_RANK assigns equal rank to ties with no gaps (1,1,2).
What does NTILE(n) do as a window function?
NTILE(n) distributes the ordered rows of each partition into n roughly equal buckets and returns the bucket number (1..n) for each row. Earlier buckets get the extra rows when the count is not evenly divisible.
For the ranking values 90, 90, 80, 70, give ROW_NUMBER, RANK, and DENSE_RANK (descending).
ROW_NUMBER: 1,2,3,4. RANK: 1,1,3,4. DENSE_RANK: 1,1,2,3.
What do the offset functions LAG and LEAD return?
LAG accesses a value from a previous row in the ordered partition; LEAD accesses a value from a following row. Syntax: LAG(expr, offset, default) OVER(... ORDER BY ...).
What is the default offset for LAG and LEAD, and what happens past the partition boundary?
The default offset is 1. When the requested row is outside the partition, they return NULL unless a default argument is supplied.
What do FIRST_VALUE and LAST_VALUE return, and what is the common pitfall with LAST_VALUE?
FIRST_VALUE returns the first row's value in the window frame; LAST_VALUE returns the last. Pitfall: with an ORDER BY the default frame ends at the current row, so LAST_VALUE returns the current row's value unless the frame is set to ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
What are the two window-frame units, ROWS and RANGE, and how do they differ?
ROWS counts a physical number of rows relative to the current row. RANGE works on logical value ranges, treating all peer rows (equal ORDER BY values) as one unit. ROWS gives distinct counts; RANGE lumps ties together.
Write the frame clause for a running total from the start of the partition to the current row.
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
What is the default window frame when ORDER BY is present but no explicit frame is specified?
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Write the frame for a centered 3-row moving average (previous, current, next row).
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
How do you compute a running total of a column named amount ordered by date?
SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
Give the formula for a simple moving average over the last $n$ observations $x_i$.
$$\text{SMA}_t = \frac{1}{n}\sum_{i=0}^{n-1} x_{t-i}$$
How would you write a trailing 7-row moving average of amount ordered by date?
AVG(amount) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
What is a CTE (Common Table Expression) and how is it introduced?
A CTE is a named temporary result set defined with the WITH clause that exists only for the duration of a single query. Syntax: WITH cte_name AS (SELECT ...) SELECT ... FROM cte_name.
Can a single WITH clause define multiple CTEs, and can they reference each other?
Yes. Separate multiple CTEs with commas after a single WITH. A later CTE may reference any CTE defined earlier in the same WITH clause.
What are the two required parts of a recursive CTE, joined by which operator?
An anchor member (the base case) and a recursive member (which references the CTE itself), combined with UNION ALL. The recursion repeats until the recursive member returns no rows.
Which keyword do some databases require to declare a recursive CTE?
The RECURSIVE keyword after WITH (required in PostgreSQL, MySQL, and standard SQL; SQL Server does not require it).
Show the other 30 Advanced SQL and Programmability flashcards
Give a classic use case for a recursive CTE.
Traversing hierarchical or graph data, such as an employee/manager org chart, a bill-of-materials, or generating a sequence of numbers/dates.
How can you prevent infinite recursion in a recursive CTE?
Ensure the recursive member eventually returns no rows (a proper termination condition), and use options like a depth counter, a cycle-detection clause, or SQL Server's MAXRECURSION hint.
Compare CTEs, subqueries, and temp tables on scope and reuse.
A subquery is inline and used once in its enclosing statement. A CTE is named, readable, can be referenced multiple times in the same statement, and supports recursion. A temp table persists across multiple statements in a session and can be indexed.
When is a temp table preferable to a CTE?
When the intermediate result is large, reused across several separate statements, or benefits from indexing/statistics. Many CTEs are re-evaluated each reference (not materialized), so a temp table avoids recomputation.
Write the syntax to insert a single row with explicit column values into table t(a, b).
INSERT INTO t (a, b) VALUES (1, 'x');
How do you perform a multi-row (bulk) insert in a single INSERT statement?
List multiple value tuples: INSERT INTO t (a, b) VALUES (1,'x'), (2,'y'), (3,'z');
How can you insert rows into a table from the result of a query?
INSERT INTO t (a, b) SELECT a, b FROM other_table WHERE condition;
What is the standard syntax for UPDATE with a join in PostgreSQL?
UPDATE t SET col = s.val FROM source s WHERE t.id = s.id; (PostgreSQL uses FROM; SQL Server uses UPDATE t SET ... FROM t JOIN source s ON ...).
Why is a WHERE clause critical in an UPDATE or DELETE statement?
Without WHERE, the operation applies to every row in the table, updating or deleting all rows unintentionally.
Compare DELETE and TRUNCATE across four dimensions: WHERE support, logging, triggers, and identity reset.
DELETE: supports WHERE, is row-by-row (fully logged), fires triggers, keeps identity seed. TRUNCATE: removes all rows, minimally logged/faster, no WHERE, usually fires no row triggers, and resets identity/auto-increment.
Is TRUNCATE typically DDL or DML, and what implication does that have?
TRUNCATE is generally treated as DDL. It is faster because it deallocates data pages rather than deleting rows individually, and in some databases it cannot be rolled back or is auto-committed.
What does UPSERT mean?
An operation that inserts a new row if it does not exist, or updates the existing row if a key conflict occurs ("update or insert"), performed atomically in one statement.
Write the PostgreSQL UPSERT syntax to insert into t(id, v) and update v on conflict.
INSERT INTO t (id, v) VALUES (1, 'a') ON CONFLICT (id) DO UPDATE SET v = EXCLUDED.v;
What is the MySQL equivalent of an UPSERT?
INSERT INTO t (id, v) VALUES (1,'a') ON DUPLICATE KEY UPDATE v = VALUES(v); (newer syntax uses an alias instead of VALUES()).
Which SQL Server statement provides UPSERT-style conditional insert/update/delete?
The MERGE statement, which matches a target against a source and runs WHEN MATCHED / WHEN NOT MATCHED clauses.
What does the PostgreSQL RETURNING clause do?
RETURNING lets an INSERT, UPDATE, or DELETE return columns from the affected rows (e.g., a generated id) without a separate SELECT: INSERT INTO t (v) VALUES ('a') RETURNING id;
What is SQL Server's equivalent of RETURNING, and how does it identify old vs new values?
The OUTPUT clause. It exposes the INSERTED pseudo-table (new values) and the DELETED pseudo-table (old values); UPDATE can reference both.
What is a view in SQL?
A named, stored query that acts as a virtual table. It stores no data itself (except materialized views); it re-runs its defining SELECT each time it is queried.
Write the syntax to create a view named active_users.
CREATE VIEW active_users AS SELECT id, name FROM users WHERE active = true;
Name three benefits of using views.
They simplify complex queries (reusable abstraction), provide security by exposing only selected columns/rows, and give a stable interface that hides underlying schema changes.
What conditions generally make a view updatable?
It must map to a single base table, with no aggregation (GROUP BY, HAVING), no DISTINCT, no window functions, no set operations (UNION), and typically no computed columns being modified — so each view row corresponds to exactly one base-table row.
What does WITH CHECK OPTION do on an updatable view?
It forces INSERTs and UPDATEs through the view to satisfy the view's WHERE condition, preventing rows from being modified so they would disappear from (or never appear in) the view.
How can you make a non-updatable view support modifications?
Define an INSTEAD OF trigger (INSTEAD OF INSERT/UPDATE/DELETE) that translates the DML on the view into the appropriate operations on the underlying base tables.
What is a materialized view and how does it differ from a regular view?
A materialized view physically stores the query's result set on disk, so reads are fast but data can be stale. A regular view stores only the query definition and recomputes results on each access (always current).
What are the two broad refresh strategies for materialized views?
Complete (full) refresh, which recomputes the entire result set, and incremental/fast refresh, which applies only the changes since the last refresh using logs. Refresh can be scheduled/on-demand or, in some systems, on commit.
How do you refresh a materialized view in PostgreSQL without locking out readers?
REFRESH MATERIALIZED VIEW CONCURRENTLY view_name; (requires a unique index on the materialized view).
What are procedural extensions to SQL, and give two examples by vendor.
Procedural extensions add imperative programming constructs (variables, loops, conditionals, error handling) to declarative SQL. Examples: Oracle PL/SQL, SQL Server T-SQL, PostgreSQL PL/pgSQL.
What is the difference between a stored procedure and a user-defined function?
A function must return a value and is usually callable within a query (often no side effects). A stored procedure is invoked with CALL/EXEC, can perform actions and return zero or many result sets, and typically cannot be embedded in a SELECT.
What are the three common parameter modes in procedural SQL, and what does each do?
IN passes a value into the routine (read-only), OUT returns a value back to the caller, and IN OUT (INOUT) passes a value in and returns a possibly modified value out.
By what two mechanisms can a routine return values to its caller?
Via a RETURN statement/value (functions and scalar returns) or via OUT / INOUT parameters. Procedures may also return result sets. RETURN also immediately exits the routine.
SQL & Databases Advanced SQL and Programmability FAQ
What is in the SQL & Databases Advanced SQL and Programmability syllabus?
SQL & Databases Advanced SQL and Programmability is split into 7 chapters: Window Functions, Common Table Expressions, Modifying Data, Views and Materialized Views, Stored Procedures and Functions, Triggers and Automation and Pivoting and Advanced Patterns. Together they contain 26 topics.
How many chapters are in SQL & Databases Advanced SQL and Programmability?
7 chapters, containing 26 topics. The largest chapter is Window Functions, with 5 topics.
Are there flashcards for SQL & Databases Advanced SQL and Programmability?
Yes — a 50-card Advanced SQL and Programmability deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.