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!)
I think you can do something like this:
select null::text as a, null::int as b
limit 0
SELECT *
FROM generate_series(0, -1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With