← Back to PostgreSQL Course | Chapter 8: Subqueries & CTEs | Lesson 5 of 7

WITH (CTE) का उपयोग

एक CTE WITH से एक subquery को नाम देता है ताकि आप इसे reuse कर सकें और queries top to bottom पढ़ सकें।

In this page:

  1. WITH (CTE)
Syntax
sql
WITH cte_name AS (
  SELECT columns FROM table_name WHERE condition
)
SELECT columns FROM cte_name;

WITH (CTE)

WITH name AS (SELECT ...) एक temporary named result define करता है जिसे main query reference कर सकती है, कई बार भी। कई CTEs commas से separated होते हैं और earlier वालों को reference कर सकते हैं।

CTEs complex queries को readable बनाते हैं। PostgreSQL 12 से ये एक बार reference होने पर inline होते हैं, जब तक MATERIALIZED specify न किया जाए।

Note: PostgreSQL 12 और बाद में CTE optimisation control करने के लिए MATERIALIZED या NOT MATERIALIZED इस्तेमाल करें।

उदाहरण: WITH (CTE)

sql
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total INTEGER);
INSERT INTO orders VALUES (1,'Ada',50),(2,'Bob',20),(3,'Ada',70),(4,'Cy',10),(5,'Bob',95);
WITH totals AS (SELECT customer, SUM(total) AS spent FROM orders GROUP BY customer),
     big AS (SELECT customer, spent FROM totals WHERE spent >= 100)
SELECT customer, spent FROM big ORDER BY spent DESC;

-- Output:
-- customer | spent
-- Ada | 120
-- Bob | 115
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि CTEs हमेशा materialised हैं
  2. छोटी queries के लिए CTEs इस्तेमाल करना जो noise add करती हैं
  3. CTEs के बीच comma भूल जाना
चैप्टर सारांश
  • WITH name AS (query) syntax इस्तेमाल होता है
  • Main query से reusable
  • कई CTEs comma separated हैं
  • Readability improve करता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.