EXISTS और NOT EXISTS
EXISTS test करता है कि एक subquery कोई rows return करता है या नहीं, जो related data check करने का एक fast तरीका है।
In this page:
Syntax
SELECT columns
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2 t2 WHERE t2.key = t1.key);
EXISTS/NOT EXISTS
EXISTS true return करता है जैसे ही subquery एक row ढूंढे, इसलिए इसे एक full result build करने की ज़रूरत नहीं। NOT EXISTS बिना related rows वाली rows ढूंढता है, और NOT IN के उलट यह NULLs सही तरीके से handle करता है।
EXISTS के अंदर selected columns matter नहीं करते, इसलिए SELECT 1 customary है।
Note:
जब subquery NULLs return कर सकता हो NOT IN से ज़्यादा NOT EXISTS prefer करें।
उदाहरण: EXISTS/NOT EXISTS
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);
INSERT INTO customers VALUES (1,'Ada'),(2,'Bob'),(3,'Cy');
INSERT INTO orders VALUES (10,1),(11,1),(12,3);
SELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) ORDER BY id;
SELECT name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- Output:
-- name
-- Ada
-- Cy
-- name
-- Bob
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. #}
आम गलतियां
- NULLs के साथ NOT IN इस्तेमाल करना
- correlation condition भूल जाना
- EXISTS के अंदर expensive columns select करना
चैप्टर सारांश
- EXISTS true है जब rows exist करें
- NOT EXISTS unmatched rows ढूंढता है
- पहले match पर रुकता है
- NULLs के साथ NOT IN से safer
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: