Sub topic 4
Listing and describing databases, schemas and tables
This chapter assumes you can open a psql session (see the previous chapter on connecting) and know basic SQL and the terms table, column, primary key and foreign key. Here you will learn the meta-commands that list what exists on a server and describe the objects you find.
The hierarchy you are walking
One PostgreSQL server (a cluster) holds several databases. A psql connection is tied to exactly one database at a time. Inside a database, schemas group tables, views, functions and other objects.
Each level has its own listing command. You run \l at server level, \dn at database level and \dt at schema level.
Listing databases with \l
\l lists every database on the server, not just the one you are connected to.
postgres=# \l
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Access privileges
-----------+----------+----------+-----------------+-------------+-------------+-------------------
mydb | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | | postgres=CTc/postgres
(4 rows)The exact columns depend on your PostgreSQL version. template0 and template1 are source copies used by CREATE DATABASE. You normally leave them alone. Add + (\l+) to see each database's size, tablespace and description. Computing sizes needs permission to connect to each database, so \l+ can fail for databases you cannot access.
To move to another database, use \c:
postgres=# \c mydb
You are now connected to database "mydb" as user "postgres".
mydb=#\c opens a new connection and closes the old one. Session settings such as \timing are psql state and survive the switch. Settings made with SET do not.
Listing schemas with \dn
mydb=# \dn
List of schemas
Name | Owner
--------+-------------------
public | pg_database_owner
sales | postgres
(2 rows)\dn hides system schemas such as pg_catalog and information_schema. Add S to include them (\dnS), or + to show access privileges and descriptions.
Listing tables with \dt
mydb=# \dt
List of relations
Schema | Name | Type | Owner
--------+-----------+-------+----------
public | customers | table | postgres
public | orders | table | postgres
(2 rows)Plain \dt shows only tables in schemas on your search_path. The sales schema above is missing from this output even though it exists. Check the path with SHOW search_path;. The default is "$user", public. To see other schemas, name them in a pattern:
\dt public.*
\dt sales.*
\dt *.*\dt *.* lists tables in every schema, including system ones. A pattern with a schema part is the reliable way to list a specific schema, because it does not depend on search_path.
How patterns work
Patterns are not full regular expressions. These rules apply to every \d command:
*matches any sequence of characters and?matches exactly one character.- A dot separates the schema part from the object part, so
sales.ord*means tables starting withordinsales. - Names are folded to lower case unless you double-quote them.
\dt Orderssearches fororders.\dt "Orders"searches for a table literally namedOrders.
Describing one table with \d
\d name describes a single object. For a table it shows columns, types, nullability, defaults, indexes, constraints and incoming foreign keys.
mydb=# \d orders
Table "public.orders"
Column | Type | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+------------------------------------
id | integer | | not null | nextval('orders_id_seq'::regclass)
customer_id | integer | | not null |
total | numeric(10,2) | | not null |
created_at | timestamp with time zone | | not null | now()
Indexes:
"orders_pkey" PRIMARY KEY, btree (id)
"orders_customer_id_idx" btree (customer_id)
Foreign-key constraints:
"orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)\d+ orders adds storage settings, statistics targets, column descriptions and the table's access method. Use it when you need more than the basic structure. A bare \d with no argument lists tables, views, sequences and other relations together.
Listing other object types
Each object type has its own letter. All of them accept a pattern, S and +.
| Command | Lists |
|---|---|
| `\dt` | tables |
| `\dv` | views |
| `\dm` | materialized views |
| `\ds` | sequences |
| `\di` | indexes |
| `\df` | functions |
| `\dT` | data types |
| `\dx` | installed extensions |
| `\dE` | foreign tables |
A typical exploration of an unfamiliar database follows the hierarchy from the top:
\conninfo
\l
\c mydb
\dn
\dt public.*
\d+ orders
\df
\diIf you forget a command, \? prints the full list of meta-commands, and \h CREATE TABLE shows SQL syntax help.
Common errors and surprises
- "Did not find any relation named ..." The object is not on your
search_path, the name has different capitalization than you assumed, or you are connected to the wrong database. Run\conninfo, then retry with a schema-qualified name such as\d sales.orders. - An empty
\dtresult. The database may have no tables in the schemas on your path. Try\dt *.*before assuming it is empty. - Missing system objects.
\dt,\dfand similar commands hide objects inpg_catalogandinformation_schema. AddS(for example\dtS) to include them. - Mixed-case names. A table created as
"Orders"needs quotes in every pattern and query. Unquoted\d Orderswill not find it. - Same table name in two schemas. An unqualified
\d ordersresolves throughsearch_pathand describes only the first match. Qualify the name to be sure.
Seeing the SQL behind a command
To confirm what a listing command is doing, start psql with -E:
psql -E -h localhost -U postgres -d mydbThen run \dn. psql prints the query it sent against pg_catalog.pg_namespace before showing the result. You can copy that query into a script and adjust it, for instance to filter by owner.
Exercise
You run \dt in a database and see only the tables in public, but you know a schema named reporting exists. Which command lists its tables, and why did plain \dt not show them?
Show answer
Run \dt reporting.*. Plain \dt only shows schemas on the search_path, which defaults to "$user", public, so reporting is not searched. You can also use \dt *.* to list tables in all schemas.
Exercise
A table was created with the quoted name "Orders". \d Orders reports that no relation was found. How do you describe it, and which command shows the SQL psql runs behind the scenes?
Show answer
Use \d "Orders". Unquoted names are folded to lower case, so Orders is searched as orders. Start psql with -E (or run \set ECHO_HIDDEN on) to print the catalog queries that meta-commands send.