Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: How to search a list of strings as a table?

Tags:

sql

postgresql

It's been a while since I've had to do any db work, so I'm not really sure how to ask this and I know I've done it in the past.
How do you create a temporary table out of a list of strings (not using CREATE TEMPORARY TABLE)? So, if you have something like :

  • '1', 'a', 'A'
    '2', 'b', 'B'
    '3', 'c', 'C'

  • SELECT  field2 
    FROM    { {'1','a','A'}, {'2','b','B'}, {'3','c','C'} } 
            AS fooarray(field1,field2,field3)
    WHERE   field1 = '2'
    -- should return 'b'
    

Hint: It's similar to...

  • SELECT * FROM unnest(array[...]);
    
like image 320
vol7ron Avatar asked Jun 05 '12 17:06

vol7ron


People also ask

How do I search for a table in PostgreSQL?

To list the tables in the current database, you can run the \dt command, in psql : If you want to perform an SQL query instead, run this: SELECT table_name FROM information_schema.

How do I do a wildcard search in PostgreSQL?

PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.

How do I get a list of column names in PostgreSQL?

To list down all tables columns on a specific table in the a PostgreSQL database using psql command-line, you can use \dS your_table_name.


1 Answers

You don't need to mess around with arrays at all, you can build the table in-place using VALUES:

7.7. VALUES Lists

VALUES provides a way to generate a "constant table" that can be used in a query without having to actually create and populate a table on-disk.

See also VALUES.

So you can do things like this:

=> select *
   from (
       values ('1', 'a', 'A'),
              ('2', 'b', 'B'),
              ('3', 'c', 'C')
    ) as t(id, c1, c2)
    where id = '2';

 id | c1 | c2 
----+----+----
 2  | b  | B
(1 row)

Don't forget to give your VALUES an alias complete with column names (t(id, c1, c2)) so that everything has a name.

like image 103
mu is too short Avatar answered Nov 14 '22 21:11

mu is too short