Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty anonymous table in Postgres?

Tags:

sql

postgresql

In Postgres if I want to create an "anonymous table" (i.e. a temporary query based on data not in the database) I can use VALUES, for example:

select * from (values (1, 'Hello world'), (100, 'Another row')) as foo (mycol1, mycol2);

But how can I create an anonymous table with no rows? (This is for a code generator, so the question isn't quite as odd as it sounds!). The following does not work

select * from (values  ) as foo (mycol1, mycol2);

because I get

ERROR:  syntax error at or near ")"
LINE 1: select * from (values  ) as foo (mycol1, mycol2);
                               ^

I know a work around

select * from (values (NULL, NULL)) as foo (mycol1, mycol2) where mycol1 is not NULL;

but is there a better or "more official" way?

(I would also be interested to know if it is possible to create a table with no columns!)

like image 995
Tom Ellis Avatar asked Sep 18 '13 15:09

Tom Ellis


2 Answers

I think you can do something like this:

select null::text as a, null::int as b
limit 0
like image 191
Roman Pekar Avatar answered Oct 19 '22 10:10

Roman Pekar


SELECT  *
FROM    generate_series(0, -1)
like image 1
Quassnoi Avatar answered Oct 19 '22 08:10

Quassnoi