SQL_Notes_and_Concepts
SQL_Notes_and_Concepts
A nested query or subquery is a query within another query, enclosed in parentheses. Subqueries
Example:
SELECT Name FROM Students WHERE Marks = (SELECT MAX(Marks) FROM Students);
Example:
SELECT Name FROM Students WHERE Course IN (SELECT Course FROM Courses WHERE
Example:
SELECT Name FROM Students WHERE (Age, Marks) = (SELECT MIN(Age), MAX(Marks) FROM
Students);
4. Correlated Subquery:
Example:
SELECT Name FROM Students S WHERE Marks > (SELECT AVG(Marks) FROM Students
Triggers in SQL
A trigger is a set of instructions that automatically runs when a specific event happens in a table (like
CREATE TRIGGER log_insert AFTER INSERT ON Students FOR EACH ROW BEGIN INSERT
INTO LogTable (Action, Time) VALUES ('New student added', NOW()); END;
CREATE TRIGGER check_balance BEFORE UPDATE ON Accounts FOR EACH ROW BEGIN IF
NEW.Balance < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Balance cannot be
Key Terms:
- Relation: Table
- Tuple: Row
- Attribute: Column
Integrity Constraints:
3. Referential Integrity - Foreign key must match primary key in another table.
Example:
CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(50), Age INT);
GROUP BY in SQL
GROUP BY groups rows with the same values in one or more columns. Often used with aggregate
functions.
Example:
HAVING Clause:
Example:
SELECT Course, COUNT(*) FROM Students GROUP BY Course HAVING COUNT(*) > 5;
2. Entity Integrity:
3. Referential Integrity:
4. Key Integrity:
5. User-Defined Integrity:
BEGIN IF NEW.Balance < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Balance