SQL Course
SQL Course
Shopping List
Keeps track of Consumer Products that need to be purchased.
10-20 pieces of Information need to be stored and readily available.
Information is for Convenience sake only and not necessary for shopping.
Security in not important.
Information is stored on a Pieces of paper, or even just in Someone’s memory.
Amazon.com Will interact with the DBMS in order to create, read,Update and delete information
CRUD – is Stands for the Create , read , Update and the delete information OR the data.
Non-relational (No-SQL):-
Organize data is anything but a traditional tables.
Key-values Stores.
Documents(JSON,XML,etc)
Graphs
Flexible Tables.
No-relational database Contain anything that does not have the relation . it Contain the
JSON Code and Also it contain the graphs And also in the form of key values pairs ,..
Non-relational database Management Systems (NRDBMS).
Helps users to Create and maintain a non-relational Databases.
MongoDB, DynamoDB ,Apache Cassandra , Firebase etc.
Implementation Specific.
o Any non-relational database falls under this category, so there’s not set
language standard.
o Most NRDBMS will implements their own languages for Performing CRUD and
administrative Operations on the databases.
Analogy
Quick Example
Database Queries:
Queries are requests made to the database management system for Specific
information.
As the Database’s Structure become more and more Complex, It become more
difficult to get the specific Pieces of information we want.
A google Search is a Query.
Wrap Up
Database is Any collection of related information.
Computer are great for Storing Databases.
Database management Systems(DBMS) make it easy to Create, Maintain and Secure a
database.
DBMS allow you to perform the CURD Operations and other Administrative tasks.
Two types of Database, relational & non-Relational .
Relational Databases use SQL and Store data in tables with rows And Columns.
Non-Relational data store Data using Other Data Structures.
Whenever we are going to Create out the tables inside the relational
databases we always have one Column that is said to be the
Primary Key
A Primary key is basically an Attribute which uniquely Defines the Rows in the
databases.
So, It is an Attribute about a Specific entry Which Will uniquely define it.
With The help Of the Primary key We can use This attribute to uniquely identify a Specific
row .
As the Primary Key is always going to be unique For Each row in the Table.
Even If All Of The Attributes of the Row are Same the Primary key wont be same.
With the Help of the Primary key we can Differentiate any Row inside the table With
Another row Inside the table.
A Primary key cannot Always be a Number it can be Anything but the major thing about
the Primary key is that it should be the unique.
Secondary Key :-
Other than the primary key that are exist inside the table are meant to Be the Primary
keys While it Should be the Foreign keys, it should be the Natural keys and it should be Alternate
keys ,..
Surrogate Key :
🔑 What is a Surrogate Key in SQL Databases? (Simple & Easy Explanation)
✅ Simple Definition:
A Surrogate Key is an artificial or system-generated key (usually a number like ID) used to
uniquely identify each row in a table.
It has no real-world meaning. It’s just there to act as a unique ID for each record.
Here, email is used as the primary key — but emails can change!
With Surrogate Key (Recommended):
Now you can safely change an email later without affecting relationships.
✅ Example of Data:
Let’s create a new Courses table and a relationship with a Enrollments table.
Advantage Description
✅ Simpler joins Small numeric keys are fast and efficient
✅ Flexibility You can change real data without breaking links
✅ Consistency Uniform IDs across all tables
✅ Easy to maintain Avoid issues with natural key changes
🧠 Remember:
Would you like a hands-on SQL demo file or example in a specific database (MySQL,
PostgreSQL, etc.)?
In This Table the Employee Id is also a Primary key and What Else
we Called the Employee Id Is to be the Surrogate Key.
A Surrogate key is basically has no mapping to Anything in the
real world
A Random Number that Assign to an employee. Like 100 is Assign to JAN ,.
And the 100 is Just a value to we are using to represent JAN inside Of the
database.
We Would prefer that Surrogate key Which is type of Primary key.
Surrogate key is a key that has no mapping to anything in the real World .
Natural Key:-
🔑 What is a Natural Key in SQL Databases?
✅ **Simple Definition:
A Natural Key is a key (column or group of columns) from the actual data that is used to
uniquely identify each record in a table.*
In short:
A Natural Key is real-world data that is already unique, so we can use it as a Primary Key.
A person's Email
A student's Roll Number
A car’s Registration Number
A product's Serial Number
These values already exist and are naturally unique, so they can be used to identify records.
📋 Sample Data:
⚠️Potential Problems:
💡 Best Practice:
A Natural Key is real-world data that is already unique and can be used as a Primary Key in a
table.
Would you like a downloadable SQL file with both surrogate and natural key examples for
practice?
Here in that table instead Of using the employee ID here we are using the
employee SSN Which Stands for the Social Security Number. Is a Number that
are used in the united State in Order to uniquely identified each Citizen.
The key Which is the opposite of the Surrogate key ,..
Natural key are the key that has mapping Or has Purpose in the
real world, Not Just in the database
Here employee SSN have the Purpose Of mapping it With the Table And Also
the Employee_SSN are the Primary key.
Foreign_key:-
🔗 What is a Foreign Key in SQL Databases?
✅ Simple Definition:
A Foreign Key is a column in one table that links to the Primary Key in another table.
It creates a relationship between two tables — like connecting data from different places.
📘 Real-Life Example:
✅ In this case:
📋 Sample Data:
🎓 Students Table
course_id course_name
1 SQL Basics
2 Web Development
📝 Enrollments Table
1 1 1
2 2 2
✅ This shows:
A Foreign Key links one table to another by referencing the Primary Key — it connects data
and keeps it valid.
Would you like me to generate a downloadable .sql file so you can try this example on your
computer?
A Foreign key is basically an attribute that we can store in a Database table. That will Link
us to another database table.
A Foreign Key Stores the primary key of a row in another database table.
A Foreign is Essentially just a way that we can define relationships between the two
tables.
A Foreign key is able to help us to define Relationships between the tables,
A Foreign key is able to help us to define Relationships between the tables.
It is Also important to know that a particular table have more than one
foreign keys on it.
Composite key :-
Sure! Let's break it down in the simplest and easiest way.
A Composite Key is a combination of two or more columns in a table that together uniquely
identify a row.
A single column is not enough to uniquely identify rows — but together, two or more columns
can do it.
1 101
2 101
1 102
✅ In MySQL / PostgreSQL
CREATE TABLE StudentCourses (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
✅ Explanation:
✨ Inserting Data
INSERT INTO StudentCourses (student_id, course_id) VALUES (1, 101);
INSERT INTO StudentCourses (student_id, course_id) VALUES (2, 101);
INSERT INTO StudentCourses (student_id, course_id) VALUES (1, 102);
-- This will work fine
🧠 Tips
SQL basics:-
SQL is a language used for Interacting with relational database
management Systems (RDBMS).
You can use SQL to get the RDBMS to do things for you
o Create, retrieve, Update & Delete Data.
o Create & manage Databases.
o Design & Create Databases tables.
o Perform Administration Tasks (security, User management,
import/Export, etc)
SQL implementations Vary between Systems.
Not all RDBMS Follow the SQL Standard to a ‘T’
The Concepts are the Same but the implementation may Vary.
SQL is actually a hybrid language, it’s basically 4 type of languages.
o Data Query language(DQL)
Used to Query the Database for information.
What piece OF information you want to get from the
database.
Get Information that is already Stored there.
o Data Definition language(DDL)
Used for defining the database Schema.
Schema is basically the overall layout of the database.
What tables are Going to be in a database And what columns
those tables Are going to have.
o Data Control Language(DCL)
Used for Controlling access to the Data in the Database.
User & Permission Management.
It is also used for controlling access of the data inside the
database.
It basically Decide out that Which user can access Which bunch
of data.
o Data manipulation (DML)
Used for Inserting, updating and deleting Data From the databases.
It is Also a data manipulation language . means Apply out the
manipulation OR the Different operations on the data.
Queries:-
A Query is a set of instructions given to the RDBMS( Written is SQL) that tell the RDBMS
what information you want it to retrieve For you.
o TONS of data in a DB.
o Often Hidden in a Complex Schema.
o Goal is to only get the Data you need.
Decimal(M, N):- That Data Type is used for the decimal numbers And for the Exact Values.
Decimal(3, 2); it Contain Three total Digits and two Of the Digits After the Decimal Points.
BLOB:- These data type are used for the binary large objects, Stores large Data.
There are two Ways to define a primary key inside the Queries .
🔹 Syntax:
DESCRIBE table_name;
🔹 Example:
DESCRIBE students;
🔹 Simple Meaning:
Like that how I can Skip a particular column when I tried to insert out their values.
Primary Key(visitors_id)
);
Primary Key(visitors_id)
);
UPDATE student
The SET command is used to assign a value to a column in a table. It is usually used with the
UPDATE statement.
✅ Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
📙 Explanation:
📊 Example:
id name marks
1 Ali 75
2 Sana 85
3 Ahmed 65
🎯 Goal:
✅ SQL Command:
UPDATE students
SET marks = 90
WHERE name = 'Ahmed';
🧾 Result:
id name marks
1 Ali 75
2 Sana 85
3 Ahmed 90
🔎 SET changed the marks column where the name was "Ahmed".
🔹 WHERE in SQL
📌 What is WHERE?
The WHERE clause is used to filter records. It tells SQL to only affect or select rows that meet a
specific condition.
📊 Example:
id name marks
1 Ali 75
2 Sana 85
3 Ahmed 90
🎯 Goal:
✅ SQL Command:
SELECT * FROM students
WHERE marks > 80;
🧾 Result:
id name marks
2 Sana 85
3 Ahmed 90
🔎 WHERE filtered the records and only returned rows with marks > 80.
🎓 Summary
Command Purpose Example
SET Changes data in a column SET marks = 90
WHERE Filters rows based on condition WHERE name = 'Ahmed'
🧪 Combined Example
🎯 Update Sana’s marks to 95:
UPDATE students
SET marks = 95
WHERE name = 'Sana';
Comparison Operations
= Symbol is used For the Equal to
Purpose Deletes data/rows from a table Deletes the entire table (structure + data)
Table remains? ✅ Yes, table stays after delete ❌ No, table is removed completely
🔹 DELETE Command
📌 Purpose:
✅ Syntax:
DELETE FROM table_name
WHERE condition;
🧪 Example:
id name position
1 Ali Manager
2 Sana Developer
3 Ahmed Developer
id name position
1 Ali Manager
2 Sana Developer
✅ Table still exists, but Ahmed's row is gone.
🔸 DROP Command
📌 Purpose:
Used to remove the entire table, including all its rows and structure.
✅ Syntax:
DROP TABLE table_name;
🧪 Example:
📦 Result:
🧠 In Simple Words
Command Think Like
🎓 Summary
Use DELETE when you want to remove some data but keep the table.
Use DROP when you want to remove the table itself from the database.
Deleting Commands:-
DELETE student
DELETE student;
Basic Queries
1. SELECT name * FROM Student;
2. SELECT name FROM Student;
3. SELECT name, major FROM Student;
4. SELECT student.name, student.major FROM student;
5. SELECT student.name, student.major FROM student ORDER BY name;
Sure! Here's a simple and easy explanation of the SQL command ORDER BY with examples and
demos so that even a beginner can understand it clearly.
The ORDER BY command is used to sort the result of a SQL query in ascending or descending
order based on one or more columns.
✅ Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
🧾 Output:
id name marks
3 Ahmed 65
1 Ali 75
2 Sana 85
4 Zara 95
🧾 Output:
id name marks
4 Zara 95
2 Sana 85
1 Ali 75
3 Ahmed 65
🧾 Output:
id name marks
1 Ali 75
3 Ahmed 65
2 Sana 85
4 Zara 95
🧾 Output:
id name marks
4 Zara 95
2 Sana 85
1 Ali 75
3 Ahmed 65
👥 If two students had the same marks, this would sort them by name next.
🧠 In Simple Words:
SQL Command What It Does
ORDER BY column ASC Sort from smallest to biggest (or A to Z)
ORDER BY column DESC Sort from biggest to smallest (or Z to A)
✅ Summary:
ORDER BY is used to sort results.
Default sort is ASC (ascending).
You can sort by numbers or text.
You can sort by multiple columns.
"REFERENCES"
🔹 What is REFERENCES in SQL?
The REFERENCES keyword is used to create a relationship between two tables in a database.
It is mainly used to define a foreign key, which links one table to another.
🔹 Example (Simple)
Step 1: Create the Classes table
CREATE TABLE Classes (
class_id INT PRIMARY KEY,
class_name VARCHAR(100)
);
🔹 Insert Example
-- Insert into Classes
INSERT INTO Classes (class_id, class_name)
VALUES (1, 'Computer Science');
🔹 Summary
Concept Meaning
REFERENCES Used to create a link (foreign key) between two tables
Purpose Keep data correct and avoid invalid relationships
Real-life use Connecting students to classes, orders to customers, etc.
Let me know if you want a practice quiz, real-world example, or a diagram to visualize it!
-- CLIENT
INSERT INTO client VALUES(400, 'Dunmore
Highschool', 2);
INSERT INTO client VALUES(401, 'Lackawana
Country', 2);
INSERT INTO client VALUES(402, 'FedEx', 3);
INSERT INTO client VALUES(403, 'John Daly Law,
LLC', 3);
INSERT INTO client VALUES(404, 'Scranton
Whitepages', 2);
INSERT INTO client VALUES(405, 'Times
Newspaper', 3);
INSERT INTO client VALUES(406, 'FedEx', 2);
-- WORKS_WITH
INSERT INTO works_with VALUES(105, 400, 55000);
INSERT INTO works_with VALUES(102, 401, 267000);
INSERT INTO works_with VALUES(108, 402, 22500);
INSERT INTO works_with VALUES(107, 403, 5000);
INSERT INTO works_with VALUES(108, 403, 12000);
INSERT INTO works_with VALUES(105, 404, 33000);
INSERT INTO works_with VALUES(107, 405, 26000);
INSERT INTO works_with VALUES(102, 406, 15000);
INSERT INTO works_with VALUES(105, 406, 130000);
Employees
Branches (offices)
Clients (customers)
Sales (who sold what to whom)
Suppliers (who gives you goods)
🧱 1. CREATING TABLES
🔹 employee Table
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
first_name VARCHAR(40),
last_name VARCHAR(40),
birth_day DATE,
sex VARCHAR(1),
salary INT,
super_id INT,
branch_id INT
);
🔹 branch Table
CREATE TABLE branch (
branch_id INT PRIMARY KEY,
branch_name VARCHAR(40),
mgr_id INT,
mgr_start_date DATE,
FOREIGN KEY(mgr_id) REFERENCES employee(emp_id) ON DELETE SET NULL
);
🧠 ON DELETE SET NULL means: if the manager is deleted, set mgr_id to NULL.
🔹 Self-reference: super_id
ALTER TABLE employee
ADD FOREIGN KEY(super_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL;
🔹 client Table
CREATE TABLE client (
client_id INT PRIMARY KEY,
client_name VARCHAR(40),
branch_id INT,
FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE SET NULL
);
🔹 works_with Table
CREATE TABLE works_with (
emp_id INT,
client_id INT,
total_sales INT,
PRIMARY KEY(emp_id, client_id),
FOREIGN KEY(emp_id) REFERENCES employee(emp_id) ON DELETE CASCADE,
FOREIGN KEY(client_id) REFERENCES client(client_id) ON DELETE CASCADE
);
🔹 branch_supplier Table
CREATE TABLE branch_supplier (
branch_id INT,
supplier_name VARCHAR(40),
supply_type VARCHAR(40),
PRIMARY KEY(branch_id, supplier_name),
FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE CASCADE
);
✅ 2. INSERTING DATA
Now, you add data (records) to those tables.
🏢 Scranton Branch
Then Angela, Kelly, and Stanley are added as employees under Michael.
🏢 Stamford Branch
This means:
👥 Clients
Clients are linked to branches:
📊 Visual Overview
Think of this like connected sheets:
This is used to keep data clean and avoid errors, depending on how you want your
database to behave when something gets deleted.
9. Here we are Going to insert out the remaining Data Of the Database
Tables.
-- Stamford
INSERT INTO employee VALUES(106, 'Josh',
'Porter', '1969-09-05', 'M', 78000, 100, NULL);
INSERT INTO branch VALUES(3, 'Stamford', 106,
'1998-02-13');
UPDATE employee
SET branch_id = 3
WHERE emp_id = 106;
INSERT INTO employee VALUES(107, 'Andy',
'Bernard', '1973-07-22', 'M', 65000, 106, 3);
INSERT INTO employee VALUES(108, 'Jim',
'Halpert', '1978-10-01', 'M', 71000, 106, 3);
-- BRANCH SUPPLIER
INSERT INTO branch_supplier VALUES(2, 'Hammer
Mill', 'Paper');
INSERT INTO branch_supplier VALUES(2, 'Uni-
ball', 'Writing Utensils');
INSERT INTO branch_supplier VALUES(3, 'Patriot
Paper', 'Paper');
INSERT INTO branch_supplier VALUES(2, 'J.T.
Forms & Labels', 'Custom Forms');
INSERT INTO branch_supplier VALUES(3, 'Uni-
ball', 'Writing Utensils');
INSERT INTO branch_supplier VALUES(3, 'Hammer
Mill', 'Paper');
INSERT INTO branch_supplier VALUES(3, 'Stamford
Lables', 'Custom Forms');
-- CLIENT
INSERT INTO client VALUES(400, 'Dunmore
Highschool', 2);
INSERT INTO client VALUES(401, 'Lackawana
Country', 2);
INSERT INTO client VALUES(402, 'FedEx', 3);
INSERT INTO client VALUES(403, 'John Daly Law,
LLC', 3);
INSERT INTO client VALUES(404, 'Scranton
Whitepages', 2);
INSERT INTO client VALUES(405, 'Times
Newspaper', 3);
INSERT INTO client VALUES(406, 'FedEx', 2);
-- WORKS_WITH
INSERT INTO works_with VALUES(105, 400, 55000);
INSERT INTO works_with VALUES(102, 401, 267000);
INSERT INTO works_with VALUES(108, 402, 22500);
INSERT INTO works_with VALUES(107, 403, 5000);
INSERT INTO works_with VALUES(108, 403, 12000);
INSERT INTO works_with VALUES(105, 404, 33000);
INSERT INTO works_with VALUES(107, 405, 26000);
INSERT INTO works_with VALUES(102, 406, 15000);
INSERT INTO works_with VALUES(105, 406, 130000);
SQL Functions
SQL Function is Special block of Code that we can call Which will do Something For us,.. Like Count things , Averages
Getting information from the tables.
6. Finding Out how many males and Females are There in Company.
7. Finding out how many males and the females Also group by their Gender
9. Finding out the Total amount how much each Client Spent with the branch.
Wildcards
A wildcard is a special symbol used in SQL to search for data when you don’t know
the exact value.
You mainly use wildcards with the LIKE operator in the WHERE clause.
✅ Basic Syntax
sql
CopyEdit
SELECT column_name
FROM table_name
WHERE column_name LIKE 'pattern';
🔑 Common Wildcards
Wildcard Meaning
_ A single character
1 John
2 Johnny
3 Jonathan
4 Joanne
5 Jack
6 Jill
7 Bob
nginx
CopyEdit
John
Johnny
Jonathan
Joanne
🟨 Output:
nginx
CopyEdit
John
Jonathan
🟨 Output:
nginx
CopyEdit
John
Johnny
🟨 Output:
nginx
CopyEdit
John
Jack
Jill
Find names starting with J and second letter is either "o" or "a"
sql
CopyEdit
SELECT name FROM Students
WHERE name LIKE 'J[o,a]%';
🟨 Output:
nginx
CopyEdit
John
Joanne
Jack
nginx
CopyEdit
Jack
Jill
📝 Notes:
Wildcards work only with the LIKE operator, not with = (equal).
Wildcards are case-insensitive in some databases (like MySQL), but case-sensitive in
others (like PostgreSQL).
🧠 Summary
Wildcard Use for Example
WildCard
WildCard is basically Defining different Patterns that we want to match Specific pieces of data to. This
would be a way to kind Of like grab data That matches a Specific pattern.
2. Write Out the Query To Find Any Branch Supplier who are in the label Bussiness.
4. Finding Any Clients Who are schools ,.. Meaning finding The name Of the client who are School.
UNION
Union is basically a Special SQL operator Which can be used to combine the Multiple Select
Statements into One. Which we can use to Combine the results of multiple Select statements
into one. So if you have two or three Select statement you are using. If I wanted them I can
combine all of them into the same result.
Sure! Let’s understand UNION in SQL in the simplest and easiest way, with clear examples
and demos.
🧠 Basic Rules
1. Each SELECT must have the same number of columns.
2. Columns must be in the same order and data type.
3. UNION removes duplicates.
4. Use UNION ALL to keep all rows including duplicates.
✅ Basic Syntax
SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2;
🟢 Example Scenario
Table 1: Students_A
id Name
1 Alice
2 Bob
3 Carol
Table 2: Students_B
id name
1 David
2 Carol
3 Emma
🎯 1. Using UNION
SELECT name FROM Students_A
UNION
SELECT name FROM Students_B;
🟨 Output:
Alice
Bob
Carol
David
Emma
🟨 Output:
Alice
Bob
Carol
David
Carol
Emma
✔️Carol appears twice because UNION ALL keeps duplicates.
🟨 Output:
1 | Alice
2 | Bob
3 | Carol
1 | David
3 | Emma
📝 Notes:
You can add ORDER BY at the end to sort the final result:
Use UNION ALL when performance is important and you don’t care about duplicates.
🧠 Summary
Keyword Removes Duplicates? Use When
UNION ✅ Yes You want only unique results
UNION ALL ❌ No You want to keep all rows (faster too)
1. Finding out the lists Of employees and the branch names. This is Interesting We actually
use The union Operator that Will join The both Employees and the branches together.
SELECT first_name FROM employee UNION SELECT branch_name FROM branch UNION
SELECT client_name FROM client;
3. If you Want to Change the name Of OUTPUT columns OR the Resulted column then you can use it
like That.
4. Finding out the list of Clients and the branch suppliers names.
SELECT clients_name FROM client UNION SELECT supplier_name FROM branch_supplier;
5. Client Ta6. ble and the branch_supplier table Both have the Common Column which is “branch_id”
and if we also need that Column For that We will Select like that.
OR
If we want to Differntiate the names of the Common Columns We Can Do it like that
6. Write a Query to Find out the List of all money spent or Earned by the Company.
Union can be very useful For sort of combining all this data in Single place.
Joins
Sure! Let's break down SQL JOINS in the simplest and easiest way, step by step, with clear
explanations and examples.
Think of it like connecting two puzzle pieces that fit together using a common column (like an
ID).
📊 Example Tables
Let’s use two simple tables:
🧒 students Table
student_id name
1 Alice
2 Bob
3 Charlie
📚 courses Table
🔍 Example:
SELECT students.name, courses.course_name
FROM students
INNER JOIN courses
ON students.student_id = courses.student_id;
📋 Output:
name course_name
Alice Math
Alice Science
Bob History
👉 Note: Charlie is not shown because he has no course. Course ID 104 is not shown because
student 4 doesn't exist in students.
🔍 Example:
SELECT students.name, courses.course_name
FROM students
LEFT JOIN courses
ON students.student_id = courses.student_id;
📋 Output:
name course_name
Alice Math
Alice Science
Bob History
Charlie NULL
🔍 Example:
SELECT students.name, courses.course_name
FROM students
RIGHT JOIN courses
ON students.student_id = courses.student_id;
📋 Output:
name course_name
Alice Math
Alice Science
Bob History
NULL English
💡 Not supported in all databases (e.g., MySQL needs a workaround using UNION).
🔍 Example:
SELECT students.name, courses.course_name
FROM students
FULL OUTER JOIN courses
ON students.student_id = courses.student_id;
📋 Output:
name course_name
Alice Math
Alice Science
Bob History
Charlie NULL
NULL English
5. ❌ CROSS JOIN
Returns all possible combinations of rows (cartesian product). Be careful—it can return a lot of
rows!
🔍 Example:
SELECT students.name, courses.course_name
FROM students
CROSS JOIN courses;
📋 Output:
name course_name
Alice Math
Alice Science
Alice History
Alice English
Bob Math
... ...
🎯 Summary Table
Type of JOIN Shows...
INNER JOIN Only matching records
LEFT JOIN All from left table + matching from right
RIGHT JOIN All from right table + matching from left
FULL OUTER JOIN All records from both tables
CROSS JOIN All possible combinations
🛠 Real-Life Analogy
Imagine:
(Both of the table have the same Column which “emp_id” and the “mgr_id”. And
Anytime you have the Situation like that , you can use Something Called “JOIN”. Join is
used to Combine Two or More tables based on The related Column. In that the related
Column is the IDs of Employees.)
Inner Join:
Inner join is going to combine row From the employees table and the branch table
whenever they have the Shared column in Common. Are also meant to be the normal Join.
LEFT Join:-
SELECT employee.emp_id,employee.first_name, branch.branch_name
FROM employee
LEFT JOIN branch
ON employee.emp_id = branch.mgr_id;
It will Show All of the data From the left table(employee) and only the Common Data From the right table. It
show all of the records of the employee but common records of branch table.
OUTPUT
RIGHT JOIN:-
The Right Join is same like the LEFT Join but inside the RIGHT join We will take all of the rows
From the right table(branches) instead of the left table. It will include All of the branches Data But
only the Common employee Data.
OUTPUT
FULL OUTER JOIN :-
FULL JOIN basically the combination of the LEFT and the RIGHT JOIN which will
basically Show all of the Data from the Both tables. It Will show out All of the data From
the Both tables.
The error is happening because MySQL (and MariaDB) does not support FULL OUTER
JOINdirectly.
🔍 Problem:
sql
CopyEdit
FULL OUTER JOIN
bash
CopyEdit
#1064 - You have an error in your SQL syntax
✅ Solution:
To achieve the effect of a FULL OUTER JOIN in MySQL, you need to combine a LEFT
JOIN and a RIGHT JOIN using UNION.
sql
CopyEdit
-- LEFT JOIN part
SELECT employee.emp_id, employee.first_name, branch.branch_name
FROM employee
LEFT JOIN branch ON employee.emp_id = branch.mgr_id
UNION
💡 Notes:
This approach ensures you get all rows from both tables, even when there’s no match.
Use UNION ALL instead of UNION if you want to include duplicates.
Nested Query
Sure! Let's understand Nested Queries (also called Subqueries) in SQL in the simplest and
easiest way — with examples and demo outputs.
✅ Query: Find the name of the employee with the highest salary.
SELECT name
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
);
🧾 Output:
name
Hamza
SELECT name
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
);
Example: Find employees who earn the same salary as someone from department 2.
SELECT name
FROM employees
WHERE salary IN (
SELECT salary
FROM employees
WHERE department_id = 2
);
SELECT avg_salary
FROM (
SELECT AVG(salary) AS avg_salary
FROM employees
) AS avg_table;
id name marks
1 Ali 88
2 Sana 92
3 Usman 70
4 Hina 92
✅ Output:
name
Sana
Hina
💡 Tips:
Use this When you want to...
= Match one value
IN Match many values
>, < Compare values
EXISTS Check if result exists
Nested Query is basically a Query Where we are going to be using multiple select Statements. Lots
of time we are Going to get very specific Information and we are going to need to use the Results of
One SELECT statement to Inform the results Of another SELECT statements.
It is more Advance Query Writing. But Lots of information you will Get using the nested Query.
1. Find names of all employees who have sold Over 30000 to a Single Client.
SELECT employee.first_name,employee.last_name
FROM employee
WHERE employee.emp_id IN(
SELECT works_with.emp_id
FROM works_with
WHERE works_with.total_sales > 30000
);
2. Finding Out All of the Clients who are handled by the branch That Micheal
Scott manages. Assume you know Micheal’s ID.
SELECT client.client_name
FROM client
WHERE client.branch_id = (
SELECT branch.branch_id
FROM branch
WHERE branch.mgr_id= 102
LIMIT 1
# it is Possible that Micheal Scott should manage multiple branch that’s why we limit it With
one.
# if Micheal Scott is Manage Mutiple branches In that Case We will use”IN” after client.branch_id
);
As long as you are able to break the Nested query in parts you are Become more able to Understand and
write out these Quries.
On Delete
Deleting entries in a Database when a Foreign key is associated to them. Meaning Deleting Those
Entries Which are connected With each other Through the Different tables with the help of the
Foreign keys.
ON DELETE CASCADE:-
We will Describe Out the Setting when we are Going to Create The Foreign key which is
basically linking The Different Tables With Each others. In ON DELETE CASCADE is
essentially Where if we delete the employee Whose ID is Stored in the manager ID column,
Then we are just Going to Delete the entire row in the database.
You can See that the manager_id is Set to be NULL and Same things happened with the
Employee’s Table.
For ON DELETE CASCADE
Because DELETE is designed to remove records (rows) from a table, not the table itself.
Example:
✅ This removes:
All rows
All columns
All indexes, constraints, and the table definition
Triggers
Here’s a simple, step-by-step look at SQL Triggers, with easy examples and “demo” tables so
you can see exactly what happens when they fire.
🤔 What Is a Trigger?
A trigger is a piece of SQL code that automatically runs (“fires”) when a specified event
happens on a table.
You define:
1. WHEN it fires:
o BEFORE or AFTER an event
2. WHAT event:
o INSERT, UPDATE, or DELETE
3. ON WHICH TABLE
FOR EACH ROW means the trigger runs once per affected row.
Inside the trigger you can reference:
o NEW.col (the value being inserted/updated)
o OLD.col (the previous value for UPDATE/DELETE)
1. Create Tables
-- Main table
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(9,2)
);
-- Audit log
CREATE TABLE salary_changes (
change_id INT AUTO_INCREMENT PRIMARY KEY,
emp_id INT,
old_salary DECIMAL(9,2),
new_salary DECIMAL(9,2),
changed_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
1 Ali 20,000
2 Sana 25,000
salary_changes (empty)
▶️Run an UPDATE
UPDATE employees
SET salary = 27_000
WHERE emp_id = 2;
employees stays:
1 Ali 20,000
2 Sana 27,000
1. Table: accounts
102 Hamza 0
2. Trigger: Block DELETE if balance > 0
CREATE TRIGGER trg_before_account_delete
BEFORE DELETE ON accounts
FOR EACH ROW
BEGIN
-- If there’s still money, stop the delete
IF OLD.balance > 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot delete account with positive balance.';
END IF;
END;
3. Demo
💡 Key Takeaways
✅ Next Steps
Try writing a DELETE trigger that archives rows instead of deleting them.
Experiment with an INSERT trigger that assigns a default value or generates an audit
record.
Trigger is basically a block of SQL code which We can write Which will define
a certain Action that Should happen When a certain Operation get performed
on the database.
So, I Could Write a trigger Which will Tell MySQL To do Something
CREATE Table trigger_test (
message VARCHAR(100)
);
Here we are Going to Create Out the table Where will the Triggering Operations Are performed.
DELIMITER $$
CREATE
TRIGGER my_trigger BEFORE INSERT ON employee
FOR EACH ROW BEGIN
INSERT INTO trigger_test VALUES ('Added New Employee');
END$$
DELIMITER ;
Explanation
You're doing great by learning SQL triggers! Let's break this trigger query into very simple,
beginner-friendly explanations, step by step.
CREATE
TRIGGER my_trigger BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
INSERT INTO trigger_test VALUES ('Added New Employee');
END$$
DELIMITER ;
🔹 DELIMITER $$
By default, SQL uses the ; symbol to know where a command ends. But here, you're writing a
trigger, which has multiple lines and semicolon ; inside.
So:
✅ This means:
"Run this trigger right before someone adds a new employee to the employee table."
🔹 FOR EACH ROW
This means:
"Do this action for every new row inserted."
This is the body of the trigger — the actual action it will perform.
This is the action that will happen every time a new employee is added.
END$$ ➜ Marks the end of the trigger, using $$ (not ;) because we changed the
delimiter earlier.
DELIMITER ; ➜ Now we reset the delimiter back to normal.
✅ Final Notes:
trigger_test must already exist.
trigger_test should have a column that accepts that text 'Added New Employee'.
DELEIMETER is keyword in SQL which will basically Change the delimeters of MySQL
If Any Entries are inserted inside the employee Table then it will add These values inside the
trigger_test Table.
To test that trigger is Working OR Not we are Inserting the value inside the employee.
Second Trigger
DELIMITER $$
CREATE
TRIGGER my_trigger11 BEFORE INSERT ON employee
FOR EACH ROW BEGIN
INSERT INTO trigger_test VALUES (New.first_name);
END$$
DELIMITER ;
OUTPUT
It is Basically Running both Of the Triggers.
Third trigger;
DELIMITER $$
CREATE
TRIGGER my_trigger22 BEFORE INSERT ON employee
FOR EACH ROW BEGIN
if NEW.sex = 'M' THEN
INSERT INTO trigger_test VALUES('NAR EMPLOYEE ADD THEE
GYA');
ELSEIF NEW.sex = 'F' THEN
INSERT INTO trigger_test VALUES('MADHA EMPLOYEE ADD THE
GYE HA');
ELSE
INSERT INTO trigger_test VALUES(' NA NAR HA NA MADHA HA');
END IF;
END$$
DELIMITER ;
EMPLOYEE
INSERT INTO `employee` (`emp_id`, `first_name`, `last_name`,
`birth_day`, `sex`, `salary`, `super_id`, `branch_id`) VALUES ('112',
'Huzaifa222', 'Noor', '2002-09-05', 'M', '38923892', '103', '3');
OUTPUT
Third trigger;
DELIMITER $$
CREATE
TRIGGER my_trigger22 AFTER INSERT ON employee
FOR EACH ROW BEGIN
if NEW.sex = 'M' THEN
INSERT INTO trigger_test VALUES('NAR EMPLOYEE ADD THEE
GYA');
ELSEIF NEW.sex = 'F' THEN
INSERT INTO trigger_test VALUES('MADHA EMPLOYEE ADD THE
GYE HA');
ELSE
INSERT INTO trigger_test VALUES(' NA NAR HA NA MADHA HA');
END IF;
END$$
DELIMITER ;
We can also do for insert , Update and delete trigger.
Deleting Trigger
Great follow-up! To delete (remove) a trigger in SQL, you use the DROP TRIGGER command.
🧱 In Your Case:
You created a trigger named my_trigger. So, to delete it, the command is:
⚠️Important:
Some databases require you to specify the table or schema name, depending on the system
you're using:
💡 For MySQL:
DROP TRIGGER IF EXISTS my_trigger;
🧪 Tip:
ER Diagram intro
What is an ER Diagram?
1. Student
Attributes: student_id (PK), name, email
2. Course
Attributes: course_id (PK), title, credit_hours
3. Enrollment (the link between Students and Courses)
Attributes: student_id (FK), course_id (FK), grade
+-----------+ +--------------+
| STUDENT | | COURSE |
|-----------| |--------------|
| PK id |<--+ +->| PK id |
| name | | | | title |
| email | | | | credit_hours |
+-----------+ | | +--------------+
| |
| | ENROLLMENT
| | +-----------------------------+
+---+-| PK (id) (often composite) |
| | FK student_id --> STUDENT |
| | FK course_id --> COURSE |
| | grade |
| +-----------------------------+
Result
That single query shows how the three tables are tied together exactly like in the ER diagram.
1. Clear planning – Talk with teammates or clients before writing a single CREATE TABLE.
2. Catch mistakes early – See missing relationships or redundant data in the picture.
3. Documentation – New developers grasp the system quickly.
Entity:
An object we want to Model & Store Information about.
Great question! In phpMyAdmin’s Designer view, the different colored lines connecting your
tables visually represent relationships between fields, especially foreign key (FK)
relationships. Here's what each color typically means (based on phpMyAdmin's common
convention):
Color Meaning
🔵 Blue Line A foreign key relationship from a table to another (normal relationship).
🟢 Green Line A foreign key that points to the same table (self-reference).
A foreign key relationship that connects two tables through a third (bridge or
🟡 Yellow Line
many-to-many table).
This shows: Each employee belongs to one branch via branch_id (FK).
Type: Normal FK (so it uses a blue line).
📌 Summary
Company Diagram