coding
coding
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.
SQL uses various data types to store different kinds of information. Examples include:
Choosing the correct data type ensures efficient storage and performance.
- 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;
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);
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
- 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.
- 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
9. Hands-On Exercises
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).
- Always test queries on a small dataset before running them on production data.
- Avoid using SELECT *; specify the required columns for better performance.