2

I'm new to PostgreSQL, so maybe my question is unconvinced. But what I want is to put the result of one query into a variable and then used it again in another query. I run my query inside pgAdmin4, Below is my query:

Also I tried those solution1, solution2 without achieving my goal.

WITH vars AS (
    (select count(*) from employee) AS vars_id
)
select 
    *
from 
    employee
where
    id=vars.vars_id;

The error is:

ERROR:  syntax error at or near "AS"
LINE 2:  (select count(*) from employee) AS vars_id
                                         ^
SQL state: 42601
Character: 49
3
  • 1
    where id=vars.vars_id; => where id = (SELECT vars.vars_id FROM vars); Commented Dec 26, 2022 at 21:10
  • 2
    vars is a table, not a single record. There are no such variables in plain SQL. Commented Dec 26, 2022 at 21:15
  • I updated my question, it gives me this error. Commented Dec 26, 2022 at 21:16

1 Answer 1

2

The result of a CTE is a table expression. You can't just refer to it as a scalar, you need to query from it:

WITH vars AS (
    SELECT COUNT(*) AS vars_id FROM employee
)
SELECT *
FROM   employee e
JOIN   vars ON e.id = vars.vars_id
Sign up to request clarification or add additional context in comments.

2 Comments

I implemented your solution, it gives me the same error as mine.
@NZJL ooh, the as clause is misplaced. Didn't even notice that, mea culpe. See my edited answer.

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.