Updating Data In Common Table Expressions

Kenneth Fisher shows that you can directly update a table referenced in a common table expression:

CTEs are cool things. You can essentially create one or more in-line view(s) within your query. One thing that isn’t overly well known is that you can actually update the data within the CTE. No, I don’t mean using using the UPDATE statement with a CTE but actually running the update through the CTE.

This is really powerful when combined with window functions, like only updating the first record given a particular partition.  You can also delete, which makes duplicate detection and deletion fairly straightforward.

Related Posts

The Power Of Window Functions

Ben Richardson has an introduction to the concept of window functions: This is a much more efficient result. In the first line of the script the id, name and gender columns are retrieved. These columns do not contain any aggregated results. Next, for the columns that contain aggregated results, we simply specify the aggregated function, […]

Read More

Visualizing Types Of Joins

Daniel Hutmacher has a nice PDF cheat sheet showing different types of joins: How it works: For each join example, there are two tables, the left and the right table, shown as two columns. For the sake of simplicity, these tables are called “a” and “b” respectively in the code. You’ll notice that the sheet […]

Read More


October 2017
« Sep Nov »