SQL NOTES FOR INTERVIEW & KNOWLEDGE PURPOSE
1. INTRODUCTION TO SQL
- SQL (Structured Query Language) is used to manage and manipulate relational databases.
- Common SQL databases: MySQL, PostgreSQL, SQLite, Oracle, SQL Server.
2. SQL DATA TYPES
- INT, FLOAT, VARCHAR(n), TEXT, DATE, TIME, BOOLEAN
3. BASIC SQL COMMANDS
- SELECT: Retrieve data from a table.
Example: SELECT * FROM employees;
- INSERT: Add data to a table.
Example: INSERT INTO employees (name, age) VALUES ('John', 30);
- UPDATE: Modify existing data.
Example: UPDATE employees SET age = 31 WHERE name = 'John';
- DELETE: Remove data from a table.
Example: DELETE FROM employees WHERE name = 'John';
4. FILTERING DATA
- WHERE clause
Example: SELECT * FROM employees WHERE age > 25;
- Logical Operators: AND, OR, NOT
- BETWEEN, IN, LIKE, IS NULL
5. SORTING RESULTS
- ORDER BY
Example: SELECT * FROM employees ORDER BY age DESC;
6. AGGREGATE FUNCTIONS
- COUNT(), SUM(), AVG(), MIN(), MAX()
Example: SELECT AVG(age) FROM employees;
7. GROUPING DATA
- GROUP BY
Example: SELECT department, COUNT(*) FROM employees GROUP BY department;
- HAVING (for filtering grouped data)
8. JOINS
- INNER JOIN: Returns matching rows.
- LEFT JOIN: All from left, matched from right.
- RIGHT JOIN: All from right, matched from left.
- FULL OUTER JOIN: All rows from both tables.
Example:
SELECT a.name, b.salary
FROM employees a
INNER JOIN salaries b ON a.id = b.emp_id;
9. SUBQUERIES
- A query within a query.
Example:
SELECT name FROM employees
WHERE department_id = (SELECT id FROM departments WHERE name = 'Sales');
10. SET OPERATIONS
- UNION, UNION ALL, INTERSECT, EXCEPT
11. VIEWS
- Virtual tables
Example: CREATE VIEW sales_view AS SELECT * FROM sales WHERE region = 'East';
12. INDEXES
- Improve query speed
Example: CREATE INDEX idx_name ON employees(name);
13. CONSTRAINTS
- NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT
14. TRANSACTIONS
- BEGIN, COMMIT, ROLLBACK
Ensures ACID properties (Atomicity, Consistency, Isolation, Durability)
15. NORMALIZATION
- Process of organizing data to reduce redundancy.
Normal Forms: 1NF, 2NF, 3NF, BCNF
16. STORED PROCEDURES & FUNCTIONS
- Stored Procedure: A reusable SQL block.
Example:
CREATE PROCEDURE GetAllEmployees AS BEGIN SELECT * FROM employees END;
- Function: Returns a value.
17. TRIGGERS
- SQL code that runs automatically in response to events.
Example:
CREATE TRIGGER trg_after_insert
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO log_table(action) VALUES('Insert on employees');
END;
18. COMMON INTERVIEW QUESTIONS
- Difference between WHERE and HAVING
- Difference between JOIN and UNION
- What is normalization? Explain types
- Explain ACID properties
- Indexing and its advantages
- How to handle NULL values in SQL
Good luck with your interview and learning!