Post

Postgres CLI Command CMDsheet

Introduction

In this blog post, we will explore some commonly used postgres commands that can help you manage your postgres dataabases.

Postgres Command Cmdsheet

1. Database Connection

Connecting to PostgreSQLpsql -U username -d database_name
Connecting with Specific Portpsql -h localhost -p 5432 -U username -d database_name

2. Database Operations

List all databases\l
Create a new databaseCREATE DATABASE db_name;
Drop a databaseDROP DATABASE db_name;
Connect to a specific database\c db_name

3. User Management

List all users\du
Create a new userCREATE USER username WITH PASSWORD 'password';
Grant user privileges on a databaseGRANT ALL PRIVILEGES ON DATABASE db_name TO username;
Change user passwordALTER USER username WITH PASSWORD 'new_password';

4. Table Operations

List all tables in a database\dt
Describe a table’s schema
(columns, types, etc.)
\d table_name
Create a tableCREATE TABLE table_name (id SERIAL PRIMARY KEY,name VARCHAR(100),age INT);
Drop a tableDROP TABLE table_name;

5. Basic Queries

Select all data from a tableSELECT * FROM table_name;
Insert data into a tableINSERT INTO table_name (name, age) VALUES ('John Doe', 30);
Update data in a tableUPDATE table_name SET age = 31 WHERE name = 'John Doe';
Delete data from a tableDELETE FROM table_name WHERE name = 'John Doe';

6. Indexing and Performance

Create an index on a columnCREATE INDEX idx_name ON table_name (column_name);
Drop an indexDROP INDEX idx_name;
Analyze the performance of a queryEXPLAIN ANALYZE SELECT * FROM table_name WHERE column_name = 'value';

7. Backup and Restore

Backup a databasepg_dump db_name > backup.sql
Restore a databasepsql -U username -d db_name -f backup.sql

8. Transaction Management

Begin a transactionBEGIN;
Commit a transactionCOMMIT;
Rollback a transactionROLLBACK;

9. System Information

Show current userSELECT current_user;
Show the PostgreSQL versionSELECT version();

10. Miscellaneous

List active connectionsSELECT * FROM pg_stat_activity;
Show disk usage for each tableSELECT relname AS "Table", pg_size_pretty
(pg_total_relation_size(relid)) AS "Size"
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC;
This post is licensed under CC BY 4.0 by the author.