Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select hardcoded values without table

Tags:

postgresql

I need to run a select without actually connecting to any table. I just have a predefined hardcoded set of values I need to loop over:

foo bar fooBar 

And I want to loop through those values. I can do:

select 'foo', 'bar', 'fooBar'; 

But this returns it as one row:

 ?column? | ?column? | ?column?  ----------+----------+----------  foo      | bar      | fooBar (1 row) 

I am using Postgresql.

like image 480
Richard Knop Avatar asked Apr 11 '13 12:04

Richard Knop


People also ask

Can we use select statement without from?

select without from , on the other hand, works on four of them. By now you might wonder why stand-alone values might be useful at all. As I implied above, it is more powerful than select without from because it is not limited to produce a single row. With select without from , you'd need to use union .

How do I select values in PostgreSQL?

PostgreSQL SELECT statement syntaxIf you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.


2 Answers

select a from (     values ('foo'), ('bar'), ('fooBar') ) s(a); 

http://www.postgresql.org/docs/current/static/queries-values.html

like image 91
Clodoaldo Neto Avatar answered Nov 23 '22 06:11

Clodoaldo Neto


Using unnest()

expand an array to a set of rows

select unnest(array['foo', 'bar', 'fooBar']); 

demo

like image 30
Vivek S. Avatar answered Nov 23 '22 04:11

Vivek S.