PostgreSQL commands cheat sheet

This cheat sheet brings together the most useful commands for working with PostgreSQL: connecting with psql, managing databases and users, privileges, backup and restore, maintenance, monitoring, server settings, and common errors. You can search for a command, filter by topic, and copy it with one click.

Connecting

  • sudo -u postgres psql

    Opens psql as the postgres operating system user. In a typical Linux installation, this is also the database superuser, and its local login usually needs no password.

  • psql -h localhost -p 5432 -U app_user -d app_db

    Connects to a specific server: -h for the host name or IP address, -p for the port (the default is 5432), -U for the database user name, and -d for the database name. When a password is required, psql prompts for it.

  • psql "postgresql://app_user@db.example.com:5432/app_db?sslmode=require"

    Connects with a URI connection string, which puts all the connection details on one line. The sslmode=require parameter requires an encrypted connection. Don't put the password in the string, because it is saved in the command history.

  • psql -d app_db -c "SELECT version();"

    Runs a single command and exits right away, without opening the interactive shell. Useful in scripts and for a quick check of the server version.

  • psql -X -v ON_ERROR_STOP=1 -1 -d app_db -f script.sql

    Runs an SQL file as a single transaction (-1) and stops at the first error, so the file runs completely or not at all. The -X option skips the personal ~/.psqlrc settings file.

  • localhost:5432:app_db:app_user:StrongPass

    A line in the ~/.pgpass file, which psql and the backup tools read the password from, so you don't have to type it. The order is host:port:database:user:password, the * sign matches any value, and the first line that matches the connection is the one used.

  • chmod 0600 ~/.pgpass

    Restricts the .pgpass file to its owner only. When the file has broader permissions, the passwords in it aren't read at all.

  • pg_isready -h localhost -p 5432

    Checks whether the server is running and accepting connections, without actually logging in. Useful in scripts before a backup or before an application starts.

    Example: localhost:5432 - accepting connections

psql commands

  • \l

    Lists all the databases on the server, with their owner, encoding, and privileges. The \l+ command adds the size of each database.

  • \c app_db

    Switches to another database on the same server. You can also give a different user, for example \c app_db app_user. When the new connection fails in an interactive session, the previous connection stays active.

  • \dt

    Lists the tables in the current database. The \dt+ command adds the size and description of each table.

  • \d orders

    Shows the table structure: columns, data types, default values, indexes, and constraints. The \d+ orders command adds more details, such as column comments.

  • \du

    Lists the users and roles on the server and their attributes, such as superuser status and permission to create databases.

  • \dn

    Lists the schemas in the database and their owners. A schema is like a folder inside the database, and the default schema is public.

  • \df

    Lists the functions and procedures in the database. The \dx command lists the extensions installed in it.

  • \dp orders

    Shows the privileges granted on the table, meaning which users may read, insert, update, and delete rows in it.

  • \x auto

    Shows each result row as a list of columns and values when the result is wider than the screen. The \x command on its own turns this display on and off.

  • \timing

    Turns on and off the display of each query's execution time, in milliseconds.

    Example: Time: 12.345 ms

  • \i script.sql

    Runs the commands in the file as if you had typed them in the shell.

  • \o result.txt

    Saves the results of the following queries to a file instead of showing them. The \o command without a file name sends the output back to the screen.

  • \copy orders TO 'orders.csv' WITH (FORMAT csv, HEADER)

    Exports a table to a CSV file with a header row. The file is written on the computer where you run psql, so the command needs no access to files on the server. To import, replace TO with FROM.

  • \watch 5

    Runs the last query again every 5 seconds, until you stop it with Ctrl+C. Without a number, the interval is 2 seconds.

  • \h CREATE TABLE

    Shows the full syntax of an SQL command. The \? command lists all the psql commands that start with a backslash.

  • \q

    Exits psql. You can also exit with Ctrl+D.

Databases

  • CREATE DATABASE app_db OWNER app_user;

    Creates a new database and sets app_user as its owner. The owner can manage the database and create tables in the public schema.

  • CREATE DATABASE app_db OWNER app_user ENCODING 'UTF8' TEMPLATE template0;

    Creates a database with UTF8 encoding, which supports every language. When the encoding or locale settings differ from those of the default template, create the database from the template0 template.

  • createdb -O app_user app_db

    Creates a database from the server's command line, without opening psql. The dropdb --if-exists app_db command deletes a database the same way.

  • ALTER DATABASE app_db OWNER TO new_owner;

    Transfers ownership of the database to another user. Ownership of the tables inside it doesn't change, and you transfer it separately.

  • DROP DATABASE app_db;

    Caution: deletes the database and all its data, with no way to recover it. The command fails while there are active connections to the database, and it is best to back it up before you run it.

  • DROP DATABASE app_db WITH (FORCE);

    Caution: terminates all active connections to the database and deletes it. Applications connected to it get an error immediately.

Users and privileges

  • CREATE ROLE app_user WITH LOGIN PASSWORD 'StrongPass';

    Creates a user that can log in, with a password. In PostgreSQL, users and groups are roles, and LOGIN is what allows logging in. A password in the command may be saved in the command history and the server log, so it is better to set it with the \password command.

  • sudo -u postgres createuser -P app_user

    Creates a user from the server's command line and asks you to type the password twice. The new user can log in by default.

  • \password app_user

    Changes a user's password from within psql. The password isn't shown as you type it, and it is sent to the server encrypted, so it isn't saved in the history or the logs. Without a user name, the command changes the password of the connected user.

  • ALTER ROLE app_user CREATEDB;

    Allows the user to create databases. You change other attributes the same way, for example VALID UNTIL '2027-12-31' for password expiry, or CONNECTION LIMIT 20 to limit the number of connections.

  • GRANT CONNECT ON DATABASE app_db TO app_user;

    Allows the user to connect to the database. This privilege gives no access to the tables, which you grant separately.

  • REVOKE CONNECT ON DATABASE app_db FROM PUBLIC;

    Revokes the connect privilege that every user gets by default, so only users granted CONNECT explicitly, the owner, and superusers can connect to the database.

  • GRANT USAGE, CREATE ON SCHEMA public TO app_user;

    Allows the user to access the public schema and create tables in it. In recent PostgreSQL versions, a user who isn't the database owner can't create tables in public without this privilege.

  • GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;

    Grants read and write privileges on all the existing tables in the schema. Tables created later don't get these privileges automatically.

  • GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_user;

    Grants privileges on the sequences in the schema. This privilege is needed to insert rows into tables whose ID comes from a serial column.

  • ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;

    Sets privileges for tables that app_owner creates in the schema in the future. The command doesn't change existing tables, so run it together with GRANT ON ALL TABLES.

  • GRANT readonly TO app_user;

    Adds the user to the readonly role, so the user gets all the role's privileges. This way you manage identical privileges for several users in one place.

  • REASSIGN OWNED BY old_user TO new_user;

    Transfers ownership of all old_user's objects in the current database to another user. Run it in every database that has objects owned by the user, and only then can you delete the user with DROP ROLE old_user.

Tables and queries

  • CREATE TABLE users (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL UNIQUE, created_at timestamptz NOT NULL DEFAULT now());

    Creates a table with an automatically generated ID, a unique email address, and a creation date. An IDENTITY column is the standard way to create an auto-incrementing ID, instead of serial.

  • ALTER TABLE users ADD COLUMN phone text;

    Adds a column to an existing table. You delete a column (DROP COLUMN) and rename a column (RENAME COLUMN) the same way.

  • INSERT INTO users (email) VALUES ('user@example.com') RETURNING id;

    Inserts a row and returns the ID generated for it, with no need for another query.

  • UPDATE users SET email = 'new@example.com' WHERE id = 42;

    Caution: updates the rows that match the WHERE condition. Without WHERE, the command updates every row in the table. Before you run it, it is best to run SELECT with the same condition.

  • DELETE FROM users WHERE id = 42;

    Caution: deletes the rows that match the condition. Without WHERE, the command deletes every row in the table.

  • INSERT INTO settings (key, value) VALUES ('theme', 'dark') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;

    Insert or update (upsert): when a row with the same key already exists, it is updated with the new value. EXCLUDED stands for the row you tried to insert, and the key column needs a unique constraint or a primary key.

  • INSERT INTO settings (key, value) VALUES ('theme', 'dark') ON CONFLICT (key) DO NOTHING;

    Inserts the row only when it doesn't exist, and skips it without an error when it already exists.

  • INSERT INTO settings (key, value) VALUES ('theme', 'dark') ON CONFLICT (key) DO SELECT RETURNING *;

    In the latest PostgreSQL versions: when the row already exists, the command returns the existing row instead of skipping it, so one query gives you the row either way.

  • SELECT * FROM users ORDER BY id LIMIT 20 OFFSET 40;

    Returns 20 rows starting from row 41, for splitting results into pages. Without ORDER BY, the row order isn't guaranteed, so pages may repeat rows.

  • SELECT * FROM users WHERE email ILIKE '%@example.com';

    A case-insensitive text search. The % sign matches any sequence of characters, and plain LIKE is case-sensitive.

  • CREATE INDEX CONCURRENTLY idx_users_created ON users (created_at);

    Creates an index without blocking writes to the table, so it suits a table your website is working with. It takes longer, and it can't run inside a transaction.

Backup and restore

  • pg_dump -Fc -f app_db.dump app_db

    Backs up a database to a custom-format file, compressed by default, which you restore with pg_restore. The backup is consistent even while the website is running, and it doesn't block reads or writes. Users and server-wide privileges aren't included in it.

  • pg_restore -d app_db app_db.dump

    Restores a custom-format or directory-format backup into an existing database. pg_restore doesn't handle a plain SQL backup, which you restore with psql.

  • createdb -T template0 -O app_user app_db_new

    Creates an empty database from the template0 template before a restore. This avoids duplicate object errors when objects have been added to the default template.

  • pg_restore -d app_db --clean --if-exists app_db.dump

    Caution: drops the existing objects in the database before restoring them from the backup. Suits a full restore over an existing database.

  • pg_restore --no-owner -d app_db app_db.dump

    Restores without the original ownership, so all the objects belong to the user who runs the restore. Useful when you move to a server where the user names are different.

  • pg_restore -j 4 -d app_db app_db.dump

    Restores with four parallel processes, which shortens the restore time of a large database. The option is available for custom-format and directory-format backups.

  • pg_restore -l app_db.dump

    Lists the contents of the backup file without restoring it. Useful to confirm that the backup includes the tables you need.

  • pg_dump -f app_db.sql app_db

    Backs up a database to a plain SQL file that you can read and edit in any text editor. The -t orders option backs up a single table, and the -s option backs up only the structure, without the data.

  • psql -X -v ON_ERROR_STOP=1 -d app_db -f app_db.sql

    Restores a plain SQL backup and stops at the first error. The database must exist before the restore.

  • pg_dumpall --globals-only -f globals.sql

    Backs up the server's users, roles, and tablespaces, which pg_dump doesn't include. Run it as a superuser, and restore it with psql -X -f globals.sql postgres.

Maintenance and size

  • VACUUM (VERBOSE, ANALYZE) orders;

    Frees the space of deleted or updated rows so it can be reused, and updates the table statistics. The command doesn't block reads or writes. In most cases, autovacuum does this work automatically.

  • ANALYZE orders;

    Updates the statistics PostgreSQL uses to choose how to run queries. It is best to run it after loading or deleting a large amount of data.

  • VACUUM FULL orders;

    Caution: rewrites the table and returns the free space to the disk, but blocks all reads and writes on the table until it finishes, and needs free space equal to the table size. In the latest PostgreSQL versions, the FULL option is deprecated in favor of the REPACK command.

  • REPACK (CONCURRENTLY) orders;

    In the latest PostgreSQL versions: rewrites the table and returns space to the disk, while the table keeps accepting reads and writes most of the time. The CONCURRENTLY option suits a table with a primary key, and needs free space equal to the size of the table and its indexes. REPACK without CONCURRENTLY locks the table like VACUUM FULL.

  • REINDEX TABLE CONCURRENTLY orders;

    Rebuilds all the table's indexes without blocking writes, for example after an index is corrupted or bloated. REINDEX without CONCURRENTLY blocks writes to the table until it finishes.

  • SELECT pg_size_pretty(pg_database_size('app_db'));

    Shows the size of the database on disk, in readable units such as MB or GB.

    Example: 1250 MB

  • SELECT pg_size_pretty(pg_total_relation_size('orders'));

    Shows the total size of the table, including its indexes. The pg_relation_size function shows the size of the data only, and pg_indexes_size shows the size of the indexes.

  • SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 10;

    Lists the ten largest tables in the database, so you can quickly see what takes up the space.

Monitoring and active connections

  • SELECT pid, usename, datname, client_addr, state, query_start, query FROM pg_stat_activity WHERE state <> 'idle' ORDER BY query_start;

    Shows the connections that are running a query now or are in the middle of a transaction, with the user, database, client address, and query. The pid column is the process ID, which you use to stop a query.

  • SELECT pid, now() - query_start AS duration, query FROM pg_stat_activity WHERE state = 'active' ORDER BY duration DESC;

    Shows the queries running now, longest first. A query that runs for many minutes is a common cause of a slow website.

  • SELECT pid, usename, now() - xact_start AS open_for FROM pg_stat_activity WHERE state = 'idle in transaction';

    Finds connections that opened a transaction and are doing nothing. A transaction left open for a long time can block tables and keep VACUUM from freeing space.

  • SELECT count(*) FROM pg_stat_activity;

    Shows the number of connections to the server. Compare it with the value of SHOW max_connections, which is 100 in most installations, to see how close the server is to the limit.

  • SELECT pg_cancel_backend(12345);

    Stops the query running in process 12345, while the connection itself stays open. This is the gentle way, and it is best to try it before terminating the connection.

  • SELECT pg_terminate_backend(12345);

    Caution: terminates the whole connection. An open transaction on the connection is rolled back, and the application that used it gets an error. Make sure it is the right process before you run it.

  • EXPLAIN SELECT * FROM orders WHERE customer_id = 7;

    Shows how PostgreSQL plans to run the query, without actually running it. A Seq Scan on a large table may point to a missing index.

  • EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 7;

    Actually runs the query and shows the timing and the number of rows at each step. In recent PostgreSQL versions, the output also includes BUFFERS data by default.

  • BEGIN; EXPLAIN ANALYZE UPDATE orders SET status = 'sent' WHERE id = 42; ROLLBACK;

    Caution: EXPLAIN ANALYZE really executes the command, including UPDATE and DELETE. To measure a write command without changing the data, wrap it in a transaction and cancel it with ROLLBACK.

Server settings

  • SHOW config_file;

    Shows the path of the postgresql.conf settings file. The SHOW hba_file command shows the path of pg_hba.conf, which controls who can connect and with which method.

  • listen_addresses = '*'

    A postgresql.conf setting that makes the server listen on all addresses, not only on localhost (the default). The change takes effect only after a server restart, and you also need a matching rule in pg_hba.conf and an open port in the firewall.

  • host app_db app_user 203.0.113.10/32 scram-sha-256

    A pg_hba.conf line that lets app_user connect to the app_db database from a single IP address, with a password using the scram-sha-256 method. Lines are checked from top to bottom, and the first line that matches the connection decides. The md5 method is deprecated.

  • SELECT pg_reload_conf();

    Reloads the settings files, including pg_hba.conf, without dropping existing connections. Settings such as listen_addresses and port require a full server restart.

  • SELECT line_number, type, database, user_name, address, auth_method, error FROM pg_hba_file_rules WHERE error IS NOT NULL;

    Checks the pg_hba.conf file and shows lines with errors. It is best to run it before you reload the settings.

  • SELECT name, setting, context FROM pg_settings WHERE name = 'max_connections';

    Shows the current value of a setting. When the context column shows postmaster, the change takes effect only after a server restart. The \dconfig command in psql lists all the settings changed from their defaults.

  • ALTER SYSTEM SET work_mem = '64MB';

    Changes a setting from within psql, without editing the files by hand. The change is saved in the postgresql.auto.conf file and takes effect after SELECT pg_reload_conf(), or after a restart for settings that require one. ALTER SYSTEM RESET work_mem undoes the change.

  • sudo systemctl restart postgresql

    Restarts the database service, and all connections are dropped. The service name depends on the distribution and the installation method, and sometimes includes the version number, for example postgresql-19.

Common errors

  • FATAL: password authentication failed for user "app_user"

    The server accepted the connection, but the password is wrong. Check the password and the user name, and reset the password with \password when needed. The server log sometimes shows a more detailed reason than the message the client gets.

  • FATAL: role "app_user" does not exist

    The user doesn't exist on the server. Database users are separate from operating system users, and when you don't give -U, psql connects with your operating system user name. Create the user or give the correct name.

  • FATAL: database "app_db" does not exist

    The database doesn't exist. When you don't give a database, psql tries to connect to a database with the same name as the user, so this error sometimes appears even when you gave no name at all.

  • FATAL: no pg_hba.conf entry for host "203.0.113.10", user "app_user", database "app_db", no encryption

    The server is reachable, but pg_hba.conf has no line that allows this connection. Add a matching line with the address, user, and database, and reload the settings.

  • connection to server at "db.example.com" (203.0.113.5), port 5432 failed: Connection refused

    The connection didn't reach the database server: the service isn't running, the server listens only on localhost (the listen_addresses setting), or the firewall blocks the port. When the message mentions a socket, the local server isn't running or listens on a different path.

  • ERROR: permission denied for schema public

    In recent PostgreSQL versions, only the database owner can create tables in the public schema by default. To fix it, make the application user the database owner, or give it GRANT USAGE, CREATE ON SCHEMA public.

  • ERROR: permission denied for table orders

    The user has no privilege on the table. Grant the required privileges with GRANT, and for tables created later, set ALTER DEFAULT PRIVILEGES.

  • FATAL: sorry, too many clients already

    The server has reached its maximum number of connections (max_connections). Check in pg_stat_activity which connections are open, and look for connections the application forgets to close, before you raise the limit.

  • ERROR: VACUUM cannot run inside a transaction block

    Commands such as VACUUM, CREATE DATABASE, and CREATE INDEX CONCURRENTLY can't run inside BEGIN. Run them as a separate command, and in a graphical management tool, make sure automatic commit of each command (autocommit) is on.

PostgreSQL is an open source relational database management system, and many applications built with Python, Laravel, and Node.js store their data in it. This page includes three types of commands: SQL statements, which end with a semicolon and run inside psql; commands of psql itself, which start with a backslash, such as \dt; and tools you run from the server's command line, such as pg_dump and createdb.

Before any command that deletes or changes data, such as DROP, DELETE, or UPDATE, back up the database with pg_dump. Restore only backups from a trusted source, because a restore runs every command in the file. When you upgrade to a new PostgreSQL version, back up with the pg_dump tool of the new version.

The commands on this page match recent versions, and commands that were added or changed in the latest versions are marked in their explanation. End-of-support dates for each version are on the PostgreSQL lifecycle page. To lay out a long query in lines and indentation, use the SQL formatter, and commands for MySQL and MariaDB databases are on the MySQL commands page.

Did you know?

A VPS gives you full root access over SSH, so you can install the PostgreSQL version you choose and manage it with every command on this page. On a Python VPS and a Laravel VPS, you can also install PostgreSQL as your application's database.

VPS plans

PostgreSQL commands FAQ

How do I connect to PostgreSQL from the command line?

Connect with the psql tool, for example psql -h localhost -U app_user -d app_db, where the -h option sets the server, the -U option the user name, and the -d option the database. On the server where PostgreSQL is installed, the superuser usually connects with sudo -u postgres psql. To let scripts and backups connect without typing a password, save it in the ~/.pgpass file with 0600 permissions.

How do I back up and restore a PostgreSQL database?

The easiest way is to back up with pg_dump -Fc -f app_db.dump app_db, which creates a compressed backup file, and to restore with pg_restore -d app_db app_db.dump. The backup is consistent even while the website keeps running. The server's users and server-wide privileges aren't included in a database backup, so back them up separately with pg_dumpall --globals-only.

How do I give a user access to only one database?

Create a user with LOGIN, grant it CONNECT on the database, and revoke the general connect privilege with REVOKE CONNECT ON DATABASE app_db FROM PUBLIC. Then grant it privileges on the schema and the tables, and with ALTER DEFAULT PRIVILEGES also on tables created later. For an application, the simplest way is to make its user the owner of the database.

Why do I get the error permission denied for schema public?

In recent PostgreSQL versions, regular users can't create tables in the public schema, and by default only the database owner can. So an application that worked on an older version gets this error on a new database. To fix it, create the database with the application user as its OWNER, or give that user GRANT USAGE, CREATE ON SCHEMA public.

How do I find a slow query and stop it?

A query on pg_stat_activity with the condition state = 'active' shows the queries running now and how long each one has been running. Stop a query with SELECT pg_cancel_backend(pid), and the connection stays open. To understand why a query is slow, run EXPLAIN ANALYZE and check whether an index is missing.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement