WITH (CTE) का उपयोग
एक CTE WITH से एक subquery को नाम देता है ताकि आप इसे reuse कर सकें और queries top to bottom पढ़ सकें।
In this page:
Syntax
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)
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
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह मान लेना कि CTEs हमेशा materialised हैं
- छोटी queries के लिए CTEs इस्तेमाल करना जो noise add करती हैं
- 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: