Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

The Complete Engineering Guide to Writing Advanced T-SQL

21 min readSep 1, 2026

--

Writing correct, set based SQL is a baseline expectation for any engineer working against SQL Server. Writing advanced T-SQL is a different discipline entirely, one that requires knowing when to reach for a recursive Common Table Expression versus a graph query, when a correlated subquery using EXISTS will outperform an equivalent IN, and how to structure error handling so that a production job fails loudly and safely rather than silently corrupting data. This guide walks through the full advanced T-SQL toolkit that a senior engineer is expected to command fluently, covering Common Table Expressions in both their standard and recursive forms, correlated subqueries and their relationship to EXISTS and IN, structured error handling with TRY CATCH, fuzzy string matching, native graph database querying, JSON parsing and generation, regular expression style pattern matching and its real limits inside T-SQL, and the full window function family spanning ranking, aggregate, and analytic offset functions.

Press enter or click to view image in full size

Common Table Expressions

A Common Table Expression, universally abbreviated CTE, is a named, temporary result set defined immediately before the statement that uses it, introduced with a WITH clause, and it exists purely for the duration of that single statement, unlike a view which persists as a schema object or a temp table which persists for the life of a session. The primary reason CTEs exist is readability and composability, letting you break a complex query into named, logically sequential building blocks that read top to bottom the way a person actually reasons about the problem, and unlike a subquery nested several levels deep, a CTE can also be referenced more than once later in the same statement without having to repeat its definition. It is worth being precise about a common misconception here, which is that a CTE is not automatically materialized or cached the way a temp table is, and in most cases SQL Server will simply inline the CTE definition into the surrounding query at compile time exactly as it does with a view, meaning a CTE referenced multiple times may have its underlying query re-evaluated multiple times rather than computed once, so a CTE should be understood as a readability and structuring tool rather than an automatic performance optimization.

A standard, non recursive CTE is simply a SELECT statement given a name, and any number of standard CTEs can be chained together in a single WITH clause, each one able to reference the CTEs defined before it.

/* Two chained standard CTEs. CustomerTotals is computed first,
then HighValueCustomers filters on top of it, and the final
SELECT reads naturally as a sequence of named steps */
WITH CustomerTotals AS
(
SELECT
CustomerID,
SUM(TotalAmount) AS LifetimeSpend
FROM dbo.Orders
GROUP BY CustomerID
),
HighValueCustomers AS
(
SELECT CustomerID, LifetimeSpend
FROM CustomerTotals
WHERE LifetimeSpend > 50000
)
SELECT c.CustomerName, h.LifetimeSpend
FROM HighValueCustomers AS h
INNER JOIN dbo.Customers AS c ON c.CustomerID = h.CustomerID
ORDER BY h.LifetimeSpend DESC;

A recursive CTE is the mechanism T-SQL provides for traversing hierarchical or graph shaped data, such as an organizational reporting chain, a bill of materials, or a category tree, without writing a procedural loop. It is structured in three required parts joined by UNION ALL. The anchor member is the base case, a plain SELECT with no self reference, that produces the starting row or rows of the recursion, for example the top level employee with no manager. The recursive member is a second SELECT that references the CTE by its own name, joining the CTE back to the base table to find the next level, and this is what SQL Server repeatedly re-executes, feeding the previous iteration’s output back in as the input to the next, until a termination condition is reached, which is simply the point at which the recursive member’s join predicate returns zero new rows. Because an incorrectly written recursive member can loop indefinitely, for example if the underlying hierarchy data has a cycle, SQL Server enforces a default MAXRECURSION limit of one hundred, which raises an error if exceeded and which can be explicitly widened or, with caution, set to zero to remove the limit entirely.

/* Recursive CTE walking an employee reporting hierarchy.
Anchor: employees with no manager (the top of the org chart).
Recursive member: joins EmployeeHierarchy back to Employees to
find direct reports of everyone found in the previous iteration.
Termination happens naturally once a level produces no more
matching rows, i.e. once you reach the individual contributors */
WITH EmployeeHierarchy AS
(
/* anchor member */
SELECT
EmployeeID,
ManagerID,
EmployeeName,
0 AS HierarchyLevel
FROM dbo.Employees
WHERE ManagerID IS NULL
UNION ALL
/* recursive member, references EmployeeHierarchy itself */
SELECT
e.EmployeeID,
e.ManagerID,
e.EmployeeName,
eh.HierarchyLevel + 1
FROM dbo.Employees AS e
INNER JOIN EmployeeHierarchy AS eh ON e.ManagerID = eh.EmployeeID
)
SELECT EmployeeID, EmployeeName, HierarchyLevel
FROM EmployeeHierarchy
OPTION (MAXRECURSION 500); /* explicitly widened for a deep org chart */

Correlated Subqueries

A subquery is correlated when its inner SELECT references a column from the outer query’s table alias, which means, unlike an independent subquery that can be evaluated once and reused, a correlated subquery is logically re-evaluated once per row of the outer query, using that row’s specific values as part of its own filter. This makes correlated subqueries the natural tool for row by row existence checks and per row scalar lookups, such as finding every customer who has placed at least one order over a certain amount, where the subquery’s WHERE clause reaches back out to the outer query’s CustomerID for every candidate row it considers.

/* Correlated subquery: the inner query's WHERE clause references
c.CustomerID from the outer query, so it is logically
re-evaluated per outer row rather than computed once */
SELECT c.CustomerID, c.CustomerName
FROM dbo.Customers AS c
WHERE EXISTS
(
SELECT 1
FROM dbo.Orders AS o
WHERE o.CustomerID = c.CustomerID
AND o.TotalAmount > 10000
);

The choice between EXISTS and IN for this kind of existence check is one of the most frequently misunderstood performance topics in T-SQL, and it deserves a direct comparison. EXISTS is a Boolean, short circuiting test, meaning SQL Server can stop searching the inner table the instant it finds a single matching row for the current outer row, and it does not care about or process NULL values returned by the inner query at all, since it only ever asks whether any row exists. IN, by contrast, is logically evaluated by comparing the outer value against the full list of values produced by the inner query, and critically, if that inner list contains even a single NULL, NOT IN can produce surprising and often wrong results, because in three valued logic a comparison against NULL evaluates to UNKNOWN rather than false, silently excluding rows that the developer expected to be returned. In modern SQL Server, the query optimizer is frequently able to rewrite a well formed IN subquery into a semantically equivalent EXISTS style semi join internally, so for simple existence checks against a NOT NULL foreign key the two often perform identically in practice, but the strong recommendation, and the safer default, is to always prefer EXISTS and NOT EXISTS over IN and especially over NOT IN whenever a subquery result could conceivably contain a NULL, since EXISTS carries no such correctness risk and generally communicates intent, a mere existence check, more clearly than IN does.

/* Correctness trap: if OrderID ever contains a NULL in the
subquery result, this NOT IN will unexpectedly return zero rows
for every single customer, not just the ones with orders,
because comparing against NULL evaluates to UNKNOWN */
SELECT CustomerID FROM dbo.Customers
WHERE CustomerID NOT IN (SELECT CustomerID FROM dbo.Orders WHERE CustomerID IS NULL);
/* Safer, NULL-proof equivalent using NOT EXISTS */
SELECT c.CustomerID FROM dbo.Customers AS c
WHERE NOT EXISTS (SELECT 1 FROM dbo.Orders AS o WHERE o.CustomerID = c.CustomerID);

Error Handling

Production T-SQL must never assume the happy path, and the standard structured mechanism for this is a TRY CATCH block, conceptually similar to exception handling in a general purpose programming language. Any statement inside the TRY block that raises a runtime error, such as a constraint violation, a deadlock, or an arithmetic overflow, immediately transfers control to the corresponding CATCH block rather than terminating the batch outright, which gives you a controlled place to log the failure, roll back any open transaction, and decide how to respond. Inside the CATCH block, SQL Server exposes a family of functions that describe exactly what went wrong:

ERROR_NUMBER returns the numeric error code,

ERROR_MESSAGE returns the fully formatted message text including any substituted parameters,

ERROR_SEVERITY returns the severity level which broadly indicates how serious the error is,

ERROR_STATE returns a state number that can help disambiguate multiple occurrences of the same error number raised from different points in code, and

ERROR_LINE and ERROR_PROCEDURE, while not explicitly listed, are commonly used alongside these to pinpoint exactly where the failure occurred.

/* Standard production pattern: transaction protected by TRY CATCH,
full diagnostic capture in the CATCH block, and a guaranteed
rollback before the error is either logged or re-raised */
BEGIN TRY
BEGIN TRANSACTION;

UPDATE dbo.Inventory
SET Quantity = Quantity - 10
WHERE ProductID = 501;
IF (SELECT Quantity FROM dbo.Inventory WHERE ProductID = 501) < 0
THROW 50001, 'Inventory cannot go negative for ProductID 501.', 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF EXACT_STATE() <> 0
ROLLBACK TRANSACTION;
INSERT INTO dbo.ErrorLog (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, LoggedAt)
VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), SYSUTCDATETIME());
THROW; /* re-raises the original error with its original number, unaltered */
END CATCH;

There are two distinct ways to deliberately raise a custom error, THROW and RAISERROR, and understanding when each is appropriate matters. THROW, introduced in SQL Server 2012, is the modern, simpler, and generally recommended choice, and when called with no arguments inside a CATCH block it re-raises the original error exactly as it was caught, preserving the original error number, message, and line information, which is invaluable for logging and re-raising without losing diagnostic fidelity. RAISERROR is the older mechanism, and while it remains fully supported and offers some capabilities THROW does not, such as inserting formatted parameters directly into the message with printf style placeholders and controlling whether the message is also written to the error log via the WITH LOG option, it does not preserve original error context in the same clean way and its severity and state handling is comparatively fiddly, so the general production guidance is to default to THROW for raising new custom errors and reserve RAISERROR only for the specific cases where its parameter substitution or WITH LOG behavior is genuinely needed.

/* THROW with a custom error number, message, and state, the
modern default for raising a new application-level error */
IF NOT EXISTS (SELECT 1 FROM dbo.Products WHERE ProductID = @ProductID)
THROW 51000, 'ProductID does not exist.', 1;

/* RAISERROR retained for its printf-style parameter substitution
and WITH LOG capability, when those specific features are needed */
RAISERROR ('Insufficient inventory for ProductID %d, requested %d, available %d.',
16, 1, @ProductID, @RequestedQty, @AvailableQty) WITH LOG;

Fuzzy Matching

Real world text data is messy, and exact equality comparisons frequently fail to match records that a human would immediately recognize as the same entity, such as Smith versus Smyth, which is the problem fuzzy matching techniques address.

  • SOUNDEX converts a string into a four character phonetic code based on how the word sounds when spoken in English, so that two differently spelled but similarly pronounced strings, like Robert and Rupert in some cases, can be compared by their SOUNDEX codes rather than their literal characters.
  • DIFFERENCE builds directly on SOUNDEX, returning an integer from zero to four indicating how many of the four SOUNDEX code characters match between two strings, with four meaning a strong phonetic match and zero meaning none, and it is commonly used to rank candidate matches by similarity rather than as a strict filter. Both functions are intentionally simple, English pronunciation oriented heuristics rather than true edit distance algorithms, and SQL Server has no built in Levenshtein distance function, so implementing true Levenshtein edit distance, which counts the minimum number of single character insertions, deletions, and substitutions needed to transform one string into another, requires either a hand written T-SQL scalar function, ideally one written to qualify for scalar UDF inlining on SQL Server 2019 and later, or a CLR based implementation for better performance at scale.
/* SOUNDEX and DIFFERENCE for a phonetic fuzzy name match, ranking
candidates by phonetic similarity rather than requiring an
exact string match */
SELECT
CustomerName,
SOUNDEX(CustomerName) AS PhoneticCode,
DIFFERENCE(CustomerName, 'Jonathan Smith') AS SimilarityScore
FROM dbo.Customers
WHERE DIFFERENCE(CustomerName, 'Jonathan Smith') >= 3
ORDER BY SimilarityScore DESC;

Beyond phonetic matching, the LIKE operator with wildcard characters remains the fundamental T-SQL pattern matching tool, where percent matches any sequence of zero or more characters, underscore matches exactly one character, and a bracketed character set such as square bracket a through z closing bracket matches any single character within that range, with a caret immediately inside the brackets negating the set to mean any character not in that range.

/* LIKE wildcard pattern matching: names starting with J, followed
by any characters, and product codes matching a strict pattern
of three letters then four digits */
SELECT CustomerName FROM dbo.Customers WHERE CustomerName LIKE 'J%';

SELECT ProductCode FROM dbo.Products
WHERE ProductCode LIKE '[A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9]';

Graph Queries

SQL Server’s native graph database features, first introduced in SQL Server 2017, let you model highly interconnected, many to many relationships, such as a social network, a fraud detection network, or a supply chain, directly inside the relational engine rather than reaching for a separate specialized graph database product, while still retaining full transactional consistency, T-SQL tooling, and integration with the rest of your relational schema. A node table, created with the AS NODE clause, represents an entity, such as a Person or a Product, and behaves like an ordinary table for most purposes, automatically gaining a hidden GraphId system column that uniquely identifies it within the graph. An edge table, created with AS EDGE, represents a directed relationship between two nodes, such as Follows or Purchased, and automatically gains hidden from and to system columns that reference the connected nodes, and critically an edge table can also carry its own ordinary attribute columns, such as the date a Follows relationship began, letting relationships themselves hold data the way node entities do.

Get DhanushKumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Querying the graph uses the MATCH clause inside an ordinary SELECT statement, with a distinctive ASCII art style syntax where a node reference, a dash, an edge reference in brackets, another dash, an arrow, and a second node reference visually represents the direction of traversal, for example node1 dash bracket edge bracket dash arrow node2 reading as node1 connects to node2 through edge. For multi hop traversal problems such as finding the shortest path between two people in a social graph, SQL Server provides SHORTEST_PATH as part of the MATCH syntax, which can traverse a variable, unbounded number of hops without the developer needing to write a manual recursive CTE over the edge table.

/* Node tables for the two entity types in a simple social graph */
CREATE TABLE dbo.Person (
PersonID INT PRIMARY KEY,
PersonName NVARCHAR(100)
) AS NODE;

/* Edge table representing a directed Follows relationship,
carrying its own attribute, FollowedSince, beyond the connection */
CREATE TABLE dbo.Follows (
FollowedSince DATE
) AS EDGE;
GO

INSERT INTO dbo.Person VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Carol');

/* $from_id and $to_id are the hidden system columns automatically
present on every edge table, populated from the two node GraphId values */
INSERT INTO dbo.Follows ($from_id, $to_id, FollowedSince)
SELECT p1.$node_id, p2.$node_id, '2025-01-15'
FROM dbo.Person AS p1, dbo.Person AS p2
WHERE p1.PersonName = 'Alice' AND p2.PersonName = 'Bob';
GO
/* MATCH clause querying who Alice follows directly, using the
directional arrow syntax to express the traversal */
SELECT Person1.PersonName AS Follower, Person2.PersonName AS Followed
FROM dbo.Person AS Person1, dbo.Follows AS Follows, dbo.Person AS Person2
WHERE MATCH(Person1-(Follows)->Person2)
AND Person1.PersonName = 'Alice';
GO
/* Shortest path traversal across an unbounded number of hops,
finding whether and how Alice connects to Carol transitively */
SELECT Person1.PersonName, STRING_AGG(Person2.PersonName, ' -> ') AS Path
FROM dbo.Person AS Person1, dbo.Follows FOR PATH AS Follows,
dbo.Person FOR PATH AS Person2
WHERE MATCH(SHORTEST_PATH(Person1(-(Follows)->Person2)+))
AND Person1.PersonName = 'Alice'
GROUP BY Person1.PersonName;

JSON Data

SQL Server does not have a dedicated native JSON data type the way it has XML, and instead JSON is stored and manipulated as ordinary NVARCHAR text, with a purpose built family of functions that parse, validate, query, and generate that text, which is a deliberate and pragmatic design choice that keeps JSON fully compatible with existing text handling, indexing, and replication behavior. ISJSON validates whether a given string is well formed JSON, returning one for valid and zero for invalid, and is the standard guard to use in a CHECK constraint on a column intended to hold JSON, or as a defensive check before attempting to parse untrusted input. JSON_VALUE extracts a single scalar value, such as a string or a number, from a JSON document at a given path expressed with a dollar sign rooted, dot and bracket notation, and it will return NULL, or optionally raise an error, if the path points at an object or an array rather than a scalar. JSON_QUERY, by contrast, extracts an object or an array, meaning a JSON fragment rather than a scalar, and is the correct function whenever the value at the target path is itself a nested structure that you want to return as JSON rather than flatten.

/* Sample JSON document stored in an ordinary NVARCHAR column,
guarded by a CHECK constraint using ISJSON for validity */
CREATE TABLE dbo.CustomerPreferences (
CustomerID INT PRIMARY KEY,
PreferencesJson NVARCHAR(MAX)
CHECK (ISJSON(PreferencesJson) = 1)
);

INSERT INTO dbo.CustomerPreferences VALUES
(1, N'{"theme": "dark", "notifications": {"email": true, "sms": false}, "tags": ["vip", "beta"]}');
/* JSON_VALUE pulls out scalars, JSON_QUERY pulls out the nested
object and array fragments as JSON rather than flattening them */
SELECT
CustomerID,
JSON_VALUE(PreferencesJson, '$.theme') AS Theme,
JSON_VALUE(PreferencesJson, '$.notifications.email') AS EmailOptIn,
JSON_QUERY(PreferencesJson, '$.notifications') AS NotificationsObject,
JSON_QUERY(PreferencesJson, '$.tags') AS TagsArray
FROM dbo.CustomerPreferences;

OPENJSON is the workhorse for turning a JSON array or object into a relational rowset, which is essential whenever a JSON document represents a collection of items, such as an array of order lines embedded in an API payload, that you need to join against or aggregate using ordinary set based SQL. Its default schema returns one row per top level element with generic key, value, and type columns, but the far more useful form supplies an explicit WITH clause describing the target column names, types, and JSON paths, effectively shredding the JSON directly into a typed, relational result set in a single step.

/* OPENJSON shredding a JSON array of order lines directly into
a typed relational rowset using an explicit WITH schema,
which can then be joined, aggregated, or inserted like any table */
DECLARE @OrderJson NVARCHAR(MAX) = N'
[
{"ProductID": 101, "Quantity": 2, "UnitPrice": 19.99},
{"ProductID": 205, "Quantity": 1, "UnitPrice": 49.50}
]';
SELECT *
FROM OPENJSON(@OrderJson)
WITH (
ProductID INT '$.ProductID',
Quantity INT '$.Quantity',
UnitPrice DECIMAL(10,2) '$.UnitPrice'
);

Generating JSON from relational data runs in the opposite direction, using FOR JSON appended to a normal SELECT statement, in either PATH or AUTO mode. AUTO mode infers the JSON structure automatically from the shape of the tables and joins in the query, nesting related tables based on how they were joined, which is fast to write but offers limited control over the exact output shape. PATH mode gives full explicit control, letting you use dot notation in column aliases, such as aliasing a column as Customer.Name, to construct arbitrarily nested JSON objects and arrays precisely as needed, which is the mode generally preferred for producing a JSON payload intended for an external API contract where the exact shape matters.

/* FOR JSON PATH generating a precisely shaped, nested JSON payload,
using dot notation in column aliases to construct nested objects */
SELECT
o.OrderID,
o.OrderDate,
c.CustomerName AS [Customer.Name],
c.Email AS [Customer.Email],
o.TotalAmount AS [Order.Total]
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c ON c.CustomerID = o.CustomerID
FOR JSON PATH, ROOT('Orders');

Regular Expressions and Pattern Matching

T-SQL, unlike languages such as Python or PostgreSQL with its native regex operators, has no built in general purpose regular expression engine, and this is a genuine, important limitation to understand rather than work around with false confidence. What T-SQL offers natively are three narrower tools.

  • LIKE, supports simplified wildcard character sets in square brackets, which can express many common patterns such as validating an alphanumeric code format but cannot express true regex constructs like quantifiers, alternation, or backreferences.
  • PATINDEX extends LIKE style wildcard patterns by returning the starting numeric position of the first match within a string rather than a simple boolean, which is useful for locating where a pattern occurs, for example finding the position of the first digit within a string, rather than merely whether it occurs.
  • STRING_SPLIT, introduced in SQL Server 2016 and enhanced with an ordinal position output column in SQL Server 2022, splits a delimited string into a rowset based on a single character separator, which handles simple delimiter based parsing extremely well but is not itself a regex tool and cannot split on a complex pattern.
/* PATINDEX locating the position of the first digit in a string,
using LIKE-style wildcard pattern syntax rather than true regex */
SELECT PATINDEX('%[0-9]%', 'OrderRef-2026-0042') AS FirstDigitPosition;

/* STRING_SPLIT parsing a comma delimited list into a rowset,
with the SQL Server 2022+ enable_ordinal argument preserving
the original position of each element */
SELECT value, ordinal
FROM STRING_SPLIT('apple,banana,cherry', ',', 1);

When a genuine regular expression, meaning true quantifiers, alternation, capture groups, or backreferences, is required, T-SQL must delegate the work outside its native expression language, and there are two established paths for doing so, each with real operational tradeoffs. A SQLCLR user defined function, written in C sharp against the full .NET regular expression library and deployed into the database as an assembly, gives you complete regex functionality callable as an ordinary scalar function, but SQLCLR must be explicitly enabled at the instance level, it is disabled by default in many hardened environments precisely because it allows arbitrary .NET code execution inside the SQL process, and it introduces a real maintenance and security surface that must be governed carefully, including code signing and permission set considerations in modern SQL Server versions. sp_execute_external_script, part of SQL Server Machine Learning Services, lets you invoke an external R or Python runtime directly from T-SQL, which is a heavier weight, higher latency mechanism appropriate for genuinely complex text processing or when you want to reuse an existing Python regex or NLP pipeline, but it requires Machine Learning Services to be installed and enabled and carries meaningfully more per call overhead than either LIKE or a SQLCLR function, so it is best reserved for batch or analytical workloads rather than a hot, high frequency OLTP path.

/* sp_execute_external_script delegating true regex matching to an
external Python runtime, appropriate for batch/analytical use,
not a low-latency, high-frequency OLTP code path */
EXEC sp_execute_external_script
@language = N'Python',
@script = N'
import re
OutputDataSet = InputDataSet
OutputDataSet["IsValidEmail"] = OutputDataSet["EmailAddress"].apply(
lambda x: bool(re.match(r"^[\w\.-]+@[\w\.-]+\.\w+$", str(x)))
)
',
@input_data_1 = N'SELECT EmailAddress FROM dbo.Customers'
WITH RESULT SETS (( EmailAddress NVARCHAR(200), IsValidEmail BIT ));

Window Functions

A window function computes a value across a set of rows related to the current row, called a window, without collapsing those rows into a single output row the way a GROUP BY aggregate does, which means you can compute a running total, a rank, or a comparison against the previous row while still returning every individual detail row in the result set, and this dual capability, aggregation alongside full row level detail in the same result set, is precisely the problem window functions were introduced to solve. Every window function shares two foundational clauses.

  • PARTITION BY divides the result set into independent groups, resetting the calculation at the start of each group, conceptually similar to
  • GROUP BY but without collapsing rows. ORDER BY, within the OVER clause, defines the logical sequence of rows within each partition, which is what makes ranking and offset style functions meaningful, since ranking a row requires knowing what came before it.

The ranking family assigns a sequential position to each row within its partition based on the ORDER BY sequence, and the four functions differ specifically in how they treat ties. ROW_NUMBER assigns a strictly unique, sequential integer to every row regardless of ties, so two rows with an identical order value still receive different consecutive numbers based on an essentially arbitrary tie break unless the ORDER BY is itself fully unique. RANK assigns the same rank to tied rows but then skips the subsequent rank values by the number of ties, so if two rows tie for rank one, the next row receives rank three rather than two. DENSE_RANK also assigns the same rank to tied rows but does not skip any subsequent values, so two rows tied for rank one are followed immediately by rank two. NTILE divides the partition into a specified number of roughly equal sized buckets and returns the bucket number for each row, which is commonly used to compute quartiles, deciles, or percentile style groupings.

/* Ranking family compared side by side on the same data, making
the tie-handling differences between the four functions visible
directly in the result set */
SELECT
CustomerName,
TotalSpend,
ROW_NUMBER() OVER (ORDER BY TotalSpend DESC) AS RowNum,
RANK() OVER (ORDER BY TotalSpend DESC) AS RankVal,
DENSE_RANK() OVER (ORDER BY TotalSpend DESC) AS DenseRankVal,
NTILE(4) OVER (ORDER BY TotalSpend DESC) AS SpendQuartile
FROM dbo.CustomerLifetimeValue;

Aggregate window functions apply familiar aggregates such as SUM, AVG, and COUNT over the OVER clause’s defined window rather than the whole GROUP BY group, which is what enables patterns like a running total or a percentage of a partition’s total, computed inline alongside the individual detail row, something a plain GROUP BY aggregate simply cannot express since it collapses the detail rows away.

/* Running total per customer using SUM OVER, and each order's
contribution to that customer's overall spend, both computed
alongside the individual order detail row rather than collapsing it */
SELECT
CustomerID,
OrderID,
OrderDate,
TotalAmount,
SUM(TotalAmount) OVER (PARTITION BY CustomerID ORDER BY OrderDate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal,
TotalAmount / SUM(TotalAmount) OVER (PARTITION BY CustomerID) AS PctOfCustomerTotal
FROM dbo.Orders;

The analytic, or offset, family reaches across rows within the window rather than aggregating them. LAG retrieves a value from a specified number of rows before the current row within the partition’s order, and LEAD does the same for a specified number of rows after, both commonly used for period over period comparisons such as computing the change in a metric versus the previous day. FIRST_VALUE and LAST_VALUE return the value from, respectively, the first or last row of the defined window frame, and LAST_VALUE in particular requires careful frame specification to behave as most people intuitively expect, which leads directly into frame specifications generally.

/* LAG comparing each day's revenue against the previous day's,
a classic period-over-period analytic pattern */
SELECT
SaleDate,
DailyRevenue,
LAG(DailyRevenue, 1) OVER (ORDER BY SaleDate) AS PreviousDayRevenue,
DailyRevenue - LAG(DailyRevenue, 1) OVER (ORDER BY SaleDate) AS DayOverDayChange
FROM dbo.DailySalesSummary;

A frame specification, expressed with ROWS or RANGE BETWEEN, narrows the window even further than PARTITION BY and ORDER BY alone, defining exactly which rows relative to the current row participate in the calculation, and getting this right matters because SQL Server’s default frame, when ORDER BY is present but no explicit frame is stated, is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is frequently not what a developer expects and is the classic reason a LAST_VALUE call appears to return the current row’s own value instead of the true last row of the partition, since under the default frame every row’s window only extends up to itself. ROWS defines the frame in terms of a physical row count relative to the current row, such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW for a three row moving average, while RANGE defines the frame in terms of a logical value range relative to the current row’s ORDER BY value, treating rows with a tied ORDER BY value as a single logical unit rather than counting them individually, and ROWS is both the more commonly needed semantics for most reporting scenarios, such as moving averages, and the better performing choice, since RANGE requires the engine to reason about value based ties rather than simple physical row offsets.

/* Explicit frame specifications fixing the two classic pitfalls:
a true moving average using ROWS, and a correct LAST_VALUE using
an explicit UNBOUNDED FOLLOWING frame rather than the misleading default */
SELECT
SaleDate,
DailyRevenue,
AVG(DailyRevenue) OVER (ORDER BY SaleDate
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ThreeDayMovingAvg,
LAST_VALUE(DailyRevenue) OVER (ORDER BY SaleDate
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS TrueLastValueInPartition
FROM dbo.DailySalesSummary;

Conclusion, Trade Offs, and Recommendations

Taken together, these advanced T-SQL techniques form the difference between code that merely produces correct output on a small development dataset and code that is genuinely production ready. Standard CTEs should be the default tool for structuring a complex query into readable, named steps, while recursive CTEs are reserved specifically for hierarchical or graph shaped traversal problems, always guarded with an appropriate MAXRECURSION setting. For existence checks, EXISTS and NOT EXISTS should be the default over IN and especially over NOT IN, both for the correctness guarantee around NULLs and for clarity of intent, with the two often optimizing identically for simple, NOT NULL foreign key cases in modern SQL Server. Every piece of production T-SQL that performs data modification should be wrapped in TRY CATCH with explicit transaction handling, capturing the full ERROR_NUMBER, ERROR_MESSAGE, ERROR_SEVERITY, and ERROR_STATE context, and THROW should be the default choice for raising new errors, with RAISERROR reserved for its specific parameter substitution and WITH LOG capabilities. Fuzzy matching with SOUNDEX and DIFFERENCE is appropriate for lightweight, English pronunciation based matching, while true edit distance or genuine regular expressions require either a hand written function, a SQLCLR assembly with its associated security governance overhead, or delegation to an external runtime via sp_execute_external_script for heavier analytical workloads. Native graph objects are a strong fit whenever a relationship heavy domain would otherwise require deeply nested, hard to maintain recursive joins. JSON functions should be chosen deliberately, JSON_VALUE for scalars, JSON_QUERY for nested fragments, OPENJSON with an explicit WITH schema for shredding into relational rows, and FOR JSON PATH for precise, contract driven JSON generation. Finally, window functions should be the first tool reached for whenever a query needs both aggregation and row level detail simultaneously, such as running totals, rankings, or period over period comparisons, with an explicit ROWS frame specification always preferred over relying on the default RANGE behavior, since the default frame is a well documented and easy to hit source of subtly incorrect LAST_VALUE and windowed aggregate results in production code. As a next step, an engineering team should audit existing stored procedures for NOT IN patterns that could silently break on NULLs, for bare GROUP BY aggregations that could be simplified and made more efficient with a window function instead, and for any hand rolled procedural loops walking hierarchical data that could be replaced outright with a recursive CTE or a native graph MATCH query.

Before you go

  • Please take a moment to like the post and follow the writer!
  • Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute here.

--

--

Written by DhanushKumar

A guy who is curious to learn and blog ... Data Science @Deloitte AI | Data Science | Azure AI

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.