SQL Basics Training Guide
1. Introduction to SQL
SQL (Structured Query Language) is a standard language for interacting with relational databases.
It allows users to create, read, update, and delete (CRUD) data in a database. SQL is essential for
managing data in systems like MySQL, PostgreSQL, SQL Server, and Oracle.
2. SQL Data Types
SQL uses various data types to store different kinds of information. Examples include:
- INT: For whole numbers.
- VARCHAR: For text strings.
- DATE: For storing dates.
Choosing the correct data type ensures efficient storage and performance.
3. Basic SQL Commands
- SELECT: Retrieves data from a table. Example: SELECT * FROM users;
- WHERE: Filters results based on conditions. Example: SELECT * FROM users WHERE age > 30;
- ORDER BY: Sorts query results. Example: SELECT * FROM users ORDER BY name ASC;
- LIMIT: Restricts the number of rows returned. Example: SELECT * FROM users LIMIT 10;
4. Modifying Data
- INSERT: Adds new records. Example: INSERT INTO users (name, age) VALUES ('John', 25);
- UPDATE: Modifies existing records. Example: UPDATE users SET age = 26 WHERE name =
'John';
- DELETE: Removes records. Example: DELETE FROM users WHERE age < 20;
Always back up data before making significant changes.
5. Table Management
- CREATE TABLE: Defines a new table. Example: CREATE TABLE users (id INT, name
VARCHAR(100));
- ALTER TABLE: Modifies a table structure. Example: ALTER TABLE users ADD email
VARCHAR(255);
- DROP TABLE: Deletes tables. Example: DROP TABLE users;
6. Keys and Constraints
- Primary Key: Uniquely identifies a row in a table.
- Foreign Key: Links two tables together.
- Constraints: Enforce rules, such as NOT NULL, UNIQUE, and DEFAULT.
7. Simple Joins
Joins combine rows from two or more tables based on related columns.
- INNER JOIN: Returns rows with matching values. Example: SELECT * FROM orders INNER JOIN
customers ON orders.customer_id = customers.id;
- LEFT JOIN: Includes all rows from the left table and matched rows from the right table.
- RIGHT JOIN: Includes all rows from the right table and matched rows from the left table.
8. Aggregations and Grouping
- Aggregation Functions: COUNT, AVG, SUM, MIN, MAX. Example: SELECT COUNT(*) FROM
users;
- GROUP BY: Groups data by columns. Example: SELECT age, COUNT(*) FROM users GROUP
BY age;
- HAVING: Filters grouped data. Example: SELECT age, COUNT(*) FROM users GROUP BY age
HAVING COUNT(*) > 5;
9. Hands-On Exercises
1. Write a query to select all users older than 30.
2. Create a table for storing product information (id, name, price, stock).
3. Write an INNER JOIN query to combine two tables (e.g., customers and orders).
10. Best Practices
- Write clean, readable SQL with proper indentation.
- Use comments to explain complex queries.
- Always test queries on a small dataset before running them on production data.
- Avoid using SELECT *; specify the required columns for better performance.