How to run your CTE just once, and re-use the output

You may already know that common table expressions, like views, don’t behave like regular tables. They’re a way to make your query more readable by allowing you to write a complex SQL expression just once, rather than repeating it all over your statement or view. This makes reading, understanding and future refactoring of your code a little less painful.

But they’re no magic bullet, and you may end up with some unexpected execution plans.

How to build a histogram in T-SQL

Talk to SQL Server developers or DBAs aboutĀ histograms, and they’ll inevitably think of index statistics. However, a task you may encounter some day is to calculate the distribution of numbersĀ in a table. And although there’s no quick built-in function to do this, it’s not as difficult as you may think.