PostgreSQL – EXISTS Operator
In PostgreSQL, the EXISTS operator is used to test for the existence of rows in a subquery.It is generally used with correlated subqueries. If the subquery returns at least one row, the result of EXISTS is true. In case the subquery returns no row, the result is of EXISTS is false.
Syntax: EXISTS (subquery)
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.
Example 1: Here we will query for customers who have at least one payment whose amount is greater than 9 USD using the “customer” and “payment” tables of our sample database.
FROM customer c
FROM payment p
WHERE p.customer_id = c.customer_id
AND amount > 9 )
ORDER BY first_name,
Example 2: Here we will query for films that are not available in the inventory using the “film” and “inventory” tables of our sample database.
FROM film f
WHERE NOT EXISTS
FROM inventory i
WHERE f.film_id = i.film_id )
ORDER BY title;
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!