

For our first query, that will look like this: But usually the solution is to convert the subquery into a join. If correlated scalar subqueries are bad for performance, how can we avoid them? There is no single, straightforward answer, and you probably won’t be able to rewrite the query to avoid such subqueries in all cases. Rewriting a scalar subquery in the SELECT list or WHERE clause However, if table “ a” is large, even a fast subquery will make the query execution unpleasantly slow. This can be fine if “ a” is a small table (remember, my recommendation is just a rule of thumb). For example, PostgreSQL will execute the subquery from the first section once for each row in table “ a”. The reason is that PostgreSQL can only execute a scalar subquery as a nested loop. My rule of thumb is: avoid correlated scalar subqueries whenever you can. Scalar subqueries usually are a performance problem an EXISTS or NOT EXISTS expression: WHERE NOT EXISTS (SELECT.an IN or NOT IN expression: WHERE a.x IN (SELECT.a common table expression (CTE): WITH q AS (SELECT.

If the query returns more than a single row, you will receive a run-time error:ĮRROR: more than one row returned by a subquery used as an expressionĪ tabular subquery appears in a context where it can return more than one value: If a scalar subquery returns no result, the resulting value is NULL. An example for a scalar subquery is the one in the previous section. If you write a subquery in a place in an SQL statement where you would otherwise have to write a single value, it is a scalar subquery. In the rest of this article, I will mostly deal with correlated subqueries. Uncorrelated subqueries are almost never a performance problem. You can see that as an InitPlan (initial plan) in the output of EXPLAIN. If the PostgreSQL optimizer does not “pull it up” (integrate it in the main query tree), the executor will calculate it in a separate step. An uncorrelated subquery is one that does not reference anything from the outside. Such a subquery is usually called a correlated subquery. The subquery will be different for each row in “ a”. In a subquery you can use table columns from the outside, like I’ll start simple, but get to more surprising and complicated topics later.
POSTGRESQL FOR LOOP HOW TO
In this article, I want to tell you how to write subqueries that perform well. But I don’t want to discuss the beauty or ugliness of SQL. This makes SQL a powerful language – and one that can be hard to read. ), and you can use it in arbitrary expressions. All you have to do is surround the query with parentheses, like (SELECT. SQL allows you to use subqueries almost anywhere where you could have a table or column name.
