Postgresql – Postgres: difference between CTE and temporary table

postgresqlpostgresql-9.4

In Postgres is there a difference between a CTE and a temporary table other than the fact that the CTE exists just for the context of one statement?

Documentation says that

Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query.

Does "can be thought" means that they are identical?

Best Answer

To add to what others have said. Temporary tables can also have primary keys, constraints, indexes, etc. whereas CTEs cannot.

On the flip side, you can do some pretty neat tricks with CTEs that would be harder, I think, if done with temporary tables-- such as chaining them to perform deletes, inserts, and selects all in one statement. There are some nice examples of "cool-CTE-tricks" here.