0
0
PostgreSQLquery~5 mins

Correlated subqueries execution model in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a correlated subquery in SQL?
A correlated subquery is a subquery that refers to a column from the outer query. It runs once for each row processed by the outer query.
Click to reveal answer
intermediate
How does PostgreSQL execute a correlated subquery?
PostgreSQL executes the correlated subquery once for each row of the outer query, using the current row's values to evaluate the subquery.
Click to reveal answer
intermediate
Why can correlated subqueries be slower than non-correlated subqueries?
Because the correlated subquery runs repeatedly for each row of the outer query, it can cause many executions and slow down the query.
Click to reveal answer
beginner
What is an example of a correlated subquery condition?
Example: SELECT e1.name FROM employees e1 WHERE e1.salary > (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department = e1.department); Here, the subquery uses e1.department from the outer query.
Click to reveal answer
advanced
How can you optimize queries with correlated subqueries in PostgreSQL?
You can rewrite correlated subqueries as JOINs or use WITH clauses (CTEs) to reduce repeated executions and improve performance.
Click to reveal answer
What does a correlated subquery depend on?
AColumns from the outer query
BOnly constants
COnly aggregate functions
DNo external references
How often is a correlated subquery executed in PostgreSQL?
AOnce for the entire query
BOnly once per table
COnce per row of the outer query
DNever executed
Which SQL clause often contains a correlated subquery?
AWHERE
BFROM
CGROUP BY
DORDER BY
What is a common way to improve performance of correlated subqueries?
AUse indexes on unrelated columns
BAdd more correlated subqueries
CUse SELECT * always
DRewrite as JOINs or CTEs
In the example: SELECT e1.name FROM employees e1 WHERE e1.salary > (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department = e1.department); what is the role of e1.department?
AIt is a constant value
BIt links the subquery to the outer query
CIt is ignored
DIt is an aggregate function
Explain how PostgreSQL executes a correlated subquery and why it might affect performance.
Think about how many times the subquery runs.
You got /3 concepts.
    Describe a strategy to optimize a query that uses a correlated subquery in PostgreSQL.
    Consider alternative SQL structures.
    You got /3 concepts.