What is SQL?
SQL (Structured Query Language) is used to communicate with databases. It allows you to query, manipulate, and define data. Most modern applications use SQL databases like MySQL, PostgreSQL, SQLite, or Microsoft SQL Server.
🗄️ Relational Databases
Data is stored in tables with rows and columns, connected by relationships.
📊 CRUD Operations
Create, Read, Update, Delete — the four basic operations on data.
🔍 Query Power
Filter, sort, join, and aggregate data with powerful query capabilities.
SELECT Queries
The SELECT statement retrieves data from one or more tables.
-- Select all columns from a table SELECT * FROM users; -- Select specific columns SELECT first_name, last_name, email FROM users; -- Select with alias SELECT first_name AS "First Name", age AS "Years" FROM users; -- Select distinct values (remove duplicates) SELECT DISTINCT city FROM users; -- Limit results SELECT * FROM products LIMIT 10; -- Example database: e-commerce CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100) UNIQUE, age INT, city VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Filtering & Sorting
Use WHERE to filter rows, ORDER BY to sort, and operators for conditions.
-- Basic comparison operators SELECT * FROM users WHERE age >= 18; SELECT * FROM users WHERE city = 'New York'; -- Text pattern matching (LIKE) SELECT * FROM users WHERE email LIKE '%@gmail.com'; SELECT * FROM users WHERE first_name LIKE 'J%'; -- Starts with J SELECT * FROM users WHERE last_name LIKE '%son'; -- Ends with son -- Logical operators (AND, OR, NOT) SELECT * FROM users WHERE age BETWEEN 25 AND 35; SELECT * FROM users WHERE city IN ('New York', 'Los Angeles', 'Chicago'); SELECT * FROM users WHERE city NOT IN ('New York', 'LA'); -- Sorting results SELECT * FROM users ORDER BY created_at DESC; -- Newest first SELECT * FROM users ORDER BY last_name ASC, first_name ASC;
JOINs — Combining Tables
JOINs combine data from multiple tables based on relationships.
-- Create related tables CREATE TABLE orders ( id INT PRIMARY KEY, user_id INT, product VARCHAR(100), amount DECIMAL(10,2), FOREIGN KEY (user_id) REFERENCES users(id) ); -- INNER JOIN (only matching rows) SELECT users.first_name, users.last_name, orders.product, orders.amount FROM users INNER JOIN orders ON users.id = orders.user_id; -- LEFT JOIN (all users, even without orders) SELECT users.first_name, users.last_name, COALESCE(orders.product, 'No orders') AS product FROM users LEFT JOIN orders ON users.id = orders.user_id; -- Multiple JOINs SELECT u.first_name, o.product, o.amount, p.category FROM users u JOIN orders o ON u.id = o.user_id JOIN products p ON o.product_id = p.id; -- Self JOIN (employee-manager relationship) SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;
Aggregate Functions & Grouping
Aggregate functions perform calculations on sets of rows. GROUP BY groups rows for aggregation.
-- Common aggregate functions SELECT COUNT(*) FROM users; -- Total users SELECT AVG(age) FROM users; -- Average age SELECT SUM(amount) FROM orders; -- Total sales SELECT MAX(amount) FROM orders; -- Highest order SELECT MIN(amount) FROM orders; -- Lowest order -- GROUP BY SELECT city, COUNT(*) AS user_count FROM users GROUP BY city ORDER BY user_count DESC; -- GROUP BY with multiple columns SELECT city, age, COUNT(*) FROM users GROUP BY city, age; -- HAVING (filter after GROUP BY) SELECT city, COUNT(*) AS user_count FROM users GROUP BY city HAVING COUNT(*) > 5; -- Complex example: monthly sales SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, COUNT(*) AS total_orders, SUM(amount) AS revenue, AVG(amount) AS avg_order_value FROM orders WHERE order_date >= '2024-01-01' GROUP BY month ORDER BY month DESC;
INSERT, UPDATE, DELETE
Modify data with INSERT (add), UPDATE (modify), and DELETE (remove).
-- INSERT single row INSERT INTO users (first_name, last_name, email, age, city) VALUES ('John', 'Doe', 'john@example.com', 30, 'Boston'); -- INSERT multiple rows INSERT INTO users (first_name, last_name, email, age, city) VALUES ('Jane', 'Smith', 'jane@example.com', 25, 'Boston'), ('Bob', 'Johnson', 'bob@example.com', 35, 'Chicago'); -- UPDATE (always use WHERE!) UPDATE users SET city = 'New York', age = 31 WHERE id = 1; -- UPDATE with calculation UPDATE orders SET amount = amount * 1.1 -- 10% increase WHERE order_date >= '2024-01-01'; -- DELETE (always use WHERE!) DELETE FROM users WHERE id = 5; -- Delete all rows (be careful!) DELETE FROM temporary_data; -- removes all rows TRUNCATE TABLE temporary_data; -- faster, resets auto-increment -- Safe practice: SELECT before DELETE SELECT * FROM users WHERE last_login < '2023-01-01'; -- Check first DELETE FROM users WHERE last_login < '2023-01-01'; -- Then delete
Schema Design & Constraints
Good database design includes proper normalization, primary keys, foreign keys, and constraints.
-- Comprehensive table creation CREATE TABLE products ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(200) NOT NULL, sku VARCHAR(50) UNIQUE NOT NULL, price DECIMAL(10,2) CHECK (price >= 0), category_id INT, in_stock BOOLEAN DEFAULT TRUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL ); -- Add index for performance CREATE INDEX idx_products_name ON products(name); -- Add constraint after creation ALTER TABLE products ADD CONSTRAINT chk_price CHECK (price >= 0); -- Create a view (virtual table) CREATE VIEW active_users AS SELECT id, first_name, last_name, email FROM users WHERE last_login > DATE_SUB(NOW(), INTERVAL 30 DAY); -- Use the view like a table SELECT * FROM active_users; -- Normalization example: separate tables -- Instead of storing addresses in users table, normalize: CREATE TABLE addresses ( id INT PRIMARY KEY, user_id INT, street VARCHAR(255), city VARCHAR(100), country VARCHAR(100), FOREIGN KEY (user_id) REFERENCES users(id) );
🛠 Project: Library Database System
Build a complete library management system with books, members, and loans.
-- Create database schema CREATE DATABASE library; USE library; -- Books table CREATE TABLE books ( id INT PRIMARY KEY AUTO_INCREMENT, isbn VARCHAR(20) UNIQUE NOT NULL, title VARCHAR(255) NOT NULL, author VARCHAR(100) NOT NULL, year_published INT, genre VARCHAR(50), available_copies INT DEFAULT 1, total_copies INT DEFAULT 1 ); -- Members table CREATE TABLE members ( id INT PRIMARY KEY AUTO_INCREMENT, member_number VARCHAR(20) UNIQUE NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE, phone VARCHAR(20), join_date DATE DEFAULT CURRENT_DATE ); -- Loans table CREATE TABLE loans ( id INT PRIMARY KEY AUTO_INCREMENT, book_id INT NOT NULL, member_id INT NOT NULL, loan_date DATE NOT NULL, due_date DATE NOT NULL, return_date DATE, FOREIGN KEY (book_id) REFERENCES books(id), FOREIGN KEY (member_id) REFERENCES members(id) ); -- Insert sample data INSERT INTO books (isbn, title, author, year_published, genre, total_copies, available_copies) VALUES ('978-0132350884', 'Clean Code', 'Robert C. Martin', 2008, 'Programming', 3, 3), ('978-0201616224', 'The Pragmatic Programmer', 'Andrew Hunt', 1999, 'Programming', 2, 2), ('978-0596007126', 'Head First SQL', 'Lynn Beighley', 2007, 'Database', 1, 1); INSERT INTO members (member_number, first_name, last_name, email, phone) VALUES ('LIB001', 'John', 'Smith', 'john@email.com', '555-0101'), ('LIB002', 'Sarah', 'Johnson', 'sarah@email.com', '555-0102'); -- Borrow a book (procedure) DELIMITER $$ CREATE PROCEDURE borrow_book( IN p_member_number VARCHAR(20), IN p_isbn VARCHAR(20) ) BEGIN DECLARE v_book_id INT; DECLARE v_member_id INT; DECLARE v_available INT; -- Get book info SELECT id, available_copies INTO v_book_id, v_available FROM books WHERE isbn = p_isbn; -- Get member info SELECT id INTO v_member_id FROM members WHERE member_number = p_member_number; -- Check availability IF v_available > 0 THEN -- Create loan record INSERT INTO loans (book_id, member_id, loan_date, due_date) VALUES (v_book_id, v_member_id, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 14 DAY)); -- Decrease available copies UPDATE books SET available_copies = available_copies - 1 WHERE id = v_book_id; SELECT 'Book borrowed successfully!' AS message; ELSE SELECT 'No copies available!' AS message; END IF; END$$ DELIMITER ; -- Query: Books currently on loan SELECT m.first_name, m.last_name, b.title, b.author, l.loan_date, l.due_date, DATEDIFF(CURDATE(), l.due_date) AS days_overdue FROM loans l JOIN books b ON l.book_id = b.id JOIN members m ON l.member_id = m.id WHERE l.return_date IS NULL ORDER BY l.due_date; -- Query: Most borrowed books SELECT b.title, b.author, COUNT(l.id) AS borrow_count FROM books b LEFT JOIN loans l ON b.id = l.book_id GROUP BY b.id ORDER BY borrow_count DESC LIMIT 10;