Categories
SQL

Why TOP (1) Can Return Multiple Rows (and Why That Matters)

Having TOP (1) return multiple rows feels wrong… but that’s what WITH TIES can do. For a long time I used patterns like this to get the first record in a group: Then I found the cleaner alternative: Let’s dive into what it is, and why you (probably) shouldn’t use it. WITH TIES The WITH TIES syntax was added over 20 years ago but it […]

Categories
SQL

Bringing Uniqueness with a CTE Sequence

Uniqueness is something we like to reinforce within data. Sometimes the uniqueness will mean we reject data, but other times we want to make it unique. Let’s consider an account name or an order reference. We wouldn’t want to simply reject an account or an order, we want to ensure they’re unique. A typical approach […]

Categories
SQL

Dealing with Duplicate Data

Data quality and consistency is key to the services we support and solutions we deliver. A gremlin which can undermine that is duplicate data. Let’s start the new year dealing with duplicate data and having a good clear-out. For our example we’ll consider an Order Product table which contains an OrderID and ProductID, and the combination of these should […]

Categories
SQL

Recursive Functions and Limitations

When writing functions within SQL Server we sometimes have need to repeat an action multiple times until a given condition is met – also known as Recursion. There are a couple of common ways which this can be implemented which also have their different limitations. A little about recursion Firstly, why do we need recursion? […]