SQL Basics in 2 Pages
1. Introduction to SQL
- SQL (Structured Query Language) is used to manage and query relational databases.
2. Basic Commands
- SELECT: Retrieve data from a table.
Example: SELECT name, age FROM students;
- WHERE: Filter records.
Example: SELECT * FROM students WHERE age > 18;
- ORDER BY: Sort results.
Example: SELECT * FROM students ORDER BY age DESC;
3. Aggregation
- COUNT(), SUM(), AVG(), MAX(), MIN()
Example: SELECT COUNT(*) FROM orders;
4. GROUP BY and HAVING
- GROUP BY: Summarize data.
Example: SELECT dept, AVG(salary) FROM employees GROUP BY dept;
- HAVING: Filter aggregated results.
Example: SELECT dept, COUNT(*) FROM employees GROUP BY dept HAVING COUNT(*) > 5;
5. Joins
- INNER JOIN: Matches records in both tables.
- LEFT JOIN: All records from left table + matched from right.
- RIGHT JOIN: All records from right + matched from left.
Example:
SELECT students.name, courses.title
FROM students
INNER JOIN courses ON students.course_id = courses.id;
6. Keys
- Primary Key: Unique identifier of a record.
- Foreign Key: Links two tables together.
Quick Tip: Always test queries with LIMIT before running on big data.