Which is better CTE or Inner-Selects in PostgreSQL

久未见 提交于 2020-01-26 02:18:09

问题


Given below is a sample of my two different query execution with same result

The select query using inner-select.

   select p.product from
   (
      select * from tbl_a where productid not in (select productid from tbl_b)
   ) p 
   order by p.product

And select query using CTE.

   with cte as 
   (
   select * from tbl_a where productid not in (select productid from tbl_b)
   )
   select product from cte order by product
  • So my question is which among the above is good to use? And At what condition can use each of them?

回答1:


Postgres always materializes CTEs, which means that the CTE version has additional overhead for reading and writing the data. (Note: this is not necessarily true in other databases.) Postgres does not (necessarily) materialize subqueries, so that version should be faster.

A better way to write this query is to dispense with the subquery/CTE entirely:

  select a.product
  from tbl_a a
  where a.productid not in (select productid from tbl_b)
  order by a.product;

(I am ignoring whether not exists or left outer join would actually be better than not in.)

There is not a general rule for using CTEs instead of subqueries when writing queries. It depends on a lot of factors, especially whether the underlying tables are indexed and how many times the CTE would appear in the query.



来源:https://stackoverflow.com/questions/25664263/which-is-better-cte-or-inner-selects-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!