8

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!)

4
  • It's not very clear what you're asking... Commented Sep 18, 2013 at 15:47
  • What do you want to do with "anonymous table"? The ability to create such table looks like a bug. Commented Sep 18, 2013 at 15:49
  • @Denis, what I'm asking is whether there's a nicer way to do: select * from (values (NULL, NULL)) as foo (mycol1, mycol2) where mycol1 is not NULL. Commented Sep 18, 2013 at 15:55
  • @IgorRomanchenko, by anonymous table I mean a temporary query based on data not in the database, such as the one returned from my first select statement. Commented Sep 18, 2013 at 15:56

2 Answers 2

6

I think you can do something like this:

select null::text as a, null::int as b
limit 0
Sign up to request clarification or add additional context in comments.

1 Comment

I like it! My preferred answer so far. Syntactically very clean.
1
SELECT  *
FROM    generate_series(0, -1)

3 Comments

That certainly gives me a query returning zero rows! But can I make it have an arbitary number of columns with arbitrary types?
@TomEllis Use SELECT null::number, null::varchar ... FROM generate_series(0, -1)
Ah yes, that works. And to get column names I can do SELECT null::int as foo, null::varchar as bar FROM generate_series(0, -1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.