Oleh  Sobchuk
Oleh Sobchuk

Reputation: 3722

PostgreSQL WITH query on already selected table

I use PostgreSQL WITH https://www.postgresql.org/docs/current/static/queries-with.html. And I can run pretty complicated query, but can I use already sorted data? For instance:

SELECT id, f_name, l_name, email FROM users
WHERE f_name = 'BabyBoy'

WITH i_need_do_thomething AS (
# and than use that filtered data
)
SELECT * FROM i_need_do_thomething

Thanks

UPDATE

All problems that I use this query in Ruby on Rails. And I use association like:

@laptop = Laptop.find(1)
@laptop.user.do_custom_sql(HERE_WILL_BE_RAW_SQL)

where @laptop.user is equal to

SELECT id, f_name, l_name, email FROM users
WHERE f_name = 'BabyBoy'

Upvotes: 0

Views: 114

Answers (1)

Michel Milezzi
Michel Milezzi

Reputation: 11115

Each query on WITH QUERIES is treated like a temporary table. You can place as many queries as you need:

WITH filtered_something AS (
    SELECT id, f_name, l_name, email FROM users WHERE f_name = 'BabyBoy'
), i_need_do_something AS (
    SELECT * FROM filtered_something
)
SELECT * FROM i_need_do_something;

Upvotes: 2

Related Questions