Question

In Postgres, is a WITH clause creating a temporary table and if so can it be used in multiple threads safely ?

I.e. WITH x below, would this be ok if the CTE running in multiple different threads?

WITH x AS (
   SELECT  psp_id
   FROM    global.prospect
   WHERE   status IN ('new', 'reset')
   ORDER   BY request_ts
   LIMIT   1
   )
UPDATE global.prospect psp
SET    status = status || '*'
FROM   x
WHERE  psp.psp_id = x.psp_id
RETURNING psp.*;
Was it helpful?

Solution

No.

A query with a CTE creates an internal, temporary representation of a table that is visible exclusively to the query itself.

I don't see a way to use a TEMPORARY table in multiple threads either, since temporary tables are only visible within the same session.

The next best thing would be an UNLOGGED table. Still cheaper than a regular table, but not quite as cheap as either of the above.

Unlike with a CTE, you can create indexes and ANALYZE TEMPORARY or UNLOGGED tables, though - which may help a lot with huge cardinalities but not with your example (LIMIT 1).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top