Skip to content
Advertisement

How to assign result of a sql query to a variable and use it into a built in function?

Looking for a solution In Postgresql

declare n_rows integer := select count(*) from sample;

SELECT generate_series AS serial_num
FROM generate_series(0, n_rows + 1)

Advertisement

Answer

SQL has no variables, so short of using a function, you can use a common table expression:

with var as (
   select count(*) as n_rows
   from sample
)
SELECT g.serial_num
FROM var, generate_series(0, n_rows + 1) as g(serial_num)

Or just:

SELECT *
FROM generate_series(0, (select count(*) + 1 from sample)) as g(serial_num) 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement