postgresql - Will Postgres CTE read all rows even if it doesn't have to? -


will query read rows big_table or needed rows?

with tmp (select * big_table) select *     small_table st join tmp on tmp.id = st.bigtableid st.id = 45 

would sub select perform better?

select *     small_table st join (select * big_table) tmp on tmp.id = st.bigtableid st.id = 45 

i it's possible write bit more readable queries using with, not if cost worse performance.

the query in cte executed autonomically (without conditions consecutive queries) in case described in question query cte slower other one.

use explain analyse in cases in doubt. should plans similar following.

with cte (the big table has 100000 rows, of them scanned in cte):

 hash join  (cost=1580.96..4269.53 rows=565 width=12) (actual time=10.349..42.718 rows=1 loops=1)    hash cond: (tmp.id = st.bigtableid)    cte tmp      ->  seq scan on big_table  (cost=0.00..1572.65 rows=112965 width=4) (actual time=0.011..11.813 rows=100000 loops=1)    ->  cte scan on tmp  (cost=0.00..2259.30 rows=112965 width=4) (actual time=0.013..33.524 rows=100000 loops=1)    ->  hash  (cost=8.30..8.30 rows=1 width=8) (actual time=0.013..0.013 rows=1 loops=1)          buckets: 1024  batches: 1  memory usage: 9kb          ->  index scan using small_table_pkey on small_table st  (cost=0.28..8.30 rows=1 width=8) (actual time=0.009..0.009 rows=1 loops=1)                index cond: (id = 45) 

without cte:

 nested loop  (cost=0.57..16.61 rows=1 width=12) (actual time=0.069..0.071 rows=1 loops=1)    ->  index scan using small_table_pkey on small_table st  (cost=0.28..8.29 rows=1 width=8) (actual time=0.008..0.008 rows=1 loops=1)          index cond: (id = 45)    ->  index scan using big_table_pkey on big_table  (cost=0.29..8.31 rows=1 width=4) (actual time=0.056..0.056 rows=1 loops=1)          index cond: (id = st.bigtableid)          heap fetches: 1 

note not need subquery in second query. automatically optimized one:

select *  small_table st join big_table tmp on tmp.id = st.bigtableid st.id = 45 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -