Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
SQL

SQL: Use CTEs for Readable Complex Queries

- 07.07.26 - ErcanOPAK

📊 CTE = Readable Complex Queries

Nested subqueries are messy. CTEs make queries readable. Break complex queries into steps. Essential for maintainable SQL.

📝 CTE Syntax

WITH cte_name AS (
    SELECT column1, column2
    FROM table
    WHERE condition
)
SELECT *
FROM cte_name
WHERE another_condition;

-- Multiple CTEs
WITH
    cte1 AS (
        SELECT ... 
    ),
    cte2 AS (
        SELECT ...
    )
SELECT ...
FROM cte1
JOIN cte2 ON cte1.id = cte2.id;

-- Recursive CTE
WITH RECURSIVE cte AS (
    -- Anchor
    SELECT id, name, parent_id, 1 as level
    FROM categories
    WHERE parent_id IS NULL
    
    UNION ALL
    
    -- Recursive
    SELECT c.id, c.name, c.parent_id, cte.level + 1
    FROM categories c
    JOIN cte ON c.parent_id = cte.id
)
SELECT * FROM cte;

🎯 Practical CTE Examples

-- Customer order summary
WITH customer_orders AS (
    SELECT 
        customer_id,
        COUNT(*) as order_count,
        SUM(total) as total_spent,
        AVG(total) as avg_order
    FROM orders
    GROUP BY customer_id
),
premium_customers AS (
    SELECT *
    FROM customer_orders
    WHERE total_spent > 1000
)
SELECT 
    u.name,
    u.email,
    p.order_count,
    p.total_spent,
    p.avg_order
FROM users u
JOIN premium_customers p ON u.id = p.customer_id
ORDER BY p.total_spent DESC;

-- Monthly sales report
WITH monthly_sales AS (
    SELECT 
        DATE_TRUNC('month', order_date) as month,
        SUM(total) as revenue
    FROM orders
    WHERE order_date >= '2024-01-01'
    GROUP BY DATE_TRUNC('month', order_date)
),
sales_growth AS (
    SELECT 
        month,
        revenue,
        LAG(revenue) OVER (ORDER BY month) as prev_month_revenue
    FROM monthly_sales
)
SELECT 
    month,
    revenue,
    prev_month_revenue,
    CASE 
        WHEN prev_month_revenue IS NULL THEN NULL
        ELSE ((revenue - prev_month_revenue) / prev_month_revenue) * 100
    END as growth_percent
FROM sales_growth;

-- Employee hierarchy
WITH RECURSIVE employee_hierarchy AS (
    -- Anchor: Top-level employees
    SELECT 
        id,
        name,
        manager_id,
        1 as level,
        name as path
    FROM employees
    WHERE manager_id IS NULL
    
    UNION ALL
    
    -- Recursive: Subordinates
    SELECT 
        e.id,
        e.name,
        e.manager_id,
        eh.level + 1,
        eh.path || ' → ' || e.name
    FROM employees e
    JOIN employee_hierarchy eh ON e.manager_id = eh.id
)
SELECT 
    REPEAT('  ', level) || name as hierarchy,
    level,
    path
FROM employee_hierarchy
ORDER BY path;

💡 CTE Benefits

  • Readable and maintainable
  • Break complex queries
  • Recursive queries
  • Reusable in query
  • Better than subqueries

“CTEs make SQL readable. Break down complexity. Essential for maintainable queries.”

— SQL Developer

Related posts:

How to get the first and last date of the current year in SQL

How to get the first and last date of the current year in SQL

SQL Server — GETDATE() Breaks Deterministic Queries

SQL Server — GETDATE() Breaks Deterministic Queries

SQL Server: Fix a Columnstore Index That Silently Falls Back to Row-by-Row Inserts Because Rows Arri...

SQL Server: Fix a Columnstore Index That Silently Falls Back to Row-by-Row Inserts Because Rows Arri...

Views: 6

Post navigation

.NET Core: Build Web UI with Razor Pages
C#: Use Generics for Type-Safe Reusable Code

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (482)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com