0
0
PostgreSQLquery~5 mins

Subqueries with EXISTS in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the SQL keyword EXISTS do in a query?

EXISTS checks if a subquery returns any rows. If it does, the condition is true; if not, it is false.

Click to reveal answer
intermediate
How does a subquery with EXISTS differ from a normal join?

A subquery with EXISTS only checks for the presence of rows, not the actual data. A join combines rows from two tables based on a condition.

Click to reveal answer
beginner
Write a simple example of a query using EXISTS to find customers who have orders.
SELECT customer_name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
Click to reveal answer
beginner
Why is SELECT 1 often used inside an EXISTS subquery?

Because EXISTS only cares if rows exist, not the data itself. SELECT 1 is simple and efficient.

Click to reveal answer
intermediate
Can EXISTS subqueries improve performance compared to joins? Why or why not?

Yes, sometimes. EXISTS stops searching as soon as it finds a matching row, which can be faster than joining all rows.

Click to reveal answer
What does the EXISTS keyword check in a SQL query?
AIf the main query has any rows
BIf the subquery returns any rows
CIf the subquery returns a specific column value
DIf the tables are joined correctly
Which of the following is a valid use of EXISTS?
ASELECT * FROM table WHERE EXISTS (SELECT 1 FROM other_table WHERE condition);
BSELECT * FROM table WHERE EXISTS = 5;
CSELECT * FROM table WHERE EXISTS table.column;
DSELECT * FROM table WHERE EXISTS (table.column = 1);
What will this query return?<br>
SELECT name FROM students s WHERE EXISTS (SELECT 1 FROM enrollments e WHERE e.student_id = s.id);
AStudents who have at least one enrollment
BAll students regardless of enrollment
CEnrollments without students
DStudents with no enrollments
Why might SELECT 1 be preferred inside an EXISTS subquery?
ABecause it counts the rows
BBecause it returns the first row only
CBecause <strong>EXISTS</strong> ignores the selected columns
DBecause it filters rows
Which is true about EXISTS subqueries?
AThey return all rows from the subquery
BThey always return false
CThey join tables like INNER JOIN
DThey return true if the subquery has any rows
Explain how the EXISTS keyword works in SQL and give a simple example.
Think about checking if something exists rather than retrieving data.
You got /3 concepts.
    Describe a situation where using EXISTS might be better than using a JOIN.
    Consider when you only want to know if related data exists.
    You got /3 concepts.