postgresql
A quick reference for common PostgreSQL commands and queries.
User Authentication
Commands for logging into PostgreSQL and managing sessions.
Login to PostgreSQL
Login using the `psql` cli.
psql -U username -d database_name
Permissions
Commands for managing user roles and permissions in PostgreSQL.
Create a user
Creates a new user in PostgreSQL with a password.
CREATE USER username WITH PASSWORD 'password';
Grant privileges to a user
Grants specific permissions to a user on a database.
GRANT privilege_type ON table_name TO username;
Grant all privileges to a user
Grants all privileges on a database to a user.
GRANT ALL PRIVILEGES ON DATABASE database_name TO username;
Grant privileges on all tables in a schema
Grants specific privileges on all tables in a schema.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO username;
Grant role to another user
Assigns a role to a user.
GRANT role_name TO username;
Revoke privileges from a user
Revokes specific permissions from a user.
REVOKE privilege_type ON table_name FROM username;
Drop a user
Deletes a user from PostgreSQL.
DROP USER username;
Database Management
Commands related to database creation, deletion and listing.
Create a database
Creates a new database in PostgreSQL.
CREATE DATABASE database_name;
Drop a database
Deletes a database from PostgreSQL.
DROP DATABASE database_name;
List all databases
Lists all databases in PostgreSQL.
\l
Schema Management
Commands related to managing schemas in PostgreSQL.
Create a schema
Defines a new schema in the database.
CREATE SCHEMA schema_name;
Drop a schema
Removes a schema and all objects within it.
DROP SCHEMA schema_name CASCADE;
Table Management
Commands related to table creation, modification and deletion.
Create a table
Creates a new table in the database.
CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(100), created_at TIMESTAMP);
List all tables
Shows all tables in the current database.
\dt
Drop a table
Deletes a table from the database.
DROP TABLE users;
Querying Data
Commands for querying and manipulating data in PostgreSQL.
Select all data from a table
Retrieves all rows from a specific table.
SELECT * FROM users;
Select specific columns
Retrieves specific columns from a table.
SELECT username, created_at FROM users;
Insert data into a table
Inserts a new row of data into a table.
INSERT INTO users (username, created_at)VALUES ('john_doe', NOW());
Insert multiple rows
Inserts multiple rows in a single query.
INSERT INTO users (username, created_at)VALUES('john_doe', NOW()),('jane_smith', NOW());
Update a row in a table
Modifies data in a specific row.
UPDATE users SET username = 'new_name' WHERE id = 1;
Indexing
Commands for creating and managing indexes.
Create an index
Creates an index on a specific column to speed up queries.
CREATE INDEX index_name ON table_name (column_name);
Drop an index
Deletes an index.
DROP INDEX index_name;