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:

For example:

If the database is running on a different server, specify the host and port:

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:

After a successful connection, the psql prompt appears:

From there, you can start managing databases, creating tables, querying data, and running administrative commands. To exit the session, use:

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:

Connect to a different database:

List all tables in the current database:

Describe the structure of a table:

List schemas:

Display available commands:

Get help for SQL commands:

Exit the psql session:

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:

List all databases:

Connect to a database:

Rename a database:

Delete a database:

View information about the current connection:

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:

View table definitions:

Add a column:

Rename a table:

Remove a column:

Delete a table:

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:

Retrieve specific columns:

Filter results:

Sort results:

Limit returned rows:

Aggregate data:

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:

Update existing data:

Delete rows:

Remove all rows from a table:

Insert data returned by a query:

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:

Create a user with a password:

Grant privileges on a database:

Grant privileges on a table:

Assign a role to another user:

Change a user’s password:

Remove a role or user:

List roles:

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:

Create a unique index:

View indexes for a table:

Remove an index:

Create a multi-column index:

Rebuild an index:

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:

List schemas:

Create a table in a schema:

Set the default schema:

Rename a schema:

Delete a schema:

Delete a schema and all its objects:

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:

Create a compressed custom-format backup:

Restore a SQL backup:

Restore a custom-format backup:

Back up all databases:

Restore all databases:

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:

Execute one or more statements:

Cancel all changes made during the transaction:

Create a savepoint:

Roll back to a savepoint:

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

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:

  1. Use \x auto for wide query results: Large rows containing JSON, arrays, or many columns become much easier to read. Keep this enabled in your psql profile to improve day-to-day troubleshooting.
  2. Master \gexec for 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.
  3. Use RETURNING to reduce round trips: Many developers run an INSERT followed by a SELECT to retrieve generated values. INSERT ... RETURNING eliminates the extra query and reduces application latency.
  4. Create indexes concurrently in production: Standard CREATE INDEX can block writes. Use CREATE INDEX CONCURRENTLY when adding indexes to busy production tables to avoid service interruptions.
  5. Use \watch as 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:

2. Connect to the database:

3. Create a table:

4. Insert data:

5. Verify the inserted record:

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:

2. Filter records with a condition:

3. Update a record:

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:

2. Delete a specific record:

3. Confirm the deletion:

You can also run the deletion inside a transaction to verify the results before committing:

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:

Safer approach:

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:

If the results are not what you expected, you can cancel the changes before committing:

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:

To view estimated execution costs and actual execution statistics, use:

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:

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:

Grant only the necessary privileges:

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.