Lesson 1: SQL Basics
1.2 Creating a Database
We use CREATE DATABASE to make a new database.
CREATE DATABASE school;
Explanation:-
Creates a new database named school.1.3 Creating a Table
CREATE TABLE is used to define a table.
CREATE TABLE students (id INT, name VARCHAR(50));
Explanation:-
Creates table students with two columns: id (integer) and name (string).1.4 Inserting Data
INSERT INTO statement adds rows into a table.
INSERT INTO students VALUES (1, "Amit");
Explanation:-
Inserts a new row with id=1 and name="Amit" into students table.1.5 Selecting Data
SELECT retrieves data from tables.
SELECT * FROM students;
Explanation:-
Selects all rows and columns from students table.1.6 WHERE Clause
WHERE filters records based on conditions.
SELECT * FROM students WHERE id=1;
Explanation:-
Selects rows where id=1.1.7 Updating Data
UPDATE modifies existing records.
UPDATE students SET name="Kapil" WHERE id=1;
Explanation:-
Updates name to "Kapil" for the row where id=1.1.8 Deleting Data
DELETE removes records from a table.
DELETE FROM students WHERE id=1;
Explanation:-
Deletes the row with id=1.Lesson 2: Filtering & Querying Data
2.9 Joins
Joins combine rows from multiple tables.
SELECT * FROM students INNER JOIN marks ON students.id=marks.stu_id;
Explanation:-
INNER JOIN returns rows where students.id matches marks.stu_id.2.10 Aggregations
Functions like COUNT, AVG, SUM are used for calculations.
SELECT AVG(marks) FROM marks;
Explanation:-
Calculates average of marks column from marks table.2.11 DISTINCT Keyword
DISTINCT removes duplicate rows in the result.
SELECT DISTINCT name FROM students;
Explanation:-
Returns unique names from students table.2.12 ORDER BY
Sort results in ascending or descending order.
SELECT * FROM students ORDER BY name ASC;
Explanation:-
Orders students by name alphabetically (ASC).2.13 LIMIT Clause
LIMIT restricts the number of rows returned.
SELECT * FROM students LIMIT 5;
Explanation:-
Returns only the first 5 rows.2.14 LIKE Operator
Search for a pattern in a column.
SELECT * FROM students WHERE name LIKE "A%";
Explanation:-
Selects rows where name starts with "A".2.15 IN Operator
Check if value exists in a set.
SELECT * FROM students WHERE id IN (1,2,3);
Explanation:-
Returns rows where id is 1, 2, or 3.2.16 BETWEEN Operator
Select values within a range.
SELECT * FROM students WHERE id BETWEEN 1 AND 5;
Explanation:-
Selects rows where id is between 1 and 5 inclusive.2.17 IS NULL / IS NOT NULL
Check for NULL values in columns.
SELECT * FROM students WHERE name IS NOT NULL;
Explanation:-
Selects rows where name is not NULL.2.18 Aliasing Columns
Rename columns using AS keyword.
SELECT name AS student_name FROM students;
Explanation:-
Renames column name to student_name in the result.2.19 Aliasing Tables
Rename tables in queries.
SELECT s.name FROM students AS s;
Explanation:-
s acts as an alias for students table.Lesson 3: Joins in Depth
3.20 INNER JOIN
Return matching rows from both tables.
SELECT * FROM students s INNER JOIN marks m ON s.id=m.stu_id;
Explanation:-
Returns rows where s.id matches m.stu_id.3.21 LEFT JOIN
Return all rows from left table and matching rows from right.
SELECT * FROM students s LEFT JOIN marks m ON s.id=m.stu_id;
Explanation:-
Includes all students even if no matching marks.3.22 RIGHT JOIN
Return all rows from right table and matching rows from left.
SELECT * FROM students s RIGHT JOIN marks m ON s.id=m.stu_id;
Explanation:-
Includes all marks even if student info missing.3.23 FULL OUTER JOIN
Return all rows when there is a match or not.
SELECT * FROM students s FULL OUTER JOIN marks m ON s.id=m.stu_id;
Explanation:-
Includes all students and marks, matches where possible.3.24 SELF JOIN
Join a table to itself.
SELECT a.name, b.name FROM employees a, employees b WHERE a.manager_id=b.id;
Explanation:-
Used to find relationships within the same table, like manager-subordinate.3.25 CROSS JOIN
Returns Cartesian product of two tables.
SELECT * FROM students CROSS JOIN marks;
Explanation:-
Every row of students combines with every row of marks.Lesson 4: Grouping & Aggregation Functions
4.26 GROUP BY
Group rows based on column values.
SELECT stu_id, COUNT(*) FROM marks GROUP BY stu_id;
Explanation:-
Counts how many marks entries exist per student.4.27 HAVING Clause
Filter groups created by GROUP BY.
SELECT stu_id, AVG(marks) FROM marks GROUP BY stu_id HAVING AVG(marks) > 50;
Explanation:-
Selects students whose average marks are greater than 50.4.28 SUM Function
Calculate total of a numeric column.
SELECT SUM(marks) FROM marks;
Explanation:-
Returns sum of all marks.4.29 COUNT Function
Count number of rows or non-NULL values.
SELECT COUNT(*) FROM students;
Explanation:-
Returns total number of rows in students.4.30 AVG Function
Calculate average value.
SELECT AVG(marks) FROM marks;
Explanation:-
Returns average of marks column.4.31 MIN / MAX Functions
Find smallest or largest value.
SELECT MIN(marks), MAX(marks) FROM marks;
Explanation:-
Returns minimum and maximum marks.Lesson 5: String & Date Functions
5.32 String Functions
Manipulate text data.
SELECT CONCAT(name," Kumar") FROM students;
Explanation:-
Adds " Kumar" to each student name.5.33 SUBSTRING Function
Extract a part of string.
SELECT SUBSTRING(name,1,3) FROM students;
Explanation:-
Returns first 3 characters of name.5.34 TRIM Function
Remove leading and trailing spaces.
SELECT TRIM(" Kapil ");
Explanation:-
Returns "Kapil" without extra spaces.5.35 UPPER / LOWER
Convert text to uppercase or lowercase.
SELECT UPPER(name), LOWER(name) FROM students;
Explanation:-
Converts names to upper and lower case.5.36 REPLACE Function
Replace part of a string.
SELECT REPLACE(name,"Kapil","Amit") FROM students;
Explanation:-
Replaces "Kapil" with "Amit" in names.5.37 Date Functions
Handle date and time.
SELECT NOW(), CURDATE();
Explanation:-
NOW() gives current date and time, CURDATE() gives current date.5.38 DATEDIFF Function
Calculate difference between dates.
SELECT DATEDIFF("2025-10-05","2025-10-01");
Explanation:-
Returns number of days between two dates.5.39 DATE_ADD / DATE_SUB
Add or subtract days to a date.
SELECT DATE_ADD(CURDATE(), INTERVAL 5 DAY);
Explanation:-
Adds 5 days to today's date.5.40 CASE Statement
Conditional logic in queries.
SELECT name, CASE WHEN marks>50 THEN "Pass" ELSE "Fail" END FROM marks;
Explanation:-
Returns "Pass" if marks>50, else "Fail".Lesson 6: Advanced Queries & Subqueries
6.41 UNION
Combine results of two SELECTs.
SELECT name FROM students UNION SELECT name FROM teachers;
Explanation:-
Combines unique names from both tables.6.42 UNION ALL
Combine results including duplicates.
SELECT name FROM students UNION ALL SELECT name FROM teachers;
Explanation:-
Includes all names even if repeated.6.43 EXISTS
Check if subquery returns any rows.
SELECT * FROM students s WHERE EXISTS (SELECT * FROM marks m WHERE m.stu_id=s.id);
Explanation:-
Returns students who have marks entries.6.44 NOT EXISTS
Check if subquery returns no rows.
SELECT * FROM students s WHERE NOT EXISTS (SELECT * FROM marks m WHERE m.stu_id=s.id);
Explanation:-
Returns students with no marks.6.45 IN Subquery
Filter values from subquery.
SELECT * FROM students WHERE id IN (SELECT stu_id FROM marks);
Explanation:-
Selects students who have marks.6.46 NOT IN Subquery
Exclude values from subquery.
SELECT * FROM students WHERE id NOT IN (SELECT stu_id FROM marks);
Explanation:-
Selects students with no marks.6.47 Nested Queries
Subqueries within queries.
SELECT name FROM students WHERE id=(SELECT MAX(stu_id) FROM marks);
Explanation:-
Finds student with highest stu_id in marks.Lesson 7: Keys, Indexes & Constraints
7.48 Indexes
Speed up queries on large tables.
CREATE INDEX idx_name ON students(name);
Explanation:-
Creates index on name column for faster search.7.49 Primary Key
Unique identifier for table rows.
ALTER TABLE students ADD PRIMARY KEY(id);
Explanation:-
id column now uniquely identifies each student.7.50 Foreign Key
Enforce relationship between tables.
ALTER TABLE marks ADD FOREIGN KEY (stu_id) REFERENCES students(id);
Explanation:-
marks.stu_id must match students.id, ensures referential integrity.7.51 AUTO_INCREMENT
Automatically increment numeric column.
CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50));
Explanation:-
id will automatically increase for each new row.7.52 Constraints
Rules applied to columns: NOT NULL, UNIQUE, CHECK, DEFAULT.
CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, age INT CHECK(age>0));
Explanation:-
NOT NULL ensures name is required, CHECK ensures age>0.Lesson 8: Table Management & Alterations
8.53 Views
Virtual tables based on SELECT query.
CREATE VIEW student_marks AS SELECT s.name, m.marks FROM students s JOIN marks m ON s.id=m.stu_id;
Explanation:-
View acts like table but stores query, not data.8.54 Dropping Views
Remove views.
DROP VIEW student_marks;
Explanation:-
Deletes the view.8.55 TRUNCATE TABLE
Delete all data but keep table structure.
TRUNCATE TABLE students;
Explanation:-
Removes all rows from students quickly, id resets if auto_increment.8.56 Dropping Table
Remove table from database.
DROP TABLE students;
Explanation:-
Deletes students table completely.8.57 Renaming Table
Change table name.
ALTER TABLE students RENAME TO student_info;
Explanation:-
Renames students table to student_info.8.58 Renaming Column
Change column name.
ALTER TABLE students RENAME COLUMN name TO student_name;
Explanation:-
Renames column name to student_name.8.59 Adding Column
Add new column to table.
ALTER TABLE students ADD COLUMN age INT;
Explanation:-
Adds age column to students table.8.60 Dropping Column
Remove column from table.
ALTER TABLE students DROP COLUMN age;
Explanation:-
Deletes age column from students table.8.61 Modifying Column
Change datatype or size.
ALTER TABLE students MODIFY COLUMN name VARCHAR(100);
Explanation:-
Changes name column length to 100 characters.Lesson 9: Transactions & Query Optimization
9.62 Transaction Basics
Manage transactions with COMMIT and ROLLBACK.
START TRANSACTION;
UPDATE students SET name="Kapil" WHERE id=1;
ROLLBACK;
Explanation:-
ROLLBACK undoes changes made in transaction.9.63 COMMIT
Permanently save changes in a transaction.
START TRANSACTION;
UPDATE students SET name="Kapil" WHERE id=1;
COMMIT;
Explanation:-
COMMIT saves changes to database.9.64 Savepoints
Partial rollback within transaction.
SAVEPOINT sp1;
UPDATE students SET name="Amit" WHERE id=1;
ROLLBACK TO sp1;
Explanation:-
Rolls back to savepoint sp1 only.9.65 Set Operators
Combine query results: UNION, INTERSECT, MINUS.
Explanation:-
Used to combine or filter results from multiple queries.9.66 EXPLAIN
Check query execution plan.
EXPLAIN SELECT * FROM students;
Explanation:-
Shows how database executes query for optimization.9.67 Aliases for Aggregate Functions
Rename result of aggregation.
SELECT COUNT(*) AS total_students FROM students;
Explanation:-
Returns count of students with alias total_students.9.68 DISTINCT with Aggregates
Count unique values.
SELECT COUNT(DISTINCT name) FROM students;
Explanation:-
Counts unique student names.9.69 Advanced Joins
Use multiple joins in query.
SELECT s.name, m.marks, c.name FROM students s JOIN marks m ON s.id=m.stu_id JOIN courses c ON m.course_id=c.id;
Explanation:-
Combine 3 tables to get student marks and course names.9.70 Subqueries in SELECT
Use subquery to compute values.
SELECT name, (SELECT AVG(marks) FROM marks WHERE stu_id=students.id) AS avg_marks FROM students;
Explanation:-
Shows each student with their average marks.9.71 Correlated Subquery
Subquery depends on outer query.
SELECT name FROM students s WHERE EXISTS (SELECT * FROM marks m WHERE m.stu_id=s.id AND m.marks>50);
Explanation:-
Selects students with marks>50 using correlated subquery.Lesson 10: Advanced SQL Logic & Data Types
10.72 SET Data Manipulation
Use SET to update multiple rows.
UPDATE students SET name="Anonymous" WHERE id>5;
Explanation:-
Changes name to "Anonymous" for all students with id>5.10.73 CASE in UPDATE
Conditional updates.
UPDATE students SET name=CASE WHEN id=1 THEN "Kapil" ELSE "Amit" END;
Explanation:-
Updates name based on id using CASE.10.74 LIMIT with DELETE
Delete limited rows.
DELETE FROM students ORDER BY id DESC LIMIT 1;
Explanation:-
Deletes only last row from table.10.75 LIMIT with UPDATE
Update limited rows.
UPDATE students SET name="Test" ORDER BY id ASC LIMIT 1;
Explanation:-
Updates only first row.10.76 Commenting Queries
Add comments for clarity.
-- This is a comment
SELECT * FROM students;
Explanation:-
Single-line comment.10.77 Multi-line Comments
Use /* */ for multi-line.
/* Comment line 1
Comment line 2 */
SELECT * FROM students;
Explanation:-
Comments span multiple lines.10.78 Temporary Tables
Create tables that exist temporarily.
CREATE TEMPORARY TABLE temp_students (id INT, name VARCHAR(50));
Explanation:-
Table exists only during session.10.79 IFNULL / COALESCE
Handle NULL values.
SELECT IFNULL(name,"No Name") FROM students;
Explanation:-
Replaces NULL with "No Name".10.80 CASE with Aggregates
Conditional aggregation.
SELECT COUNT(CASE WHEN marks>50 THEN 1 END) AS passed_students FROM marks;
Explanation:-
Counts students with marks>50.10.81 Data Types Overview
Understand common SQL data types.
Explanation:-
INT, VARCHAR, DATE, DECIMAL, TEXT, etc.10.82 CHAR vs VARCHAR
Difference between fixed and variable length strings.
Explanation:-
CHAR stores fixed size, VARCHAR variable size.10.83 DECIMAL / NUMERIC
Store precise decimal values.
Explanation:-
DECIMAL(10,2) stores numbers with 2 decimal places.10.84 TEXT / BLOB
Store large text or binary data.
Explanation:-
TEXT for long text, BLOB for binary files.10.85 Constraints Summary
NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.
Explanation:-
Defines rules for data integrity.10.86 Normalization Basics
Organize tables to reduce redundancy.
Explanation:-
Separate related data into different tables.10.87 1NF / 2NF / 3NF
Normal forms explained.
Explanation:-
Rules to ensure no duplicate data and dependencies.10.88 Denormalization
Combine tables for performance.
Explanation:-
May duplicate data to speed up queries.Lesson 11: Stored Procedures, Functions & Triggers
11.89 Stored Procedures
Reusable SQL code blocks.
CREATE PROCEDURE get_students() BEGIN SELECT * FROM students; END;
Explanation:-
Defines procedure to get all students.11.90 Calling Stored Procedure
Execute procedure.
CALL get_students();
Explanation:-
Runs stored procedure get_students.11.91 Stored Functions
Return value from SQL function.
CREATE FUNCTION total_marks(stu INT) RETURNS INT BEGIN DECLARE t INT; SELECT SUM(marks) INTO t FROM marks WHERE stu_id=stu; RETURN t; END;
Explanation:-
Function calculates total marks for a student.11.92 Triggers
Execute actions on table events.
CREATE TRIGGER before_insert_student BEFORE INSERT ON students FOR EACH ROW SET NEW.name=UPPER(NEW.name);
Explanation:-
Automatically converts inserted student names to uppercase.11.93 Transactions with Savepoints
Partial rollbacks within transaction.
START TRANSACTION; SAVEPOINT sp1; UPDATE students SET name="A"; ROLLBACK TO sp1;
Explanation:-
Rollback only to savepoint sp1.11.94 Views with Joins
Combine multiple tables in view.
CREATE VIEW student_info AS SELECT s.name, m.marks FROM students s JOIN marks m ON s.id=m.stu_id;
Explanation:-
View shows student names with marks.Lesson 12: Database Administration & Maintenance
12.95 Privileges / GRANT
Grant permissions to users.
GRANT SELECT, INSERT ON school.* TO "user"@"localhost";
Explanation:-
Gives user SELECT and INSERT privileges on school database.12.96 REVOKE
Remove privileges.
REVOKE INSERT ON school.* FROM "user"@"localhost";
Explanation:-
Removes INSERT privilege from user.12.97 Backup / Restore
Use mysqldump for backup.
-- Backup
mysqldump -u root -p school > school.sql
-- Restore
mysql -u root -p school < school.sql
Explanation:-
Export and import database data.12.98 Import CSV
Load CSV data into table.
LOAD DATA INFILE "students.csv" INTO TABLE students FIELDS TERMINATED BY "," LINES TERMINATED BY "\n";
Explanation:-
Imports CSV file into students table.12.99 Export CSV
Save table data to CSV.
SELECT * FROM students INTO OUTFILE "students.csv" FIELDS TERMINATED BY "," LINES TERMINATED BY "\n";
Explanation:-
Exports table data into CSV file.12.100 Next Steps
After mastering basics, learn advanced SQL, procedures, triggers, and database design.
Comments (1)
Login to comment
support: hi