Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias a POSTGRES select statement

Tags:

sql

postgresql

I want to create new tables in the query and use them at the end for a final query. I don't remember what the syntax is and can't find it anywhere. (here is a basic example for illustration only).

phones as 
    (
        SELECT phone_number from customers
    )


emails as 
    (
        SELECT emails from customers
    )

// do something with both
like image 637
William Falcon Avatar asked Oct 25 '25 14:10

William Falcon


2 Answers

You are looking for CTE's

With phones as 
    (
        SELECT phone_number from customers
    )
,emails as 
    (
        SELECT emails from customers
    )
select * from phones--/emails 
like image 144
Pரதீப் Avatar answered Oct 28 '25 04:10

Pரதீப்


You are looking for a Common Table Expression (CTE). These are introduced using with:

with phones as (
      SELECT phone_number from customers
     ),
     emails as (
      SELECT emails from customers
    )
select . . .;

Your example selects don't seem particularly useful, but I assume they are just for illustration.

like image 22
Gordon Linoff Avatar answered Oct 28 '25 02:10

Gordon Linoff