Re: Place of subselect - Mailing list pgsql-general

From Tom Lane
Subject Re: Place of subselect
Date
Msg-id 14704.1227619180@sss.pgh.pa.us
Whole thread Raw
In response to Place of subselect  ("Guillaume Bog" <guibog@gmail.com>)
List pgsql-general
"Guillaume Bog" <guibog@gmail.com> writes:
> I have performance issues if I do the following pseudo-query:

> SELECT a, b, (SELECT count(*) FROM t2 WHERE something) AS c
> FROM t1 ORDER BY a LIMIT 10;

> After some tests, it seems to me that the subquery on t2 is computed for all
> rows of t1.

Yeah. The SQL specification says that ORDER BY happens after computing
the SELECT output-list.  In some cases that'll get optimized but you
can't count on it.

You can probably improve matters by using a sub-select:

SELECT a, b, (SELECT count(*) FROM t2 WHERE something) AS c
FROM ( SELECT a, b, ... FROM t1 ORDER BY a LIMIT 10 ) ss;

            regards, tom lane

pgsql-general by date:

Previous
From: "Dr.ONE"
Date:
Subject: PostgreSQL 8.3.5 client_encoding WIN1251 trouble
Next
From: Siddharth Shah
Date:
Subject: Effect of stopped status collector process