Postgres Essentials - Cheat Sheet
Basic Commands
Command | Description |
---|
psql | Launches the PostgreSQL command-line interface |
createdb [database_name] | Creates a new database |
dropdb [database_name] | Deletes a database |
createuser [username] | Creates a new user |
dropuser [username] | Deletes a user |
Database Management
Command | Description |
---|
\l | Lists all databases |
\c [database_name] | Connects to a specific database |
\dt | Lists all tables in the current database |
\d [table_name] | Shows information about a specific table |
\du | Lists all users |
\password [username] | Changes the password for a user |
Table Management
Command | Description |
---|
CREATE TABLE [table_name] ([column_name] [data_type], ...) | Creates a new table |
DROP TABLE [table_name] | Deletes a table |
ALTER TABLE [table_name] ADD COLUMN [column_name] [data_type] | Adds a new column to a table |
ALTER TABLE [table_name] DROP COLUMN [column_name] | Deletes a column from a table |
Data Manipulation
Command | Description |
---|
INSERT INTO [table_name] ([column_name], ...) VALUES ([value], ...) | Inserts a new row into a table |
SELECT [column_name], ... FROM [table_name] [WHERE condition] | Retrieves data from a table |
UPDATE [table_name] SET [column_name]=[value] [WHERE condition] | Updates existing data in a table |
DELETE FROM [table_name] [WHERE condition] | Deletes data from a table |
Transactions
Command | Description |
---|
BEGIN; | Starts a new transaction |
COMMIT; | Commits a transaction |
ROLLBACK; | Rolls back a transaction |