Skip to content

Instantly share code, notes, and snippets.

@codesnik
Created February 3, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codesnik/d3641298743ed42c6a05 to your computer and use it in GitHub Desktop.
Save codesnik/d3641298743ed42c6a05 to your computer and use it in GitHub Desktop.
union vs union all
[busfor_prod] # explain analyze SELECT * FROM cities where id in (select from_id FROM timetable_segments UNION ALL SELECT to_id FROM timetable_segments);
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Nested Loop (cost=747.24..1988.45 rows=19318 width=442) (actual time=12.208..13.778 rows=606 loops=1)
-> HashAggregate (cost=746.95..748.95 rows=200 width=4) (actual time=12.194..12.311 rows=606 loops=1)
Group Key: timetable_segments.from_id
-> Append (cost=0.00..665.16 rows=32716 width=4) (actual time=0.012..7.302 rows=32716 loops=1)
-> Seq Scan on timetable_segments (cost=0.00..332.58 rows=16358 width=4) (actual time=0.012..2.133 rows=16358 loops=1)
-> Seq Scan on timetable_segments timetable_segments_1 (cost=0.00..332.58 rows=16358 width=4) (actual time=0.002..1.988 rows=16358 loops=1)
-> Index Scan using cities_pkey on cities (cost=0.29..6.19 rows=1 width=442) (actual time=0.002..0.002 rows=1 loops=606)
Index Cond: (id = timetable_segments.from_id)
Planning time: 0.447 ms
Execution time: 13.899 ms
(10 rows)
Time: 14.907 ms
[busfor_prod] # explain analyze SELECT * FROM cities where id in (select from_id FROM timetable_segments UNION SELECT to_id FROM timetable_segments);
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Hash Join (cost=2137.38..4842.78 rows=19318 width=442) (actual time=12.560..20.761 rows=606 loops=1)
Hash Cond: (cities.id = timetable_segments.from_id)
-> Seq Scan on cities (cost=0.00..2233.36 rows=38636 width=442) (actual time=0.007..4.401 rows=38636 loops=1)
-> Hash (cost=1728.43..1728.43 rows=32716 width=4) (actual time=12.520..12.520 rows=606 loops=1)
Buckets: 32768 Batches: 1 Memory Usage: 278kB
-> HashAggregate (cost=1074.11..1401.27 rows=32716 width=4) (actual time=12.311..12.394 rows=606 loops=1)
Group Key: timetable_segments.from_id
-> Append (cost=0.00..992.32 rows=32716 width=4) (actual time=0.006..7.309 rows=32716 loops=1)
-> Seq Scan on timetable_segments (cost=0.00..332.58 rows=16358 width=4) (actual time=0.006..2.217 rows=16358 loops=1)
-> Seq Scan on timetable_segments timetable_segments_1 (cost=0.00..332.58 rows=16358 width=4) (actual time=0.002..1.976 rows=16358 loops=1)
Planning time: 0.226 ms
Execution time: 20.903 ms
(12 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment