Sub topic 4
Listing and Describing Databases, Schemas, and Tables
Assume you know basic SELECT, WHERE, JOIN, and ORDER BY queries. You should also have access to a PostgreSQL server and be connected with psql. This chapter focuses on discovering the structure of a database before you query its data.
The object hierarchy
A PostgreSQL server can contain several databases. A database contains schemas, and schemas contain objects such as tables, views, sequences, indexes, and functions. A table belongs to one schema, even when you refer to it without writing the schema name.
The public schema is commonly used in small projects. Larger systems often use several schemas to separate applications, reporting objects, or internal data.
A name such as app.users is schema-qualified. Using qualified names makes scripts clearer and avoids accidentally selecting an object with the same name in another schema.
List databases and schemas
In psql, commands beginning with a backslash are meta-commands. They are handled by the client rather than sent as SQL to PostgreSQL.
Use these commands to inspect the top levels:
\l
\c mydb
\dn\llists databases visible to your role.\c mydbconnects to the database namedmydb.\dnlists schemas in the current database.
A database connection is separate from the server connection. You can connect to one database at a time through a normal psql session. Use \conninfo to confirm where you are connected.
List and describe tables
After connecting to a database, list tables in the public schema:
\dt public.*To list tables across schemas, use:
\dt *.*The broader pattern may include system tables, so it can produce a large result. You can also list views and other relation types:
\dv public.*
\di public.*
\ds public.*Here, \dv lists views, \di lists indexes, and \ds lists sequences.
Use \d to describe an object. The command shows columns, data types, nullable status, indexes, constraints, and sometimes foreign-key relationships.
\d+ public.ordersThe + requests additional details, such as storage information and descriptions. If the table is in the current search path, \d orders may be sufficient, but the qualified form is safer when exploring an unfamiliar database.
| Command | Purpose |
|---|---|
| `\dt public.*` | List tables in `public` |
| `\d+ public.orders` | Describe one table in detail |
| `\dv public.*` | List views |
| `\di public.*` | List indexes |
| `\df` | List functions |
A repeatable inspection sequence
For a new database, inspect it in this order:
- Confirm the connection with
\conninfo. - List schemas with
\dn. - List tables in likely schemas with
\dt schema_name.*. - Describe important tables with
\d+ schema_name.table_name. - Check views, indexes, sequences, and functions when the table structure does not explain the application behavior.
Exercise
Which command describes the columns, indexes, and constraints of the table sales.orders?
Show answer
Run \d+ sales.orders in psql.