Structured Notes on SQL
1. Introduction to SQL
- SQL (Structured Query Language) is used to communicate with relational databases.
- It is used for creating, modifying, managing, and querying data in RDBMS (e.g., MySQL, Oracle,
PostgreSQL, SQL Server).
2. Types of SQL Commands
- DDL (Data Definition Language): CREATE, ALTER, DROP, TRUNCATE
- DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
- DCL (Data Control Language): GRANT, REVOKE
- TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
3. Important SQL Commands
- CREATE TABLE table_name (column datatype constraints);
- ALTER TABLE table_name ADD column datatype;
- DROP TABLE table_name;
- TRUNCATE TABLE table_name;
- INSERT INTO table_name (col1, col2) VALUES (val1, val2);
- SELECT col1, col2 FROM table_name WHERE condition;
- UPDATE table_name SET col1 = val1 WHERE condition;
- DELETE FROM table_name WHERE condition;
4. SQL Clauses
- WHERE, GROUP BY, HAVING, ORDER BY, LIMIT
5. SQL Constraints
- NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT
6. Joins in SQL
- INNER JOIN: matching rows in both tables
- LEFT JOIN: all rows from left + matching rows from right
- RIGHT JOIN: all rows from right + matching rows from left
- FULL JOIN: rows with a match in one of the tables
7. Aggregate Functions
- COUNT(), SUM(), AVG(), MAX(), MIN()
8. Subqueries
- Nested queries within another query
Example: SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM
employees);
9. Views
- Virtual table based on result of a query
CREATE VIEW view_name AS SELECT col1, col2 FROM table_name WHERE condition;
10. Indexes
- Improves data retrieval speed
CREATE INDEX index_name ON table_name(column_name);
11. Transactions
- ACID Properties: Atomicity, Consistency, Isolation, Durability
12. Normalization
- 1NF: Atomic values
- 2NF: No partial dependency
- 3NF: No transitive dependency
- BCNF: Every determinant is a candidate key
13. SQL Injection (Security)
- Occurs when untrusted data is passed into SQL statements.
- Prevention: Use prepared statements or parameterized queries.