Quantcast
Viewing all articles
Browse latest Browse all 207

Performance difference using CTE and subquery

I have run the following queries.

CTE

WITH temp AS (SELECT id, timestamp FROM table group by timestamp, id)SELECT COUNT(*) FROM temp WHERE timestamp = '2023-01-01 08:28:45'

Subquery

SELECT COUNT(*) FROM (SELECT id, timestamp FROM table group by timestamp, id) as temp WHERE timestamp = '2023-01-01 08:28:45'

The CTE statement took Total runtime: 638.871 ms
The Subquery statement took Total runtime: 3,795.166 ms

Question

This is the same table, same data, and indexes. What can be the reason for the difference?

Both statement were run on a PostgreSQL 9.6.7 installation.

It seems that the subquery is using External merge while the CTE is not.


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>