-- CONNECTING TO THE DATABASE
\c database_name
-- Connects to a specific database.
-- LIST ALL DATABASES
\l
-- Lists all databases available in the PostgreSQL server.
-- LIST ALL TABLES IN THE CURRENT DATABASE
\dt
-- Lists all tables in the currently connected database.
-- CREATE A DATABASE
CREATE DATABASE my_database;
-- Creates a new database named "my_database".
-- DELETE A DATABASE
DROP DATABASE my_database;
-- Deletes the database named "my_database".
-- CREATE A TABLE
CREATE TABLE users (
id SERIAL PRIMARY KEY, -- Auto-incrementing primary key
username VARCHAR(100) UNIQUE, -- Unique username
email VARCHAR(255) NOT NULL, -- Email cannot be NULL
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Default timestamp
);
-- Creates a table "users" with fields id, username, email, and created_at.
-- DELETE A TABLE
DROP TABLE users;
-- Deletes the "users" table.
-- ALTER A TABLE
ALTER TABLE users ADD COLUMN age INT;
-- Adds a new column "age" to the "users" table.
ALTER TABLE users DROP COLUMN age;
-- Removes the "age" column from the "users" table.
-- INSERT DATA INTO A TABLE
INSERT INTO users (username, email) VALUES ('JohnDoe', 'john@example.com');
-- Inserts a record into the "users" table.
-- INSERT MULTIPLE RECORDS
INSERT INTO users (username, email) VALUES
('JaneDoe', 'jane@example.com'),
('MikeSmith', 'mike@example.com');
-- Inserts multiple records at once.
-- SELECT DATA
SELECT * FROM users;
-- Fetches all rows from the "users" table.
SELECT username, email FROM users WHERE id = 1;
-- Fetches specific columns where the condition is met.
-- UPDATE DATA
UPDATE users SET email = 'john.new@example.com' WHERE id = 1;
-- Updates the "email" field for the record where id = 1.
-- DELETE DATA
DELETE FROM users WHERE id = 2;
-- Deletes the record where id = 2.
-- CREATE AN INDEX
CREATE INDEX idx_users_email ON users(email);
-- Creates an index on the "email" column of the "users" table.
-- DROP AN INDEX
DROP INDEX idx_users_email;
-- Removes the index on the "email" column.
-- JOIN OPERATIONS
SELECT users.id, users.username, orders.amount
FROM users
JOIN orders ON users.id = orders.user_id;
-- Performs an INNER JOIN between "users" and "orders" based on user_id.
-- LEFT JOIN
SELECT users.username, orders.amount
FROM users
LEFT JOIN orders ON users.id = orders.user_id;
-- Fetches all users, and their corresponding orders if available.
-- GROUP BY
SELECT username, COUNT(*) AS order_count
FROM orders
GROUP BY username;
-- Groups data by "username" and counts their orders.
-- ORDER BY
SELECT * FROM users ORDER BY created_at DESC;
-- Fetches all rows, ordered by the "created_at" column in descending order.
-- AGGREGATE FUNCTIONS
SELECT COUNT(*) AS total_users, AVG(age) AS average_age FROM users;
-- Counts all users and calculates the average age.
-- TRANSACTIONS
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
-- Ensures atomicity. If any statement fails, use ROLLBACK.
-- ROLLBACK TRANSACTION
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
ROLLBACK;
-- Rolls back any changes made within the transaction.
-- CREATE A VIEW
CREATE VIEW user_emails AS
SELECT id, username, email FROM users;
-- Creates a view "user_emails" for commonly used SELECT queries.
-- SELECT FROM A VIEW
SELECT * FROM user_emails;
-- Fetches data from the "user_emails" view.
-- DELETE A VIEW
DROP VIEW user_emails;
-- Deletes the "user_emails" view.
-- GRANT PERMISSIONS
GRANT SELECT, INSERT ON users TO role_name;
-- Grants SELECT and INSERT permissions on "users" to "role_name".
-- REVOKE PERMISSIONS
REVOKE SELECT, INSERT ON users FROM role_name;
-- Revokes SELECT and INSERT permissions from "role_name".
-- CREATE A ROLE
CREATE ROLE read_only_user WITH LOGIN PASSWORD 'password';
-- Creates a role that can log in with a specific password.
-- DELETE A ROLE
DROP ROLE read_only_user;
-- Deletes the role "read_only_user".
-- BACKUP A DATABASE
pg_dump my_database > backup.sql
-- Creates a backup of "my_database" to the file "backup.sql".
-- RESTORE A DATABASE
psql my_database < backup.sql
-- Restores a database from the "backup.sql" file.
-- LIST ACTIVE CONNECTIONS
SELECT * FROM pg_stat_activity;
-- Lists all active connections to the database.
-- TERMINATE CONNECTIONS
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'my_database'
AND pid <> pg_backend_pid();
-- Terminates all connections to "my_database" except the current one.