SQL WITH Clause (CTE) ποΈΒΆ
Prerequisites: SELECT Statement, Subqueries
Mentor's Note: Think of the
WITHclause as a "Bookmark". If you have a huge, messy query, you can bookmark a part of it, give it a name, and then use that name later. It turns "Spaghetti Code" into organized logic. π‘
π The Scenario: The Recipe π₯ΒΆ
Imagine you are making a complex dish. - Method A (Subqueries): You try to chop onions, boil water, and fry chicken all in one tiny pan at the same time. (Messy! π€―) - Method B (WITH Clause): 1. Prepare the Sauce. (The Sauce CTE) π₯£ 2. Cook the Meat. (The Meat CTE) π₯© 3. Combine them into the Final Plate. β
π» 1. The Basic SyntaxΒΆ
Example: High Earning FilterΒΆ
-- Scenario: Find employees earning more than 50k and join them with Dept
WITH HighEarners AS (
SELECT emp_name, salary, dept_id
FROM employees
WHERE salary > 50000
)
SELECT H.emp_name, D.dept_name
FROM HighEarners H
JOIN departments D ON H.dept_id = D.id;
π» 2. Why use CTEs? (Benefits) πΒΆ
- Readability: You read the logic from top to bottom.
- No Redundancy: You can reference the same CTE multiple times in one query.
- Replacement for Subqueries: Much easier to debug than nested "Select within Select".
π¨ Visual Logic: The Modular BuildΒΆ
graph TD
A[Step 1: Get Raw Sales] --> B[CTE: SalesData]
C[Step 2: Get Raw Users] --> D[CTE: UserData]
B --> E[Final JOIN: Combine Results]
D --> E
π‘ Interview Tip πΒΆ
"Interviewers often ask: 'Is a CTE permanent?' Answer: NO. A CTE only exists while the query is running. Once the query ends, the bookmark is deleted. Use a
VIEWif you want it to be permanent!"