Pages

Sunday, August 24, 2014

Postgres's psql and schemas

When I was a lad and the ancestors of the dinosaurs had just emerged from the primordial soup, you could run the psql client with a named data base and just type something like:
select something, something_else, a_third_thing from some table_or_other;

And get a result.
Then along came schemas.
What's a schema? It's a namespace that allows tables within a database to be grouped.
Now when you run the above you'd get something like:

ERROR:  column "something" does not exist
LINE 1: select something, something_else, a_third_thing from some_table_or_other;

This is because you need to specify the schema you want to search.
How do you know what schema to search?
Well you can list the tables and Postgres will by default show a column with the schema names, e.g.:

ckan_prd=# \dt
                     List of relations
 Schema |             Name              | Type  |  Owner
--------+-------------------------------+-------+----------
 public | activity                      | table | ckan_prd
 public | activity_detail               | table | ckan_prd
 public | authorization_group           | table | ckan_prd
 . . .

You can also list the schemas themselves e.g :

ckan_prd=# \ds
                     List of relations
 Schema |            Name             |   Type   |  Owner
--------+-----------------------------+----------+----------
 public | system_info_id_seq          | sequence | ckan_prd
 public | system_info_revision_id_seq | sequence | ckan_prd
(2 rows)
. . .

Once you have identified the schema there are a couple of ways you can specify it, that I know of.
First you can do it in the query, by prepending the relevant schema to the table name(s)* with a dot ('.'), e.g.
select something, something_else, a_third_thing from some_schema.some_table_or_other
This may seem a little counter-intuitive as the error message above seems to indicate that postgres is havnig a problem finding the column, not the table. But no matter. I'm sure if you think about it there is a perfectly logical explanation. I've declined to think about it, so I can't tell you. Anyhoo...

The other way you can do it, if you know you're going to be working with a single schema all or most of the time is set the SCHEMA environment variable, e.g.:

set SCHEMA 'public';

Note: the variable name SCHEMA is case sensitive, the value 'public' is single quoted and the end of statement semi colon (';') is required.
That's it. Go forth and query postgres.

* Note: not actually sure if you can query tables from different schemas in a single query. I assume you can but I'm not really an RDBMS man.

References:


No comments:

Post a Comment