1.
Basic SQL Queries
sql
CopyEdit
-- Retrieve all records from the "students" table
SELECT * FROM students;
-- Insert a new record into the "students" table
INSERT INTO students (student_id, name, age, department)
VALUES (101, 'Azzam', 22, 'Computer Science');
-- Update the age of a student
UPDATE students
SET age = 23
WHERE student_id = 101;
-- Delete a student record
DELETE FROM students
WHERE student_id = 101;
2. Using Joins
sql
CopyEdit
-- Retrieve student names and their department names using INNER JOIN
SELECT students.name, departments.department_name
FROM students
INNER JOIN departments
ON students.department_id = departments.department_id;
-- Retrieve all students, including those without a department (LEFT JOIN)
SELECT students.name, departments.department_name
FROM students
LEFT JOIN departments
ON students.department_id = departments.department_id;
3. Grouping and Aggregates
sql
CopyEdit
-- Count the total number of students in each department
SELECT department_id, COUNT(*) AS student_count
FROM students
GROUP BY department_id;
-- Find the average age of students in each department
SELECT department_id, AVG(age) AS average_age
FROM students
GROUP BY department_id;
4. Subqueries
sql
CopyEdit
-- Retrieve the names of students who belong to the department with ID 2
SELECT name
FROM students
WHERE department_id = (
SELECT department_id
FROM departments
WHERE department_name = 'Computer Science'
);
-- Retrieve students whose age is above the average age
SELECT name, age
FROM students
WHERE age > (
SELECT AVG(age) FROM students
);
5. Views
sql
CopyEdit
-- Create a view for active students
CREATE VIEW active_students AS
SELECT name, age, department_id
FROM students
WHERE status = 'Active';
-- Query the view
SELECT * FROM active_students;
6. Transactions
sql
CopyEdit
-- Begin a transaction
START TRANSACTION;
-- Insert a new student
INSERT INTO students (student_id, name, age, department)
VALUES (102, 'John Doe', 21, 'Mathematics');
-- Rollback the transaction if something goes wrong
ROLLBACK;
-- Commit the transaction to save changes
COMMIT;
7. Triggers
sql
CopyEdit
-- Create a trigger to automatically log deletions in the "students" table
CREATE TRIGGER log_student_deletion
AFTER DELETE ON students
FOR EACH ROW
INSERT INTO deletion_log (student_id, deleted_at)
VALUES (OLD.student_id, NOW());
8. Indexing
sql
CopyEdit
-- Create an index on the "name" column for faster search
CREATE INDEX idx_student_name ON students (name);
-- Drop the index
DROP INDEX idx_student_name ON students;