# SQL Server Patterns Worth Catching in Code Review at SQLDay Lite 2026

Mariusz Wójcik's SQLDay Lite 2026 session in Gdańsk: nine reproducible SQL Server patterns that pass code review, with fixes and reviewer checklists.

Some sessions you can take straight back to your team's next pull request, and "SQL Anti-Patterns That Survive Code Reviews" by Mariusz Wójcik is one of them. Mariusz, Senior Azure Architect and board member of Data Community Poland, brought it to SQLDay Lite 2026, which Data Community Poland organized at the Gdańsk University of Technology on 24-25 September 2026.

The idea behind the session is simple and useful: some T-SQL looks completely reasonable, runs without an error, and still does something other than what its author intended. Those are exactly the patterns a reviewer reads past. Mariusz collected nine of them in a public repository of reproducible demos built on the AdventureWorks sample database, each paired with a fix and a checklist a reviewer can use the next time a pull request lands.

## A reviewer's format: assumption, cause, fix, checklist

Every script in the [session repository](https://github.com/MariuszWojcikDC/SQL-Anti-Patterns-That-Survive-Code-Reviews) follows the same structure. It opens with the assumption a developer reasonably makes, for example that ISNULL returns its second argument with that argument's type and length. It then sets up a business scenario, reproduces the behavior, explains the cause with a link to Microsoft Learn, and shows a fix. It closes with a short checklist of questions for review.

Stating the assumption in plain words lets a team recognize its own habits, and the checklists turn each example into a review habit rather than trivia. Each script also cleans up after itself, so the examples are easy to run on a test instance.

## When the data type quietly decides the result

The ISNULL example builds a person-label export from Person.Person. It uses Title, or FirstName when Title is missing. Title is nvarchar(8), FirstName is nvarchar(50), and ISNULL takes its type and length from the first argument. The result: first names longer than eight characters are cut to eight, with no error, and SELECT INTO carries the short nvarchar(8) type into the new table. The fix widens the first argument before the expression is evaluated, as in Mariusz's demo script:

```
ISNULL(CAST(p.Title AS nvarchar(50)), p.FirstName) AS DisplayValue
```

```
ISNULL(CAST(p.Title AS nvarchar(50)), p.FirstName) AS DisplayValue
```

```
ISNULL(CAST(p.Title AS nvarchar(50)), p.FirstName) AS DisplayValue
```

The script points out that casting the finished result cannot bring back text that has already been truncated. The width has to be set on the way in.

COALESCE works differently. Its result type follows data type precedence across all arguments, not the argument that supplies the value. In the demo, an export wants ProductNumber and falls back to ProductID. Because int ranks above nvarchar, SQL Server tries to convert a value like AR-5381 to int and stops with error 245. Converting ProductID to nvarchar(25) inside the COALESCE keeps both arguments in the agreed domain.

The first script in the repository shows a related surprise in table creation. SELECT INTO from Sales.SalesOrderHeader carries the IDENTITY property of SalesOrderID into the new staging table. A later INSERT ... EXEC without a column list then raises error 213, because the target has only two ordinary writable columns for three incoming values. The recommended fix is an explicitly defined staging table with agreed types and nullability, plus an explicit INSERT column list. As the script puts it, the visible column count is not the insert contract.

## Context that changes what a query means

The first is an unqualified column in a subquery. Sales.SalesOrderDetail has no CustomerID column, so selecting it on its own raises error 207. Inside a subquery, though, SQL Server also looks one level up, and CustomerID binds to the outer Sales.Customer table. The demo shows the consequence: the IN query returns every customer and the NOT IN query returns none, without comparing any order data. Qualifying the column as sod.CustomerID makes the typo visible immediately. The guidance is to qualify every column in a subquery with an alias, including outer references, which matches Microsoft's own recommendation on [qualifying column names in subqueries](https://learn.microsoft.com/sql/relational-databases/performance/subqueries).

The second is collation in temporary tables. A #temp column created without COLLATE inherits tempdb's default collation, not the user database's. A join between imported postal codes and Person.Address works where the two match, and the same unchanged query can raise a collation conflict after the database moves to an instance with different defaults. Declaring the column with COLLATE database_default ties it to the current database's default. The checklist adds a point that is easy to miss: the choice of collation also decides whether letters and accents compare as equal, which is a business question as much as a technical one.

## COALESCE does more than pick the first non-NULL value

First, COALESCE is expanded into a CASE expression, so an argument containing a subquery may run twice. The demo picks one of two orders at random with ORDER BY NEWID(): order 43659 with SalesPersonID 279, and order 43697 with no salesperson. The fallback is 1. If the first evaluation returns 279, the THEN branch is chosen, and the subquery runs again. If that second run picks the order without a salesperson, the whole expression returns NULL despite the explicit fallback. Running the batch 100 times with GO 100 makes the effect easy to observe. The fix is to evaluate the selection once, store the result, and apply COALESCE to the stored value.

Second, as shown above, the result type follows data type precedence. Third, nullability metadata differs: a computed column defined as COALESCE(SalesPersonID, 0) is described as nullable, while ISNULL(SalesPersonID, 0) is NOT NULL, even though both return exactly the same values. Only the ISNULL column can be part of a primary key. The script is careful to say this does not make ISNULL a universal replacement: its own type and length rules apply, and 0 must not be a valid SalesPersonID.

## What the schema guarantees versus what the data happens to contain

Two examples deal with rules a team believes are enforced but are not.

In HumanResources.EmployeeDepartmentHistory, the primary key includes BusinessEntityID, StartDate, DepartmentID and ShiftID. A query for employees with more than one active department returns nothing, which looks reassuring. The demo then inserts, inside a transaction that is rolled back, a second active assignment for the same employee that differs only in department, and the database accepts it. One comment in the script captures the lesson well: "An empty result describes the data, not a schema guarantee." If only one open assignment is allowed, a unique filtered index on BusinessEntityID where EndDate IS NULL enforces it. If several are valid, the reports must handle a one-to-many relationship. Either way, the business has to decide.

The concurrent-load example looks at ID generation. Two ETL processes number their batches with MAX(LoadRowID) plus ROW_NUMBER(), both read the same maximum, and both propose IDs 3 and 4. The primary key protects uniqueness and rejects the second batch, but it does not generate or reserve numbers. The script recommends letting IDENTITY assign values, or using a SEQUENCE with NEXT VALUE FOR when there is a valid reason to avoid IDENTITY, and keeping the primary key as the final guarantee. It also notes that neither IDENTITY nor SEQUENCE promises gapless numbering, since a rollback or outage can consume a value.

## Planning ahead for the int limit

The most extensive demo addresses a fact table whose int IDENTITY key reaches 2,147,483,647, after which the next INSERT raises error 8115. Altering a large table to bigint can mean long locks, extra space and log growth, so the script shows a staged migration that keeps the loading process running:

- create an empty table with the same columns, a bigint key and an IDENTITY seed of 2,147,483,648, so old and new IDs never overlap
- rename the old table and create a view under its former name that combines both tables with UNION ALL
- add an INSTEAD OF INSERT trigger on the view that routes new facts to the bigint table
- move history in small batches with IDENTITY_INSERT, copying and deleting each batch in one transaction
- once the archive is empty, remove the view and trigger and give the bigint table the original name

The script flags what matters in production: SCOPE_IDENTITY() sees a different scope once the insert runs inside a trigger, and dependencies such as foreign keys, indexes and permissions need checking before cutover. Mariusz credits Brian McMeans' post [Running Out of INT](https://thevikingdba.blogspot.com/2026/08/running-out-of-int-v.html) as a source for this pattern.

## Validating imported text with more than ISNUMERIC

The last example looks at a CSV importer that receives quantities, dates, postal codes and times as text. ISNUMERIC returns 1 when a value can be converted to any numeric type, which includes scientific notation like 1e4, currency symbols and even a lone plus or minus sign. A digit string such as 20240229 or 235959 passes, even though it is a date or a time, while the valid Polish postal code 50-120 does not. Converting the US postal code 02138 to a number also drops its leading zero.

The recommended approach is TRY_CONVERT to the exact target type, followed by rules for the field's format and range. The script makes a point worth repeating: a NULL from TRY_CONVERT signals a value to handle, not one to discard quietly.

## A checklist for your next review

Drawn from the checklists in the repository:

- Check the type of an expression, not only the types of its columns, especially with ISNULL, COALESCE and SELECT INTO.
- Qualify every column in a subquery with a table alias.
- Declare collation on #temp text columns, and test after restoring on the target instance.
- Ask which constraint actually enforces a business rule, rather than relying on today's data.
- Let IDENTITY or SEQUENCE assign IDs when several processes load in parallel.
- Track how far each IDENTITY column is from its type's limit, and plan the migration early.
- Validate imported text with TRY_CONVERT and domain rules, and keep the original value and rejection reason.

## When review ends, the data keeps the record

What stands out across the nine examples is how many of them produce no error at all. A truncated first name, a subquery that returns every customer, a postal code without its leading zero, a second active assignment: each one lands in a table as a perfectly valid-looking row. Code review is the first line of defense, and Mariusz's checklists make it a much stronger one. The second line is watching the data that the code produces.

That is where data quality monitoring complements review. Shifts in value lengths, null rates, row counts and distributions are often the first visible sign that an expression behaves differently from what its author expected, and validation rules can encode the business decisions the session keeps returning to, such as one open assignment per employee or a postal code format that keeps its zeros. digna does this for [SQL Server data quality](/integrations/sql-server) directly inside the SQL Server environment, so the checks run where the data lives.

Many thanks to Mariusz Wójcik for a set of examples that any SQL Server team can run, discuss and turn into better reviews, and to Data Community Poland for organizing [SQLDay Lite 2026](https://sqlday.pl/lite) in Gdańsk. All nine demo scripts, with their scenarios, fixes and checklists, are available in Mariusz's [GitHub repository](https://github.com/MariuszWojcikDC/SQL-Anti-Patterns-That-Survive-Code-Reviews).

## Frequently asked questions

### What SQL anti-patterns survive code reviews?

Nine T-SQL patterns that run without errors yet do something unintended, such as ISNULL truncating values, unqualified subquery columns binding to the outer table, tempdb collation conflicts, MAX plus ROW_NUMBER ID generation and ISNUMERIC validation. Mariusz Wójcik published reproducible AdventureWorks demos for all nine, each with a fix and a reviewer checklist.

### Why does ISNULL truncate strings in SQL Server?

ISNULL takes its data type and length from the first argument, not from the value it returns. In the session's demo, Title is nvarchar(8) and FirstName is nvarchar(50), so first names longer than eight characters were cut to eight without any error. Casting the first argument to nvarchar(50) fixes it; casting the result afterwards cannot.

### Can COALESCE return NULL even with a non-NULL fallback?

Yes, when an argument contains a subquery. SQL Server expands COALESCE into a CASE expression, so that subquery may run twice. In the demo, a random ORDER BY NEWID() pick first returned SalesPersonID 279, a second run chose an order without a salesperson, and the result was NULL despite the fallback of 1.

### How can an int IDENTITY key be migrated to bigint while loads keep running?

The session shows a staged migration. Create a bigint table seeded at 2,147,483,648, rename the old table, put a UNION ALL view under its name with an INSTEAD OF INSERT trigger routing new rows, then move history in small IDENTITY_INSERT batches before giving the bigint table the original name.

### Why is ISNUMERIC not enough to validate imported text?

Because ISNUMERIC returns 1 for anything convertible to any numeric type, including 1e4, currency symbols and a lone plus or minus sign. It accepts 20240229, which is a date, yet rejects the valid Polish postal code 50-120. The recommended approach is TRY_CONVERT to the exact target type, plus format and range rules.
