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

EXISTS और NOT EXISTS

EXISTS test करता है कि एक subquery कोई rows return करता है या नहीं, जो related data check करने का एक fast तरीका है।

In this page:

  1. EXISTS/NOT EXISTS
Syntax
sql
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

sql
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
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. NULLs के साथ NOT IN इस्तेमाल करना
  2. correlation condition भूल जाना
  3. 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:

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.