0

The following works in Postgres:

SELECT
    *
FROM
    (
        SELECT
            product_id,
            product_name,
            price,
            ROW_NUMBER () OVER (ORDER BY product_name)
        FROM
            products
    ) x
WHERE
    ROW_NUMBER BETWEEN 6 AND 10;

My question is why does the following simpler attempt not work?

        SELECT
            product_id,
            product_name,
            price,
            ROW_NUMBER () OVER (ORDER BY product_name)
        FROM
            products
     
WHERE
    ROW_NUMBER BETWEEN 6 AND 10;

1 Answer 1

2

Because window functions, like row_number(), are applied to the result of the query (in your case that's the inner one), i.e. after the WHERE clause (not statement) has already taken effect.

Sign up to request clarification or add additional context in comments.

1 Comment

So the variable does not exist in the namespace and cannot be referred to unless it is returned by an inner query. Interesting.

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.