SQL Cheat Sheet for Beginners
1. Basic SQL Commands
-- Select all records
SELECT * FROM table_name;
-- Select specific columns
SELECT column1, column2 FROM table_name;
-- Filtering records
SELECT * FROM table_name WHERE condition;
-- Sorting results
SELECT * FROM table_name ORDER BY column_name ASC|DESC;
-- Limiting results
SELECT * FROM table_name LIMIT 10;
2. Filtering with WHERE
-- Operators: =, <>, >, <, >=, <=
SELECT * FROM employees WHERE age > 30;
-- BETWEEN, IN, LIKE
SELECT * FROM products WHERE price BETWEEN 10 AND 50;
SELECT * FROM users WHERE country IN ('USA', 'UK');
SELECT * FROM books WHERE title LIKE 'Python%';
3. Joins
-- INNER JOIN
SELECT * FROM orders
INNER JOIN customers ON orders.customer_id = customers.id;
-- LEFT JOIN
SELECT * FROM employees
LEFT JOIN departments ON employees.dept_id = departments.id;
-- RIGHT JOIN
SELECT * FROM students
RIGHT JOIN courses ON students.course_id = courses.id;
4. Grouping and Aggregation
-- Aggregate functions: COUNT(), SUM(), AVG(), MAX(), MIN()
SELECT department, COUNT(*) FROM employees
GROUP BY department;
-- HAVING clause
SELECT department, AVG(salary) FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
5. Table Operations
-- Creating a table
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
-- Inserting data
INSERT INTO users (id, name, email)
VALUES (1, 'Alice', 'alice@example.com');
-- Updating data
UPDATE users SET name = 'Bob' WHERE id = 1;
-- Deleting data
DELETE FROM users WHERE id = 1;
6. Other Useful Clauses
-- DISTINCT
SELECT DISTINCT country FROM customers;
-- ALIAS
SELECT name AS employee_name FROM employees;
-- IS NULL / IS NOT NULL
SELECT * FROM orders WHERE shipped_date IS NULL;