What Are PostgreSQL Commands?
PostgreSQL commands fall into two distinct categories: psql meta-commands (processed locally by the terminal client, starting with a backslash \) and standard PostgreSQL SQL Commands (processed by the server and ending with a semicolon ;).
These commands allow users to manage databases, tables, users, roles, and the data itself. They include both SQL statements like SELECT, INSERT, UPDATE, and DELETE, and meta-commands in the psql command-line interface (such as \dt for listing tables).
PostgreSQL commands are fundamental for database creation, modification, data retrieval, security, and maintenance.
This structured reference guide highlights the most frequently used commands for database administration, navigation, and data manipulation.
This structured reference guide highlights the most frequently used commands for database administration, navigation, and data manipulation.
How to Connect to PostgreSQL
To connect to a PostgreSQL database, you typically use the psql command-line client. The basic syntax is:
|
1 |
psql -U app_user -d company_db |
For example:
|
1 |
psql --username=app_user --dbname=company_db |
If the database is running on a different server, specify the host and port:
|
1 |
psql -h db.example.com -p 5432 -U app_user -d company_db |
After running the command, PostgreSQL prompts you for a password if authentication is required. Once connected, you can execute SQL statements and psql meta-commands directly from the terminal.
You can also connect using a connection string:
|
1 |
psql "postgresql://app_user:StrongPassword123@localhost:5432/company_db" |
After a successful connection, the psql prompt appears:
|
1 |
mydatabase=# |
From there, you can start managing databases, creating tables, querying data, and running administrative commands. To exit the session, use:
|
1 |
\q |
Understanding PostgreSQL Commands
Basic psql Commands
The psql client includes meta-commands that help you navigate and manage PostgreSQL databases. These commands begin with a backslash (\) and are executed directly by psql, not by the PostgreSQL server.
List available databases:
|
1 |
\l |
Connect to a different database:
|
1 |
\c db_name |
List all tables in the current database:
|
1 |
\dt |
Describe the structure of a table:
|
1 |
\d your_table |
List schemas:
|
1 |
\dn |
Display available commands:
|
1 |
\? |
Get help for SQL commands:
|
1 |
\h |
Exit the psql session:
|
1 |
\q |
These commands are useful for exploring database objects and managing sessions without writing SQL queries.
PostgreSQL Database Commands
Database commands are used to create, modify, and remove databases.
Create a new database:
|
1 |
CREATE DATABASE my_store_db; |
List all databases:
|
1 |
\l |
Connect to a database:
|
1 |
\c my_store_db; |
Rename a database:
|
1 |
ALTER DATABASE my_store_db RENAME TO newdatabase; |
Delete a database:
|
1 |
DROP DATABASE my_store_db; |
View information about the current connection:
|
1 |
\conninfo |
These commands help administrators organize and manage multiple databases on a PostgreSQL server.
PostgreSQL Table Commands
Table commands are used to create and manage database tables.
Create a table:
|
1 2 3 4 5 |
CREATE TABLE team_members ( member_id SERIAL PRIMARY KEY, full_name VARCHAR(120), role_name VARCHAR(80) ); |
View table definitions:
|
1 |
\d team_members; |
Add a column:
|
1 2 |
ALTER TABLE team_members ADD COLUMN work_email VARCHAR(255); |
Rename a table:
|
1 2 |
ALTER TABLE team_members RENAME TO company_staff; |
Remove a column:
|
1 2 |
ALTER TABLE company_staff DROP COLUMN work_email; |
Delete a table:
|
1 |
DROP TABLE company_staff; |
These commands define how data is structured and stored within a database.
PostgreSQL Data Query Commands
Data query commands retrieve information from tables.
Retrieve all rows:
|
1 2 |
SELECT * FROM staff_members; |
Retrieve specific columns:
|
1 2 |
SELECT full_name, team_name FROM staff_members; |
Filter results:
|
1 2 3 |
SELECT * FROM staff_members WHERE team_name = 'Marketing'; |
Sort results:
|
1 2 3 |
SELECT * FROM staff_members ORDER BY full_name ASC; |
Limit returned rows:
|
1 2 3 |
SELECT * FROM staff_members LIMIT 5; |
Aggregate data:
|
1 2 3 |
SELECT team_name, COUNT(*) AS total_staff FROM staff_members GROUP BY team_name; |
These commands are used to search, analyze, and report on stored data.
PostgreSQL Data Modification Commands
Data modification commands add, update, and remove records.
Insert a new row:
|
1 2 |
INSERT INTO staff_members (full_name, team_name) VALUES ('Jane Doe', 'Operations'); |
Update existing data:
|
1 2 3 |
UPDATE staff_members SET team_name = 'Finance' WHERE member_id = 3; |
Delete rows:
|
1 2 |
DELETE FROM staff_members WHERE member_id = 3; |
Remove all rows from a table:
|
1 |
TRUNCATE TABLE staff_members; |
Insert data returned by a query:
|
1 2 3 4 |
INSERT INTO archived_staff_members SELECT * FROM staff_members WHERE team_name = 'Operations'; |
These commands allow users to maintain accurate and up-to-date information within PostgreSQL databases.
PostgreSQL User and Role Commands
PostgreSQL uses roles to manage authentication and permissions. A role can function as a user, a group, or both.
Create a new role:
|
1 |
CREATE ROLE reporting_team; |
Create a user with a password:
|
1 2 |
CREATE USER dashboard_user WITH PASSWORD 'StrongPass_2026'; |
Grant privileges on a database:
|
1 2 3 |
GRANT CONNECT ON DATABASE company_db TO dashboard_user; |
Grant privileges on a table:
|
1 2 3 |
GRANT SELECT, UPDATE ON staff_members TO dashboard_user; |
Assign a role to another user:
|
1 |
GRANT reporting_team TO dashboard_user; |
Change a user’s password:
|
1 2 |
ALTER USER dashboard_user WITH PASSWORD 'UpdatedPass_2026'; |
Remove a role or user:
|
1 |
DROP ROLE dashboard_user; |
List roles:
|
1 |
\du |
These commands help control access to database resources and enforce security policies.
PostgreSQL Index Commands
Indexes improve query performance by allowing PostgreSQL to locate data more efficiently.
Create an index:
|
1 2 |
CREATE INDEX idx_staff_full_name ON staff_members(full_name); |
Create a unique index:
|
1 2 |
CREATE UNIQUE INDEX idx_staff_work_email ON staff_members(work_email); |
View indexes for a table:
|
1 |
\d staff_members; |
Remove an index:
|
1 |
DROP INDEX idx_staff_full_name; |
Create a multi-column index:
|
1 2 |
CREATE INDEX idx_staff_team_name ON staff_members(team_name, full_name); |
Rebuild an index:
|
1 |
REINDEX INDEX idx_staff_full_name; |
Indexes can significantly speed up searches, joins, and sorting operations, but they also require storage and maintenance during data updates.
PostgreSQL Schema Commands
Schemas organize database objects into logical namespaces. They help separate applications, users, or environments within the same database.
Create a schema:
|
1 |
CREATE SCHEMA reporting; |
List schemas:
|
1 |
\dn |
Create a table in a schema:
|
1 2 3 4 |
CREATE TABLE reporting.monthly_reports ( report_id SERIAL PRIMARY KEY, created_on DATE ); |
Set the default schema:
|
1 |
SET search_path TO reporting; |
Rename a schema:
|
1 2 |
ALTER SCHEMA reporting RENAME TO reporting_archive; |
Delete a schema:
|
1 |
DROP SCHEMA reporting; |
Delete a schema and all its objects:
|
1 |
DROP SCHEMA reporting_archive CASCADE; |
Schemas provide a way to group related database objects and avoid naming conflicts.
PostgreSQL Backup and Restore Commands
PostgreSQL provides command-line utilities for creating backups and restoring databases.
Create a backup using pg_dump:
|
1 |
pg_dump --username=db_admin --dbname=company_db --file=company_db_backup.sql |
Create a compressed custom-format backup:
|
1 |
pg_dump -U db_admin -Fc company_db > company_db.dump |
Restore a SQL backup:
|
1 |
psql --username=db_admin --dbname=company_db --file=company_db_backup.sql |
Restore a custom-format backup:
|
1 |
pg_restore --username=db_admin --dbname=company_db company_db.dump |
Back up all databases:
|
1 |
pg_dumpall --username=db_admin --file=cluster_backup.sql |
Restore all databases:
|
1 |
psql --username=db_admin --file=cluster_backup.sql |
Regular backups are essential for disaster recovery, migration, and protecting against data loss.
PostgreSQL Transaction Commands
Transactions allow multiple operations to be executed as a single unit of work. They help maintain data consistency and integrity.
Start a transaction:
|
1 |
BEGIN; |
Execute one or more statements:
|
1 2 3 4 5 6 7 8 9 |
UPDATE wallet_accounts SET current_balance = current_balance - 250 WHERE account_id = 101; UPDATE wallet_accounts SET current_balance = current_balance + 250 WHERE account_id = 202; COMMIT; |
Cancel all changes made during the transaction:
|
1 |
ROLLBACK; |
Create a savepoint:
|
1 |
SAVEPOINT payment_checkpoint; |
Roll back to a savepoint:
|
1 |
ROLLBACK TO SAVEPOINT payment_checkpoint; |
Transactions ensure that operations either complete successfully as a group or leave the database unchanged if an error occurs.
Tips from the expert
Perry Clark
Professional Services Consultant
Perry Clark is a seasoned open source consultant with NetApp. Perry is passionate about delivering high-quality solutions and has a strong background in various open source technologies and methodologies, making him a valuable asset to any project.
In my experience, here are tips that can help you better manage and use PostgreSQL commands:
- Use
\x autofor wide query results: Large rows containing JSON, arrays, or many columns become much easier to read. Keep this enabled in yourpsqlprofile to improve day-to-day troubleshooting. - Master
\gexecfor dynamic administration: Generate SQL with a query and execute the results immediately. This is extremely useful for bulk maintenance tasks across multiple tables or schemas. - Use
RETURNINGto reduce round trips: Many developers run anINSERTfollowed by aSELECTto retrieve generated values.INSERT ... RETURNINGeliminates the extra query and reduces application latency. - Create indexes concurrently in production: Standard
CREATE INDEXcan block writes. UseCREATE INDEX CONCURRENTLYwhen adding indexes to busy production tables to avoid service interruptions. - Use
\watchas a lightweight monitoring tool: Any query can become a real-time dashboard. This is invaluable during deployments, incident investigations, and performance tuning sessions.
Common PostgreSQL Command Examples
Create a Database, Table, and Insert Data
The following example creates a database, creates a table, and inserts a record.
1. Create a database:
|
1 |
CREATE DATABASE project_db; |
2. Connect to the database:
|
1 |
\c project_db; |
3. Create a table:
|
1 2 3 4 5 |
CREATE TABLE staff_records ( staff_id SERIAL PRIMARY KEY, full_name VARCHAR(120), team_name VARCHAR(60) ); |
4. Insert data:
|
1 2 |
INSERT INTO staff_records (full_name, team_name) VALUES ('John Smith', 'Technology'); |
5. Verify the inserted record:
|
1 2 |
SELECT * FROM staff_records; |
This workflow demonstrates the basic steps required to start working with a new PostgreSQL database.
Query and Update Records
Once data exists in a table, you can retrieve and modify it using SELECT and UPDATE statements.
1. Query all records:
|
1 2 |
SELECT * FROM team_members; |
2. Filter records with a condition:
|
1 2 3 |
SELECT * FROM team_members WHERE team = 'Product'; |
3. Update a record:
|
1 2 3 |
UPDATE team_members SET team = 'Operations' WHERE full_name = 'John McCain'; |
4. Verify the update:
SELECT *
FROM team_members
WHERE full_name = ‘John McCain’;
Using a WHERE clause is important because it limits the update to specific rows.
Delete Records Safely
When deleting data, always review the affected rows before running a DELETE statement.
1. Check which records will be removed:
|
1 2 3 |
SELECT * FROM team_members WHERE member_id = 5; |
2. Delete a specific record:
|
1 2 |
DELETE FROM team_members WHERE member_id = 5; |
3. Confirm the deletion:
|
1 2 3 |
SELECT * FROM team_members WHERE member_id = 5; |
You can also run the deletion inside a transaction to verify the results before committing:
|
1 2 3 4 5 6 7 8 9 |
BEGIN; DELETE FROM team_members WHERE member_id = 5; SELECT * FROM team_members; ROLLBACK; |
Using transactions and precise WHERE clauses helps prevent accidental data loss.
PostgreSQL Commands Best Practices
Here are some of the ways to improve your use of PostgreSQL commands.
1. Always Use WHERE with UPDATE and DELETE
The UPDATE and DELETE commands affect every row in a table when a WHERE clause is omitted. This can lead to accidental data loss or large-scale changes that are difficult to reverse.
Unsafe example:
|
1 2 |
UPDATE staff_records SET team_name = 'Operations'; |
Safer approach:
|
1 2 3 |
UPDATE staff_records SET team_name = 'Operations' WHERE staff_id = 25; |
Before running an UPDATE or DELETE, execute a SELECT statement with the same WHERE condition to verify which rows will be affected.
2. Use Transactions for Risky Changes
Transactions allow you to group multiple operations and either commit them together or roll them back if something goes wrong. This is especially useful when modifying large amounts of data.
Example:
|
1 2 3 4 5 6 7 |
BEGIN; UPDATE staff_records SET team_name = 'Customer Success' WHERE team_name = 'Operations'; COMMIT; |
If the results are not what you expected, you can cancel the changes before committing:
|
1 |
ROLLBACK; |
Using transactions reduces the risk of accidental changes and helps maintain data consistency.
3. Use EXPLAIN Before Optimizing Queries
The EXPLAIN command shows how PostgreSQL plans to execute a query. It helps identify slow operations such as sequential scans, expensive joins, or inefficient sorting.
Example:
|
1 2 3 4 |
EXPLAIN SELECT * FROM staff_records WHERE team_name = 'Technology'; |
To view estimated execution costs and actual execution statistics, use:
|
1 2 3 4 |
EXPLAIN ANALYZE SELECT * FROM staff_records WHERE team_name = 'Technology'; |
Reviewing execution plans before making changes helps ensure optimization efforts are focused on real performance bottlenecks.
4. Use Indexes on Frequently Filtered Columns
Indexes improve query performance by reducing the amount of data PostgreSQL must scan. They are most effective on columns that are frequently used in WHERE, JOIN, and ORDER BY clauses.
Create an index:
|
1 2 |
CREATE INDEX idx_staff_records_team_name ON staff_records(team_name); |
For example, if queries often filter by department, an index can significantly reduce query execution time. However, indexes are not free. Each index consumes storage space and adds overhead to INSERT, UPDATE, and DELETE operations. Create indexes only when they provide measurable benefits.
5. Avoid Using the postgres Superuser for Applications
The default postgres account has unrestricted access to the entire PostgreSQL server. Using it for applications increases the risk of accidental changes and security issues.
Instead, create a dedicated user with only the permissions required by the application:
|
1 2 |
CREATE USER reporting_user WITH PASSWORD 'StrongPassword_2026'; |
Grant only the necessary privileges:
|
1 2 3 |
GRANT SELECT, INSERT, UPDATE, DELETE ON staff_records TO reporting_user; |
Following the principle of least privilege limits potential damage if application credentials are compromised and improves overall database security.
Running PostgreSQL in Production with NetApp Instaclustr
The commands in this guide cover the day-to-day work of creating databases, querying and modifying data, managing roles, and maintaining your environment, but running PostgreSQL reliably in production also means handling provisioning, monitoring, high availability, backups, and version upgrades. NetApp Instaclustr offers a fully hosted and managed PostgreSQL service that runs in the cloud or on-premises and delivers a production-ready PostgreSQL cluster backed by 24×7 expert support, letting your teams focus on building applications instead of administering database infrastructure.
Key capabilities of Instaclustr for PostgreSQL:
- Fully managed and 100% open source: Instaclustr customizes and optimizes PostgreSQL on all major cloud providers and on-premises data centers, with no proprietary features or lock-in, running in your cloud account or theirs.
- Industry-leading 99.99% SLA: Instaclustr’s availability SLAs for PostgreSQL set the service apart and are backed by continuous maintenance and version upgrades.
- Multi-region replication: Read replicas can be created in secondary regions for high availability, minimizing latency and maximizing uptime.
- PGBouncer connection pooling: A lightweight connection pooler enhances database performance and scalability through efficient connection management and resource optimization.
- DevOps-friendly provisioning and monitoring: Provision via console, REST API, or Terraform, and monitor through built-in dashboards or the Prometheus API and other integrations.
- Enterprise-grade security and compliance: The platform is SOC2, ISO27001, and ISO27018 certified, meets GDPR requirements, and offers PCI-compliant solutions.
- pgvector for AI workloads: Instaclustr supports the pgvector extension, enabling efficient storage and similarity search of high-dimensional vector data so you can power RAG and other AI applications directly within PostgreSQL.
Ready to run PostgreSQL without the operational overhead? Explore Instaclustr’s fully managed PostgreSQL service and spin up a production-ready cluster in minutes.