Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a CTE scan, and what are its implications for performance?

Tags:

postgresql

I'm trying to diagnose a slow query, using EXPLAIN ANALYZE. I'm new to the command so I've read http://www.postgresql.org/docs/9.3/static/using-explain.html . The query plan uses a "CTE scan", but I don't know what that is, compared to, say, a sequential scan - and more importantly, what a CTE scan means in general for query performance.

like image 728
bblack Avatar asked Nov 10 '14 20:11

bblack


People also ask

What is CTE scan?

Computer tomography enterography (CTE) is a type of computed tomography medical test that helps diagnose certain gastrointestinal diseases in the small intestine, sometimes referred to as the small bowel. CTE is a noninvasive imaging exam.

Does PostgreSQL have CTE?

PostgreSQL conforms to the ANSI SQL-99 standard and implementing CTEs in PostgreSQL is similar to SQL Server. CTE is also known as WITH query. This type of query helps you to simplify long queries, it is similar to defining temporary tables that exist only for the running of the query.


1 Answers

A "CTE scan" is a sequential scan of the materialized results of a CTE term (a named section like "blah" in a CTE like WITH blah AS (SELECT ...).

Materialized means that PostgreSQL has calculated the results and turned them into a temporary store of rows, it isn't just using the CTE like a view.

The main implication is that selecting a small subset from a CTE term and discarding the rest can do a lot of wasted work, because the parts you discard must still be fully calculated.

For details see a recent blog post I wrote on the topic.

like image 120
Craig Ringer Avatar answered Oct 17 '22 00:10

Craig Ringer