4

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
1

2 Answers 2

9

You are looking for CTE's

With phones as 
    (
        SELECT phone_number from customers
    )
,emails as 
    (
        SELECT emails from customers
    )
select * from phones--/emails 
Sign up to request clarification or add additional context in comments.

4 Comments

cool thanks. Will accept in 10 mins. Do i need to join now to use data from all tables? or can i say select phones.phone, emails.email
@WilliamFalcon - It depends on the requirement. You current sample query makes not sense. Add sample data and expected result in next question.
yeah, it's a very simplified example for illustration. The as queries are fairly complex involving a bunch of joins. It's to do some calculations (group by users per month, see rate of growth, etc...)
@WilliamFalcon - You can Join,union, etc.. between phones and emails in your current example
3

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.