1

I am using PostgreSQL to write an SQL query to select from the same sql results twice. For example,

SELECT a.id, b.id
  FROM
    (SELECT * FROM tableA) as a,
    (SELECT * FROM tableA) as b
  WHERE a.id = b.id+1

As you can see the following SQL query has been executed twice:

SELECT * FROM tableA

Is it possible to store the SQL results temporarily instead of running the same query twice because this query can be complicated?

3
  • What about a join of tableA with itself ? Something like: SELECT a.id,b.id from tableA a join tableB b on a.id=b.id+1
    – Houari
    Sep 25, 2015 at 15:32
  • The line "SELECT * FROM tableA" is just an example and it could be complicated nested queries.
    – chesschi
    Sep 25, 2015 at 15:36
  • If the SELECT * from tableA can't be replaced by a view, you can use also a sub-query using with keyword
    – Houari
    Sep 25, 2015 at 15:39

3 Answers 3

3

Common Table Expression:

with cte as 
(SELECT * FROM tableA)
select * from cte where...

So you don't have to write the same stuff twice. Don't know if its executed once or severel times though...

2
  • What I'm wondering (and I'm honestly not sure, and that seems to be OP's question): if you refer to the CTE twice in your query, are you guaranteed that the CTE will only be executed once?
    – sstan
    Sep 25, 2015 at 15:25
  • I don't know, check the execution plan.
    – jarlh
    Sep 25, 2015 at 15:26
2

A CTE solves your problem. But it is likely that the lead() function would as well . . . and with better performance:

SELECT a.*
FROM (SELECT a.id, lead(a.id) over (order by a.id) as b_id
      FROM tableA a
     ) a
WHERE id = b_id;

Or, for something that will work with duplicates:

SELECT a.id, a.id + 1
FROM tableA a
WHERE EXISTS (SELECT 1 FROM tableA a2 WHERE a2.id = a.id + 1);

A self-join seems like overkill for whatever you really want to accomplish. It might be the right solution, but there are alternatives.

1

You can use a cte.

with a as (select * from tableA)
, b as (select * from tableA)
select a.id, b.id 
from a join b on a.id = b.id+1

Or it could be done with a self-join.

select a.id, b.id 
from tableA a join tableB b
on a.id = b.id+1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.