PostgreSQL Cheatsheet

Introduction

PostgreSQL is a powerful, open-source relational database management system (RDBMS) known for its reliability and extensibility. It supports SQL (Structured Query Language) and offers a wide range of features, making it a popular choice for both small and large-scale applications.

This page contain cheatsheet of commonly used PostgreSQL commands.

PostgreSQL Basics

CommandDescription
\qQuit psql command-line utility
\lList all databases
\c <database>Connect to a specific database
\dtList all tables in the current database
\d <table>Show details of a specific table
\duList all users
\eOpen the default text editor to edit a query

Database Operations

CommandDescription
CREATE DATABASE <name>Create a new database
DROP DATABASE <name>Delete an existing database
ALTER DATABASE <name> RENAME TO <new>Rename a database

Table Operations

CommandDescription
CREATE TABLE <table>Create a new table
DROP TABLE <table>Delete an existing table
ALTER TABLE <table> ADD COLUMN <column>Add a new column to an existing table
ALTER TABLE <table> DROP COLUMN <column>Remove a column from an existing table

Data Manipulation

CommandDescription
INSERT INTO <table> VALUES (...)Insert data into a table
SELECT * FROM <table>Retrieve all records from a table
UPDATE <table> SET <column> = <value>Update data in a table
DELETE FROM <table> WHERE <condition>Delete data from a table based on a condition

Querying Data

CommandDescription
SELECT <columns> FROM <table> WHERE <condition>Retrieve specific data based on a condition
ORDER BY <column>Sort the result set by a specific column
GROUP BY <column>Group rows based on a specific column
JOIN <table> ON <condition>Combine rows from two or more tables

Security

CommandDescription
CREATE USER <user> WITH PASSWORD '<password>'Create a new user
ALTER USER <user> WITH SUPERUSERGrant superuser privileges to a user
REVOKE <permission> ON <object> FROM <user>Revoke specific permissions from a user

These are just some of the basic PostgreSQL commands and operations. Refer to the PostgreSQL Documentation for more in-depth information and advanced features.