[SQL] SQL Common Table Expressions (CTEs) for Beginners: Think in Steps, Not in Circles

 


This post breaks down the concept of Common Table Expressions (CTEs) using a simple "kitchen prep" analogy. It provides a side-by-side look at raw data, the CTE logic, and the final SQL query to help readers understand how to organize their data pipelines more effectively.


What is a Common Table Expression (CTE)?

A Common Table Expression (CTE) is a temporary, named result set in SQL that exists only for the duration of a single query. You can think of it as a "virtual table" or a "named subquery" that helps break down complex logic into smaller, more readable steps.


Key Characteristics
  • Temporary Scope: It is created when the query starts and disappears as soon as the query finishes executing.
  • Syntax: Defined using the WITH keyword at the very beginning of your SQL statement.
  • Named & Reusable: Unlike standard subqueries, a CTE is assigned a specific name and can be referenced multiple times within the same main query.




Think of a Common Table Expression (CTE) as a "temporary result shelf"
Imagine you are cooking a complex meal. Instead of trying to chop veggies, sear meat, and boil pasta all in one giant pot at the exact same time, you chop the veggies first and put them in a temporary bowl on the side. When you're ready, you grab that bowl and add it to the main dish.
In SQL, a CTE is that temporary bowl. It holds a sub-result so you can reference it easily in your main query.

The Syntax
You start a CTE with the word WITH.
WITH MyTemporaryBowl AS (
    -- Your "chopping" query goes here
    SELECT ...
)
-- Your "main cooking" query goes here
SELECT * FROM MyTemporaryBowl;


Real-World Example
Let’s say we have a table of Sales:



Goal: Find employees who sold more than the average total sales per person.


Step 1: Create the CTE (The "Bowl")
First, we calculate the total sales for everyone.
WITH TotalSalesCTE AS (
    SELECT Employee, SUM(SaleAmount) AS Total
    FROM Sales
    GROUP BY Employee
)

At this point, TotalSalesCTE looks like this:




Step 2: Use it in the Main Query
Now we use that "bowl" to filter the results.
WITH TotalSalesCTE AS (
    SELECT Employee, SUM(SaleAmount) AS Total
    FROM Sales
    GROUP BY Employee
)
SELECT Employee, Total
FROM TotalSalesCTE
WHERE Total > (SELECT AVG(Total) FROM TotalSalesCTE);


Final Result:



Conclusion
CTEs don't make your database faster, but they make you faster. They turn "spaghetti code" into a organized, step-by-step recipe that anyone on your team can follow.

Comments

All Categories

Call Fusion BIP Report2 Change Password1 Code Combinations2 Compute Instance2 CTE1 Customer1 Data Aggregation2 Database5 Date Conversion1 DB Adapter2 Decryption1 Development1 EBS4 Encryption1 ESS Jobs3 Examine1 FBDI3 Fusion APIs1 Fusion BIP7 GIT2 GL3 GL Journals1 GL_DAILY_CONVERSION_TYPES1 GL_DAILY_RATES1 ICS1 Identity Domain1 Integrations1 Java1 Journal Import1 Keys1 Legal Entity1 LookupTypeLOV1 LOV1 LOVs1 MultiPartAPIs1 Networking1 NVL2 NVL in OIC2 OCI12 OCI Billing1 OCI Compute5 OCI Cost Management1 OCI Events Service1 OCI Free Tier3 oci networking1 OCI Notifification Service1 OCI Security3 OIC4 OIC Mapper2 Oracle26 Oracle ADF17 Oracle APEX1 Oracle Apps59 Oracle Apps R126 Oracle ATP1 Oracle BIP8 Oracle Cloud13 Oracle Cloud Free Tier1 Oracle cloud Infrastructure10 Oracle Cloud Security2 Oracle Cloud VM1 Oracle DB4 oracle ebs5 Oracle ERP4 Oracle ERP Adapter2 Oracle ERP Cloud7 Oracle financials2 Oracle Forms1 Oracle Fusion57 Oracle Fusion BIP4 Oracle Fusion ERP17 Oracle Fusion Financials18 Oracle Integration Cloud3 Oracle OAF17 Oracle OCI14 Oracle OIC22 Oracle SOA 12c10 Oracle SQL17 Oracle VBCS1 Oracle VBS2 Oracle Visual Builder Cloud Service1 Oracle Visual Builder Studio2 Oracle Workflow Notifications1 Others10 Payables2 Payables Import1 Properties1 R121 Register BIP as ESS Job1 Reset Password1 Responsibility1 REST4 Security List1 Site Map1 SOAP2 SOAP API2 SOAP UI3 SQL16 SQL Functions3 SQL Queries14 SQL Query8 SQL Tips3 SSH1 TCA1 Value Sets1 VBCS1 vcn1 Virtual Machine2 Virtual Machines1 XML1 XSLT1
Show more