On this page 33 sections
- Connect to PostgreSQL
- Connection information
- List databases
- Change database
- List schemas
- List tables
- Describe tables
- List columns with SQL
- List users and roles
- Create a database
- Delete a database
- Create users and roles
- Grant privileges
- Basic SELECT queries
- Count rows
- Sort query results
- Insert data
- Update data
- Delete data
- List views
- List indexes
- List functions
- Show PostgreSQL version
- Show configuration values
- Active connections
- Execute SQL from the shell
- Execute SQL from a file
- Export query results
- Import CSV data
- Dump a database
- Restore a database
- Useful psql display commands
- Quit psql
Connect to PostgreSQL
psql is the PostgreSQL command-line client. A connection normally specifies a user, database, host and optionally a port.
psql -U postgrespsql -U postgres -d appdbpsql -h 10.10.10.20 -p 5432 -U postgres -d appdbpsql 'postgresql://postgres:password@10.10.10.20:5432/appdb'Connection information
Inside psql, backslash commands are client-side meta-commands. They do not require a trailing semicolon.
\conninfoSELECT current_database();SELECT current_user;List databases
\l lists databases available on the PostgreSQL server. \l+ includes additional information such as size and tablespace.
\l\l+SELECT datname FROM pg_database;Change database
\c reconnects the current psql session to another database. PostgreSQL does not use a SQL USE database statement like MySQL.
\c appdb\c appdb appuserList schemas
Schemas organize database objects such as tables, views and functions. The public schema exists by default in many PostgreSQL databases.
\dn\dn+SHOW search_path;List tables
\dt lists tables visible in the current search path. A schema can be specified explicitly when needed.
\dt\dt *.*\dt public.*\dt+Describe tables
\d shows the structure of database objects. For a table it displays columns, data types, indexes and constraints.
\d users\d+ users\d public.usersList columns with SQL
information_schema provides portable metadata about database objects.
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'users';List users and roles
PostgreSQL uses roles for both users and groups. A role with LOGIN permission can authenticate to the server.
\du\du+SELECT rolname FROM pg_roles;Create a database
CREATE DATABASE creates a new PostgreSQL database. The connected role must have sufficient privileges.
CREATE DATABASE appdb;createdb -U postgres appdbDelete a database
DROP DATABASE permanently removes a database and its contents.
DROP DATABASE appdb;dropdb -U postgres appdbCreate users and roles
CREATE ROLE creates a PostgreSQL role. LOGIN allows the role to authenticate like a normal database user.
CREATE ROLE appuser WITH LOGIN PASSWORD 'StrongPassword';CREATE USER appuser WITH PASSWORD 'StrongPassword';ALTER USER appuser WITH PASSWORD 'NewPassword';Grant privileges
Privileges control which roles can connect to databases and access database objects.
GRANT CONNECT ON DATABASE appdb TO appuser;GRANT USAGE ON SCHEMA public TO appuser;GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO appuser;GRANT ALL PRIVILEGES ON DATABASE appdb TO appuser;Basic SELECT queries
SELECT retrieves data from tables. LIMIT is useful when inspecting an unfamiliar database without returning large result sets.
SELECT * FROM users;SELECT * FROM users LIMIT 10;SELECT id, username, email FROM users;SELECT * FROM users WHERE username = 'admin';Count rows
COUNT is useful for quickly checking how much data exists in a table.
SELECT COUNT(*) FROM users;SELECT COUNT(*) FROM users WHERE active = true;Sort query results
ORDER BY sorts result rows using one or more columns.
SELECT * FROM users ORDER BY id DESC;SELECT * FROM users ORDER BY username ASC;Insert data
INSERT adds new rows to a table.
INSERT INTO users (username, email)
VALUES ('samir', 'samir@example.com');INSERT INTO users (username, email)
VALUES ('samir', 'samir@example.com')
RETURNING *;Update data
UPDATE modifies existing rows. A WHERE clause should normally be used to avoid changing every row in the table.
UPDATE users
SET email = 'new@example.com'
WHERE username = 'samir';Delete data
DELETE removes rows matching the specified condition.
DELETE FROM users WHERE username = 'samir';List views
Views are stored queries that can be queried similarly to tables.
\dv\dv+List indexes
Indexes can improve query performance and are often useful when reviewing a database schema.
\di\di *.*List functions
\df shows functions available in the current database.
\df\df+Show PostgreSQL version
The server version can be checked using SQL or psql itself.
SELECT version();psql --versionShow configuration values
SHOW displays the current value of PostgreSQL runtime configuration parameters.
SHOW port;SHOW data_directory;SHOW config_file;SHOW hba_file;Active connections
pg_stat_activity provides information about current PostgreSQL sessions and queries.
SELECT pid, usename, datname, client_addr, state
FROM pg_stat_activity;SELECT pid, usename, datname, query
FROM pg_stat_activity
WHERE state = 'active';Execute SQL from the shell
-c executes a SQL statement directly without entering an interactive psql session.
psql -U postgres -d appdb -c "SELECT current_database();"psql -U postgres -d appdb -c "\dt"Execute SQL from a file
SQL scripts can be executed either from the shell or from inside an existing psql session.
psql -U postgres -d appdb -f backup.sql\i script.sqlExport query results
\copy runs through the client and is convenient for exporting query results to CSV files.
\copy users TO 'users.csv' CSV HEADER\copy (SELECT id, username FROM users) TO 'users.csv' CSV HEADERImport CSV data
\copy can also load local CSV data into a table.
\copy users(id, username, email) FROM 'users.csv' CSV HEADERDump a database
pg_dump creates a logical backup of a PostgreSQL database.
pg_dump -U postgres -d appdb > appdb.sqlpg_dump -U postgres -d appdb -Fc -f appdb.dumpRestore a database
Plain SQL dumps can be restored with psql. Custom-format dumps are normally restored with pg_restore.
psql -U postgres -d appdb < appdb.sqlpg_restore -U postgres -d appdb appdb.dumpUseful psql display commands
psql includes several commands that make query output easier to inspect in a terminal.
\x\s\?\h SELECTQuit psql
\q closes the current psql session.
\q