Sub topic 1
How a PostgreSQL server is organized
Prerequisites
This chapter assumes you know basic SQL (SELECT, WHERE, JOIN, ORDER BY), are comfortable in a terminal, and have PostgreSQL installed locally or access to a running server. You should also understand tables, columns, and primary and foreign keys.
Server, databases, and schemas
A PostgreSQL server is one running process. It manages several databases, and each database holds schemas. A schema is a named group of tables, views, functions, and indexes. Every new database has a schema called public.
Objects are only visible inside the database where they live. Connect to a database before you inspect its objects.
Connecting to a database with psql
psql is the PostgreSQL command-line client. Pass the host, port, user, and database as flags:
psql -h localhost -p 5432 -U postgres -d mydb-hsets the host.-psets the port.-Usets the user.-dsets the database.
If the server requires a password, psql prompts for it. To confirm the connection, run \conninfo.
> Note: the connection details above are placeholders. Replace them with your server's values.
Meta-commands and built-in help
Meta-commands start with a backslash. psql handles them itself. The server never sees them. Three useful ones are:
| Command | Purpose |
|---|---|
| `\?` | List all psql meta-commands |
| `\h SELECT` | Show SQL syntax help for a statement |
| `\q` | Quit psql |
Listing and describing databases, schemas and tables
Use these commands to explore an unfamiliar database:
\l
\c mydb
\dn
\dt public.*
\d+ orders\l lists databases, and \c mydb switches to one. \dn lists schemas. \dt public.* lists tables in public. \d+ orders describes the orders table, including its columns and storage details.
Exercise
Which meta-command lists the tables in the public schema of the current database?
Show answer
\dt public.*