0

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'

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

so I can use WITH ONLY in a separate case? And I can't use it as I wrote in the example. Right?
Yes, you can't do it this way. In this case I think you should use ActiveRecord::Base.connection.execute(entire_sql_here) and then iterate over result set.

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.