psql and your first tables
psql is the command-line client that ships with PostgreSQL. Professionals use it every day because it's fast, scriptable and available on every server. It understands two kinds of input:
- SQL statements, which end with a semicolon
;and are sent to the server. - Meta-commands, which start with a backslash
\, are handled by psql itself and don't need a semicolon.
Exploring with meta-commands
\dt lists tables. \d name describes one: its columns, types, indexes and relationships.
Read that output carefully: orders has a primary key index, and two foreign keys pointing at customers and products. \d is the quickest way to understand an unfamiliar database.
The meta-commands you'll use most
| Command | What it does |
|---|---|
\l |
List databases |
\c dbname |
Connect to another database |
\dt |
List tables (\dt sales.* for one schema) |
\d name |
Describe a table, view or index |
\di, \dv, \df |
List indexes, views, functions |
\du |
List roles (users) |
\dn |
List schemas |
\x |
Toggle expanded output (one column per line), great for wide rows |
\timing |
Show how long each query takes |
\i file.sql |
Run a SQL file |
\? |
Help for meta-commands; \h CREATE TABLE shows SQL syntax help |
\q |
Quit |
Try \x with a wide row, and \timing:
This browser editor has one database, so
\c,\iand\honly work in a real psql session.
Databases and schemas
A Postgres server (also called a cluster) holds many databases. Each database holds schemas, and each schema holds tables. A fresh server has a database called postgres and every database has a schema called public.
-- In a real psql session:
CREATE DATABASE shop;
\c shopSchemas are folders inside one database, useful for separating modules or tenants:
When you write a table name without a schema, Postgres looks through the search path, which is normally just public:
Creating a table
What each part means:
GENERATED ALWAYS AS IDENTITYauto-numbers theidcolumn: 1, 2, 3… This is the modern, standard way. Older code usesserial, which still works but has quirks.PRIMARY KEY= unique + not null + indexed. Every table should have one.textholds strings of any length. In Postgres,textis the normal choice (more on types in the next lesson).timestamptzis a timestamp with time zone, andDEFAULT now()fills it in automatically.
INSERT … RETURNING
Postgres can hand back the rows it just wrote, including generated values. This saves a second query:
Changing a table
IF EXISTS turns a missing-table error into a harmless notice. Notice the second DROP prints a NOTICE instead of failing.
Reading error messages
Postgres errors are precise. Run this and read the LINE and HINT parts:
The caret ^ points at the problem and the hint suggests the fix. Get used to reading them: they'll save you hours.
Practice
- Create a
moviestable with an identityid, a requiredtitle, ayearinteger and aratingnumeric. - Insert three movies, using
RETURNINGto see their ids. - Add a
watched boolean DEFAULT falsecolumn, then describe the table with\d movies.
1.What's the difference between \dt and SELECT * FROM t;?
2.What does RETURNING id do on an INSERT?
3.What is the modern way to make an auto-incrementing id?