Using a CTE with a DELETE Statement in SQL Server to Remove Duplicates

Common Table Expressions (CTEs) are a nifty SQL feature that allow us to define a temporary result set, which can then be used in subsequent queries, including DELETE statements. In the context of removing duplicate data, a CTE can be helpful when we want to identify and remove only the duplicated rows, keeping one version of each unique record.

Let’s go through a step-by-step example of using a CTE with a DELETE statement to remove duplicate data.

Continue reading

Understanding Common Table Expressions (CTEs): A Beginner’s Guide

Common table expressions (CTEs) are a feature that we can use in SQL to help simplify complex queries and enhance readability. They can help with things like code readability, performance, recursive queries, and more.

This article explores what CTEs are, their syntax, types, use cases, and best practices, along with examples to help illustrate their usage.

Continue reading

Fix Error “The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions…” in SQL Server (Error 1033)

If you’re getting an error that reads “The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified” in SQL Server, it appears that you’re using the ORDER BY clause in a place that it must also be accompanied by a TOP, OFFSET or FOR XML clause, but you’re not including one of those clauses.

To fix this issue, be sure to include one of those clauses in your query if you need to use the ORDER BY clause.

Continue reading