0% found this document useful (0 votes)
2 views88 pages

SQL Course

A database is a collection of related information that can be stored in various formats, including on paper or digitally. Database Management Systems (DBMS) facilitate the creation, maintenance, and security of databases, allowing for CRUD operations. There are two main types of databases: relational (using SQL and structured tables) and non-relational (using flexible data structures), each with its own management systems and query languages.

Uploaded by

Huzaifa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views88 pages

SQL Course

A database is a collection of related information that can be stored in various formats, including on paper or digitally. Database Management Systems (DBMS) facilitate the creation, maintenance, and security of databases, allowing for CRUD operations. There are two main types of databases: relational (using SQL and structured tables) and non-relational (using flexible data structures), each with its own management systems and query languages.

Uploaded by

Huzaifa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 88

What is database ??

 Any collection of the related Information


o Phone Book
o Shopping list
o Todo list
o Your 5 best Friends list
 Database can stored in Different ways
o On paper
o In Your Mind
o On computer
o This power point
o Comments Sections

Computers + Databases = Heart


Amazon.com
 Keep tracks of Products, Reviews, Purchases Orders , Credits Cards , Users , Medias , Etc
 Trillions of pieces of information need to be Stored and readily available.
 Information is extremely valuable and critical to Amazon.com’s Functioning
 Security is essential , Amazon Stores Peoples Personal information
 Credit Card # , SSN, Address, Phone.
 Information is Stored on a Computer.

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.

Computer are great at keep track of Large amounts of information.

Database management System:-


A Special Software program that helps users Create and maintain A databases.

 Make it easy to manage large Amounts of Information.


 Handles Security.
 Backups
 Importing/exporting data
 Concurrency
 Interacts with software Applications
 Programming languages.

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.

Types of the Databases


Relational Databases(SQL):-
Organize data Into one or more tables.
 Each table has Columns and rows.
 A unique key identifies each rows.
Relation Data contain the Tables and the in the form of the rows And the columns.
 Relational database management system helps users to Create and maintain a
relational databases like MYSQL, ORACLES, POSTGREESQL,MRIADB, Etc
 Structured Query language(SQL)
 Standardized language For interacting with RDBMS.
 Used to Perform CURD operations as well as other administrative tasks to define
Tables and Structures.
 SQL Code used on One RDBMS is Not always Portable to another without
Modifications.

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.

Here it is in the simplest terms:

 SQL (Structured Query Language)


o A language for talking to relational databases.
o You use it to ask questions (queries), add, change, or remove data.
o It’s a standard—lots of database systems understand the same core SQL
commands (e.g. SELECT, INSERT, UPDATE, DELETE).
 MySQL
o A product—specifically, a Relational Database Management System (RDBMS)
made by Oracle.
o It stores your data in tables and runs SQL commands on that data.
o It also adds its own extra features (like storage engines, user-management tools,
backups).

Analogy

 SQL is like the English language.


 MySQL is like a book publisher that prints and distributes books in English—you need
the language (SQL) to write the books, and the publisher (MySQL) to actually produce
and manage them.

Quick Example

1. Writing in SQL (the language):


2. SELECT name, age
3. FROM users
4. WHERE age > 18;
5. Running it in MySQL (the software):
o You save that SQL sentence into MySQL, and it returns all adult users from its
stored tables.

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.

✅ Why Use Surrogate Keys?

 They are simple and fast (e.g., auto-increment numbers).


 Help avoid using complex or large natural keys (like Email, SSN, etc.).
 Keep relationships clean and efficient.

🔁 Natural Key vs Surrogate Key


Natural Key Surrogate Key
Comes from real data (e.g., Email, SSN) System-generated (e.g., Auto ID)
Has real-world meaning No real-world meaning
May change Never changes
Could be long or complex Always short and simple

✅ Example with Demo:

🎓 Suppose You Have a Students Table:

Without Surrogate Key (Using Natural Key):

CREATE TABLE Students (


email VARCHAR(100) PRIMARY KEY,
name VARCHAR(100),
age INT
);

Here, email is used as the primary key — but emails can change!
With Surrogate Key (Recommended):

CREATE TABLE Students (


student_id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(100),
name VARCHAR(100),
age INT
);

 student_id is a surrogate key.


 email, name, and age are real data.

Now you can safely change an email later without affecting relationships.

✅ Example of Data:

student_id email name age


1 [email protected] John Doe 21
2 [email protected] Sara Khan 22

 The student_id is auto-generated.


 It’s used to reference the student in other tables (e.g., enrollments).

✅ Use Case with Foreign Key:

Let’s create a new Courses table and a relationship with a Enrollments table.

CREATE TABLE Courses (


course_id INT PRIMARY KEY AUTO_INCREMENT,
course_name VARCHAR(100)
);

CREATE TABLE Enrollments (


enrollment_id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);

 Enrollments uses surrogate keys (student_id, course_id) to link tables.


 Efficient, clean, and works well in large databases.
✅ Benefits Summary:

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:

 Surrogate Key = Fake ID (system-generated, internal use only)


 Natural Key = Real-world data (like Email or SSN)
 Use Surrogate Keys when:
🔹 Natural keys are long, changeable, or not unique.

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 and Easy Explanation with Examples)

✅ **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.

✅ Examples of Natural Keys:

 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.

📘 Example with SQL Demo

🧑‍🎓 Student Table using a Natural Key:


Let’s say students have unique roll numbers in a school.

CREATE TABLE Students (


roll_number VARCHAR(20) PRIMARY KEY,
name VARCHAR(100),
age INT
);

Here, roll_number is the Natural Key because:

 It’s part of real data.


 It uniquely identifies each student.

📋 Sample Data:

roll_number name age

CS101 Ali Khan 21

CS102 Sara Noor 22

No need to create a new ID. The real-world roll_number is enough.

✅ When to Use a Natural Key

Use a natural key when:

 The real-world data is guaranteed to be unique (like a National ID).


 The key is not going to change.
 It’s already meaningful and easy to work with.

⚠️Potential Problems:

Natural Keys can cause issues if:

 They change (e.g., a user changes email).


 They are long or complex (like long strings).
 They are not guaranteed to be unique in future.
✅ Comparison: Natural Key vs Surrogate Key

Feature Natural Key Surrogate Key

Based on Real data System-generated (e.g. ID)

Meaningful Yes (e.g., email) No

Can change Sometimes Never

Use for joins Less efficient More efficient

💡 Best Practice:

 Use natural keys only when they are:


o Truly unique
o Stable (won’t change)
 Otherwise, use a surrogate key (like id) to avoid future issues.

🧠 Summary in One Line:

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, Easy Explanation with Examples & Demo)

✅ 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.

🧠 Think of it like this:

A foreign key is a reference. It tells the database:


“This value must exist in another table!”

✅ Why Use Foreign Keys?

 To connect related data (like students to courses).


 To ensure data integrity (no invalid or unrelated data).
 To prevent orphan records (e.g., an enrollment without a student).

📘 Real-Life Example:

Let’s say you have two tables:

 Students: Stores student info.


 Enrollments: Stores which student is enrolled in which course.

🔨 Step-by-Step SQL Demo:

1️⃣ Create Students Table

CREATE TABLE Students (


student_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);

2️⃣ Create Courses Table

CREATE TABLE Courses (


course_id INT PRIMARY KEY AUTO_INCREMENT,
course_name VARCHAR(100)
);

3️⃣ Create Enrollments Table with a Foreign Key

CREATE TABLE Enrollments (


enrollment_id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);

✅ In this case:

 student_id in Enrollments is a foreign key pointing to Students.student_id.


 course_id in Enrollments is a foreign key pointing to Courses.course_id.

📋 Sample Data:

🎓 Students Table

student_id name email

1 Ali Khan [email protected]

2 Sara Noor [email protected]


📚 Courses Table

course_id course_name

1 SQL Basics

2 Web Development

📝 Enrollments Table

enrollment_id student_id course_id

1 1 1

2 2 2

✅ This shows:

 Ali Khan is enrolled in SQL Basics.


 Sara Noor is enrolled in Web Development.

❌ What Happens if You Try to Insert Wrong Data?


INSERT INTO Enrollments (student_id, course_id) VALUES (5, 2);

⛔ This will give an error if student_id 5 doesn't exist in Students.

👉 This is referential integrity — Foreign Keys protect data accuracy.

✅ Summary in One Line:

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.

✅ What is a Composite Key in SQL?

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.

🎯 Why Use a Composite Key?

Imagine a table where:

 A student can enroll in multiple courses, and


 A course can have multiple students.
So we use both student_id and course_id together to make sure the same student is not added to
the same course twice.

📋 Example: StudentCourses Table


student_id course_id

1 101

2 101

1 102

 Here, neither student_id nor course_id alone is unique.


 But the combination of both is unique!

So, we can use a composite key: (student_id, course_id)

🛠️How to Create a Composite Key in SQL

✅ In MySQL / PostgreSQL
CREATE TABLE StudentCourses (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);

✅ Explanation:

 PRIMARY KEY (student_id, course_id) creates a composite key.


 This prevents duplicate combinations like (1, 101) from being added twice.

✨ 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

-- This will FAIL because (1, 101) already exists


INSERT INTO StudentCourses (student_id, course_id) VALUES (1, 101);
🔍 Use Case Summary
Situation Solution

No single column is unique Use a composite key

You want to prevent duplicate combinations Composite key helps

Example tables: Enrollment, OrderItems, BookingDetails, etc.

🧠 Tips

 Composite keys can only be used on two or more columns.


 They are used as a primary key or a unique constraint.

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.

These are Different types of things That SQL can Do.

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.

SELECT employee.name, employee.age


FROM employee
WHERE employee.salary > 30000
You can Write a Query Which will tell the RDBMS exactly What piece of Information you
want and it will be able to grab just that information

Basic Data types that Are used Inside the SQL


INT :- That Data type Is used For the Whole Numbers.

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.

VARCHAR(1):- String of text of length 1


VARCHAR(20):- Here 20 means We have assigned length to the characters. Because We want to
prevent the database From Wasting Space ,.

BLOB:- These data type are used for the binary large objects, Stores large Data.

DATE:- That data type is used to Store “YYYY-MM-DD”


TIMESTAMP:- That data type is used For the “YYYY-MM-DD HH::MM::SS” used for the Recording
time

There are two Ways to define a primary key inside the Queries .

Create table Student(


Create table Student(
Student_id INT,
Student_id INT PRIMARY KEY,
name VARCHAR(20),
name VARCHAR(20),
major VARCHAR(20),
major VARCHAR(20)
PRIMARY KEY(Student_id)
);
);
What is DESCRIBE in SQL?
The DESCRIBE command is used to show the structure of a table — meaning it tells you:

 The column names


 The data types of those columns
 Whether a column allows NULL values
 If a column is a Primary Key or has any default value

🔹 Syntax:
DESCRIBE table_name;

🔹 Example:

Imagine you have a table called students.

DESCRIBE students;

This will give you an output like:

Field Type Null Key Default Extra


id int NO PRI NULL auto_increment
name varchar YES NULL
age int YES NULL
email varchar YES NULL

🔹 Simple Meaning:

DESCRIBEis like asking SQL:


"Hey, what does this table look like?"
And SQL replies with all the column details.
ALTER :- The Command to add new Column inside of the database.

ALTER Table student ADD GPA Decimal(3, 2);


ALTER Table student DROP COLUMN gpa;

Inserting Data into the tables

Insert into student Values( 2, 'Hamza noor', 'sociology')

Select * From Student;

Like that how I can Skip a particular column when I tried to insert out their values.

insert into student(Student_id,name) Values( 3, 'Hamza noor')

These are the SQL Queries of the table.

Create table visitors (

visitors_id int AUTO_INCREMENT,

name varchar(20) Not Null DEFAULT ‘Unkown’ ,

major varchar(20) Unique ,

Primary Key(visitors_id)

);

Insert into visitors value(1,'HUZAIFA','Computer Sceince');

Insert into visitors value(2,'HAmze','medical Sceince');

Insert into visitors value(3,'Usama','checmical Sceince');


Autoincrement will Increment the data automatically Without defining the ID of
the data.

Create table visitors (

visitors_id int AUTO_INCREMENT,

name varchar(20) Not Null DEFAULT ‘Unkown’ ,

major varchar(20) Unique ,

Primary Key(visitors_id)

);

Insert into visitors(name, major)


value('HUZAIFA','Computer Sceince');

Insert into visitors(name, major) value('HAmze','medical


Sceince');

Insert into visitors(name, major) value('Usama','checmical


Sceince');

Updating and Deleting Data With SQL

SELECT * FROM student; SELECT * FROM student;

UPDATE student UPDATE student

SET major = “CS” SET name = “HUZAIFA ” ,major = “CS”

WHERE major= “Computer Science”; WHERE student_id = 1;

SELECT * FROM student;

UPDATE student

SET name = “Unkown” ;


📌 What is SET?

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:

 UPDATE tells SQL which table to update.


 SET tells SQL what data to change and what to change it to.
 WHERE (optional) tells SQL which rows to update (explained below).

📊 Example:

Let’s say we have a table named students:

id name marks
1 Ali 75
2 Sana 85
3 Ahmed 65

🎯 Goal:

We want to change Ahmed's marks to 90.

✅ 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.

✅ Syntax (used in various SQL commands):


SELECT * FROM table_name WHERE condition;
UPDATE table_name SET column = value WHERE condition;
DELETE FROM table_name WHERE condition;

📊 Example:

Using the same students table:

id name marks
1 Ali 75
2 Sana 85
3 Ahmed 90

🎯 Goal:

Select students who have marks greater than 80.

✅ 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

<> Symbol is used for the Not equal to


> Symbol is used for the greater than to
< Symbol is used for the less than to
>= Symbol is used for the Greater than or equal to
<= Symbol is Used for the less than or equal to

Difference between the DELETE and DROP


Feature DELETE DROP

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

Undo? ❗ Hard to undo unless using transactions ❗ Cannot undo easily

Syntax DELETE FROM table_name WHERE... DROP TABLE table_name

🔹 DELETE Command

📌 Purpose:

Used to remove specific rows (records) from a table.

✅ Syntax:
DELETE FROM table_name
WHERE condition;

🧪 Example:

Suppose we have a table named employees:

id name position

1 Ali Manager

2 Sana Developer

3 Ahmed Developer

🎯 Goal: Remove Ahmed’s record.


DELETE FROM employees
WHERE name = 'Ahmed';

📦 Result After Delete:

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:

We have the same employees table.

🎯 Goal: Completely remove the table from the database.


DROP TABLE employees;

📦 Result:

The entire employees table is deleted — it's like it never existed.

❌ You cannot query it anymore:

SELECT * FROM employees; -- ❌ Error: Table doesn't exist

🧠 In Simple Words
Command Think Like

DELETE Erasing data inside the table (keeping the table)

DROP Throwing the entire table in the trash (removes everything)

🎓 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:-

SELECT * FROM student;

DELETE student

SELECT * FROM student;

DELETE student;

WHERE name= “Huzaifa Noor” AND


major = “undecided”;

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.

🔹 What is ORDER BY in SQL?


📌 Definition:

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], ...;

 ASC = Ascending order (Default)


 DESC = Descending order

📊 Example Table: students


id name marks
1 Ali 75
2 Sana 85
3 Ahmed 65
4 Zara 95

🔸 Example 1: Sort by marks in ascending order


🎯 Goal: Show students sorted by lowest to highest marks.
SELECT * FROM students
ORDER BY marks ASC;

🧾 Output:

id name marks
3 Ahmed 65
1 Ali 75
2 Sana 85
4 Zara 95

🔸 Example 2: Sort by marks in descending order


🎯 Goal: Show students from highest to lowest marks.
SELECT * FROM students
ORDER BY marks DESC;

🧾 Output:
id name marks
4 Zara 95
2 Sana 85
1 Ali 75
3 Ahmed 65

🔸 Example 3: Sort by name in alphabetical order


SELECT * FROM students
ORDER BY name ASC;

🧾 Output:

id name marks
1 Ali 75
3 Ahmed 65
2 Sana 85
4 Zara 95

🔤 ORDER BY also works on text (alphabetical) values.

🔸 Example 4: Sort by two columns (marks and then name)


SELECT * FROM students
ORDER BY marks DESC, name ASC;

🧾 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.

Different Operations inside the Query


SELECT * FROM student WHERE student_id <= 3 AND name <> ‘HUZAIFA NOOR’

SELECT * FROM students WHERE name IN(‘Huzaifa’,’Hamza’,’asaav’);

"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.

🔹 Why use REFERENCES?


 To connect data in one table to data in another.
 To maintain data integrity.
 To avoid duplicate or orphan records.

🔹 Think of it like this:


You have two tables:
 Students table (student data)
 Classes table (class data)

Each student belongs to a class, so we need to link students to their class.

🔹 Example (Simple)
Step 1: Create the Classes table
CREATE TABLE Classes (
class_id INT PRIMARY KEY,
class_name VARCHAR(100)
);

Step 2: Create the Students table using REFERENCES


CREATE TABLE Students (
student_id INT PRIMARY KEY,
student_name VARCHAR(100),
class_id INT,
FOREIGN KEY (class_id) REFERENCES Classes(class_id)
);

✅ Now, Students.class_id must match a value in Classes.class_id.

🔹 How does it work?


 When you insert a student, their class_id must exist in the Classes table.
 If you try to add a class_id that doesn't exist — SQL will give an error.

🔹 Insert Example
-- Insert into Classes
INSERT INTO Classes (class_id, class_name)
VALUES (1, 'Computer Science');

-- Insert into Students (valid class_id)


INSERT INTO Students (student_id, student_name, class_id)
VALUES (101, 'Ali Khan', 1); -- ✅ Works!

-- Insert with invalid class_id


INSERT INTO Students (student_id, student_name, class_id)
VALUES (102, 'Sara Ahmed', 2); -- ❌ Error! Class 2 doesn't exist

🔹 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.

🔹 Bonus Tip: Foreign Key Shortcut


You can also define it in one line like this:

class_id INT REFERENCES Classes(class_id)

But using FOREIGN KEY is more clear.

Let me know if you want a practice quiz, real-world example, or a diagram to visualize it!

Company Database Into


Schema/Structure For The Company database:
SQL Queries for the Company database:-
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
);
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
);
ALTER TABLE employee
ADD FOREIGN KEY(branch_id)
REFERENCES branch(branch_id)
ON DELETE SET NULL;
ALTER TABLE employee
ADD FOREIGN KEY(super_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL;
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
);
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
);
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
);
-- Corporate
INSERT INTO employee VALUES(100, 'David',
'Wallace', '1967-11-17', 'M', 250000, NULL,
NULL);
INSERT INTO branch VALUES(1, 'Corporate', 100,
'2006-02-09');
UPDATE employee
SET branch_id = 1
WHERE emp_id = 100;
INSERT INTO employee VALUES(101, 'Jan',
'Levinson', '1961-05-11', 'F', 110000, 100, 1);
-- Scranton
INSERT INTO employee VALUES(102, 'Michael',
'Scott', '1964-03-15', 'M', 75000, 100, NULL);
INSERT INTO branch VALUES(2, 'Scranton', 102,
'1992-04-06');
UPDATE employee
SET branch_id = 2
WHERE emp_id = 102;
INSERT INTO employee VALUES(103, 'Angela',
'Martin', '1971-06-25', 'F', 63000, 102, 2);
INSERT INTO employee VALUES(104, 'Kelly',
'Kapoor', '1980-02-05', 'F', 55000, 102, 2);
INSERT INTO employee VALUES(105, 'Stanley',
'Hudson', '1958-02-19', 'M', 69000, 102, 2);
-- 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);

Explanation of the Query


Absolutely! Let's go step-by-step and explain the entire SQL script like you're learning for the
first time.
🌟 SIMPLE & DETAILED EXPLANATION
OF THE SQL SCRIPT
Imagine you are building a system for a company (like Dunder Mifflin from "The Office") where
you want to store data about:

 Employees
 Branches (offices)
 Clients (customers)
 Sales (who sold what to whom)
 Suppliers (who gives you goods)

Now let’s break down the SQL script.

🧱 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
);

What this does:

 Creates a table to store employee data.


 emp_id: Unique number for each employee.
 first_name, last_name: Employee's name.
 birth_day: Date of birth.
 sex: 'M' or 'F'.
 salary: How much the employee earns.
 super_id: ID of the supervisor (another employee).
 branch_id: Which office (branch) they work in.

🔹 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
);

What this does:

 Stores data about office branches.


 branch_id: Unique ID for each branch.
 branch_name: Name of the branch.
 mgr_id: Employee ID of the manager.
 mgr_start_date: When the manager started.
 FOREIGN KEY: Links mgr_id to employee table's emp_id.

🧠 ON DELETE SET NULL means: if the manager is deleted, set mgr_id to NULL.

🔹 Linking employee and branch


ALTER TABLE employee
ADD FOREIGN KEY(branch_id)
REFERENCES branch(branch_id)
ON DELETE SET NULL;

Links each employee to the branch they work at.

🔹 Self-reference: super_id
ALTER TABLE employee
ADD FOREIGN KEY(super_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL;

This says: one employee can be the supervisor of another.

🔹 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
);

Stores information about clients (customers). Each client is linked to a branch.

🔹 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
);

This table tracks sales made by employees to clients.

 total_sales: How much an employee sold to a client.


 ON DELETE CASCADE: If an employee or client is deleted, delete their sales records too.

🔹 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
);

Stores which suppliers supply which branches.

✅ 2. INSERTING DATA
Now, you add data (records) to those tables.

🏢 Corporate Branch & Manager


INSERT INTO employee VALUES(100, 'David', 'Wallace', ...);
INSERT INTO branch VALUES(1, 'Corporate', 100, ...);
UPDATE employee SET branch_id = 1 WHERE emp_id = 100;
 David Wallace is created as an employee and made the manager of the Corporate branch.

🏢 Scranton Branch

Michael Scott is created as an employee and set as manager of Scranton.

Then Angela, Kelly, and Stanley are added as employees under Michael.

🏢 Stamford Branch

Josh is created and set as manager of Stamford branch.

Andy, Jim are added to Stamford under Josh.

📦 Suppliers for Branches


INSERT INTO branch_supplier VALUES(2, 'Hammer Mill', 'Paper');

This means:

 Scranton (branch 2) gets paper from "Hammer Mill".


 Stamford (branch 3) gets supplies too.

👥 Clients
Clients are linked to branches:

INSERT INTO client VALUES(400, 'Dunmore Highschool', 2);

Means "Dunmore Highschool" is a client of Scranton.

💼 Sales (works_with table)


INSERT INTO works_with VALUES(105, 400, 55000);
Means:

 Employee 105 (Stanley) sold $55,000 to client 400 (Dunmore Highschool).

🧠 SUMMARY IN SIMPLE WORDS


Concept Meaning
Tables Like Excel sheets, store specific kinds of data
Primary Key Unique ID in a table (no duplicates)
Foreign Key Connects two tables (like links between pages)
ON DELETE CASCADE Delete linked records automatically
ON DELETE SET NULL If linked data is deleted, just set it to NULL

📊 Visual Overview
Think of this like connected sheets:

[employee] --works_with--> [client]


↑ ↑
| |
mgr_id branch_id
↓ ↓
[branch] <--- branch_supplier

Explanation from video


1. FOREIGN KEY(mgr_id) REFERENCES employee(emp_id) ON DELETE SET NULL
That line of the query mean’s that We are going to create out the “mgr_id” as a
Foreign_key and the we will make it to REFERENCES to the employee’s table “emp_id”
which is basically the Primary key.
“ Primary key is always referenced by the foreign key ”
And at the end we are going to set out that on deleting the Forigen setting out the their
Value “NULL” on the “mgr_id”

"ON DELETE SET NULL" means:


If the related record in the parent table (employee) is deleted, then set the foreign key in the
child table (branch) to NULL.

2. After Thatwe are Going to Create out the “employee.super_id” AND


“employee.branch_id” as a Foreign Key in the Following Query.
Same like the previous we will create two more Foreign keys inside the
employee table.

ALTER TABLE employee


ADD FOREIGN KEY(branch_id) REFERENCESbranch(branch_id)
ON DELETE SET NULL;

3. The Above Foreign key (brench_id) Of the Employee Table is referenced


Form the “branch_id” Which id Primary key of the Branch Table.
ALTER TABLE employee ADD FOREIGN KEY(super_id) REFERENCES employee(emp_id) ON DELETE SET NULL;
ALTER TABLE employee
The Above foreign key is “super_id” is Referenced by the
ADD FOREIGN
“emp_id” whichKEY(super_id)REFERENCES
is the primary key employee(emp_id)
ON DELETE SET NULL;

4. After that we will Create out the branch 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
);

5. After that we will create out the “Works with-in ” 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
);

Inside that table Each Component “emp_id”


is Foreign and the primary key also.

ON DELETE CASCADE Deletes all related records automatically

This is used to keep data clean and avoid errors, depending on how you want your
database to behave when something gets deleted.

6. After That we will Create out the “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
);
All of the tables that meant to be existed.
7. Inside that here we are Going to Insert the data For the
Corporate Values
Corporate
INSERT INTO employee VALUES(100, 'David',
'Wallace', '1967-11-17', 'M', 250000, NULL,
NULL);
INSERT INTO branch VALUES(1, 'Corporate', 100,
'2006-02-09');
UPDATE employee
SET branch_id = 1
WHERE emp_id = 100;
INSERT INTO employee VALUES(101, 'Jan',
'Levinson', '1961-05-11', 'F', 110000, 100, 1);

8. Inserting out the Data For the “scranton” Here we Are


Going to Inserting out the Data For the “scranton”
branch.
-- Scranton
INSERT INTO employee VALUES(102, 'Michael',
'Scott', '1964-03-15', 'M', 75000, 100, NULL);
INSERT INTO branch VALUES(2, 'Scranton', 102,
'1992-04-06');
UPDATE employee
SET branch_id = 2
WHERE emp_id = 102;
INSERT INTO employee VALUES(103, 'Angela',
'Martin', '1971-06-25', 'F', 63000, 102, 2);
INSERT INTO employee VALUES(104, 'Kelly',
'Kapoor', '1980-02-05', 'F', 55000, 102, 2);
INSERT INTO employee VALUES(105, 'Stanley',
'Hudson', '1958-02-19', 'M', 69000, 102, 2);

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);

More Basic Queries


Query to Find out all of the data from The employees.
SELECT * FROM employee
Query to Find out all of the data From the clients.

SELECT * FROM clients


Select All From the Employees and It should be Ordered By the salary.

SELECT * FROM employee ORDER BY salary


Select All From the Employees and It should be Ordered By the salary. And their Order Should be
inside the DESC.

SELECT * FROM employee ORDER BY salary DESC


Finding All of the employees Order By their Sex and then names

SELECT * FROM employee ORDER BY sex , first_name ,


last_name
Finding out the data of the first 5 employee inside the Table.

SELECT * FROM employee LIMIT 5


Writing out the Query to Findout the First and the last name of all the employees.

SELECT * FROM employee first_name , last_name


Writing out the SQL Query to Find out All of the Genders

SELECT FROM DISTINCT sex


Writing out the SQL Query to Find out All of the Branches

SELECT FROM DISTINCT Branches

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.

1. Finding the Number of employees


SELECT COUNT(emp_id) FROM employee;

2. Finding the Number Of the female Employees born after 1987.


SELECT COUNT(emp_id) FROM employee WHERE sex = ‘F’ AND birth_date > ‘1970-01-01’
3. Finding out the average Salaries of all Of the employees.

SELECT AVG(salary) FROM employee;

4. Finding out the average from all the male Employees.


SELECT AVG(salary) FROM employee WHERE sex = ‘M’;
5. Finding out the SUM of all Employee inside the Company.

SELECT SUM(salary) FROM employee;

6. Finding Out how many males and Females are There in Company.

SELECT COUNT(sex) FROM employee;

7. Finding out how many males and the females Also group by their Gender

SELECT COUNT(sex), sex FROM employee GROUP BY sex;


8. Finding out the Total Sales of the each Salesman(emp_id).

SELECT SUM(total_sales), emp_id FROM work_with GROUP BY emp_id;

9. Finding out the Total amount how much each Client Spent with the branch.

SELECT SUM(total_sales), client_id FROM work_with GROUP BY client_id;

Wildcards

🌟 What is a Wildcard in SQL?

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';

The pattern includes wildcard characters.

🔑 Common Wildcards
Wildcard Meaning

% Any number of characters (including 0)

_ A single character

[ ] Any one character in the brackets (only in SQL Server)

[^ ] or ! Not in the list (only in SQL Server)

🟢 Example Table: Students


id name

1 John

2 Johnny

3 Jonathan

4 Joanne

5 Jack

6 Jill

7 Bob

🎯 1. Using % — Match any number of characters

Find all names starting with "Jo"


sql
CopyEdit
SELECT name FROM Students
WHERE name LIKE 'Jo%';
🟨 Output:

nginx
CopyEdit
John
Johnny
Jonathan
Joanne

% means: anything can come after "Jo"

Find all names ending with "n"


sql
CopyEdit
SELECT name FROM Students
WHERE name LIKE '%n';

🟨 Output:

nginx
CopyEdit
John
Jonathan

% means: anything can come before "n"

Find names that contain "oh"


sql
CopyEdit
SELECT name FROM Students
WHERE name LIKE '%oh%';

🟨 Output:

nginx
CopyEdit
John
Johnny

% means: anything can come before and after "oh"


🎯 2. Using _ — Match exactly one character

Find all 4-letter names starting with "J"


sql
CopyEdit
SELECT name FROM Students
WHERE name LIKE 'J___';

🟨 Output:

nginx
CopyEdit
John
Jack
Jill

Each _ stands for one character

🎯 3. Using [ ] — Match specific characters (SQL Server only)

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

[o,a] means second letter is either "o" or "a"

🎯 4. Using [^ ] — Not matching the characters (SQL Server only)

Find names starting with J but second letter is not "o"


sql
CopyEdit
SELECT name FROM Students
WHERE name LIKE 'J[^o]%';
🟨 Output:

nginx
CopyEdit
Jack
Jill

[^o] means second letter is not "o"

📝 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

% Any number of characters 'Jo%'

_ One character 'J___'

[abc] Any of these letters 'J[a,o]%'

[^abc] Not any of these letters 'J[^o]%'

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.

% = any # = characters , _ = one Character


1. Finding Any Client’s name who are Something like LLC.

SELECT * FROM client WHERE client_name LIKE ‘%LLC’;

2. Write Out the Query To Find Any Branch Supplier who are in the label Bussiness.

SELECT * FROM branch_supplier WHERE supplier_name LIKE ‘% LABEL%’;

3. Finding out the Employee Who are born in October(10th month).

SELECT * FROM employee WHERE birth_date LIKE ‘____-10%’;


To Write the above the Query First you Should have to understand the Format of the Query.

4. Finding Any Clients Who are schools ,.. Meaning finding The name Of the client who are School.

SELECT * FROM clients WHERE client_name LIKE ‘%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.

🌟 What is UNION in SQL?


UNION is used to combine the results of two or more SELECT statements into a single result.

✅ It removes duplicate rows by default.

🧠 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

✔️Carol appears only once, even though it was in both tables.

🎯 2. Using UNION ALL

SELECT name FROM Students_A


UNION ALL
SELECT name FROM Students_B;

🟨 Output:

Alice
Bob
Carol
David
Carol
Emma
✔️Carol appears twice because UNION ALL keeps duplicates.

🎯 3. Using UNION with more columns


SELECT id, name FROM Students_A
UNION
SELECT id, name FROM Students_B;

🟨 Output:

1 | Alice
2 | Bob
3 | Carol
1 | David
3 | Emma

SQL compares both id and name to remove exact duplicates.

📝 Notes:
 You can add ORDER BY at the end to sort the final result:

SELECT name FROM Students_A


UNION
SELECT name FROM Students_B
ORDER BY name;

 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;


2. If we Also want to Find out the List of Clients And With including the Previous Data Then we will use
the Following Query.

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.

SELECT first_name AS Company_Names FROM employee UNION SELECT branch_name FROM


branch;

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.

SELECT clients_name , branch_id FROM client UNION SELECT supplier_name , branch_id


FROM branch_supplier;

OR
If we want to Differntiate the names of the Common Columns We Can Do it like that

SELECT clients_name , client.branch_id FROM client


UNION
SELECT supplier_name , branch_supplier.branch_id FROM branch_supplier;

6. Write a Query to Find out the List of all money spent or Earned by the Company.

SELECT salary FROM employee


UNION
SELECT total_sales FROM work_with;
But you Can take these Examples And Extrapolate it out to More Complex Examples. Union
basically Combine results From Two Select Statements.

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.

🧠 What is a JOIN in SQL?


A JOIN in SQL is used to combine rows from two or more tables based on a related column
between them.

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

course_id student_id course_name


101 1 Math
102 1 Science
103 2 History
104 4 English

🧩 Types of JOINS with Examples


1. ✅ INNER JOIN
Shows only the matching records in both tables.

🔍 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.

2. 🌍 LEFT JOIN (or LEFT OUTER JOIN)


Shows all students, even if they don’t have any course. If no course, it shows NULL.

🔍 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

👉 Note: Charlie is included, but with NULL because he has no course.


3. 🌎 RIGHT JOIN (or RIGHT OUTER JOIN)
Shows all courses, even if they are not linked to any student. If no student, it shows 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

👉 Note: "English" is included even though no matching student exists.

4. 🔄 FULL OUTER JOIN


Shows all records from both tables. If no match, fills with NULL.

💡 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:

Every student is matched with every course:

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:

 students = List of people.


 courses = List of classes they
are taking.
 INNER JOIN = People who are enrolled in at least one course.
 LEFT JOIN = Show all people, even those not taking any class.
 RIGHT JOIN = Show all courses, even if nobody enrolled.
 FULL OUTER JOIN = Everyone and every course, connected or not.
Joins
 Joins are basically used to Combine rows from two or more tables based on the related
columns between them.
 Joins can be really use full for Combining information from the Different Tables into a
Single Result which we can use to Find out the specific Information form a database.

1. Finding All the branches and name of their managers.

(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.)

SELECT employee.emp_id,employee.first_name, branch.branch_name


FROM employee
JOIN branch
ON employee.emp_id = branch.mgr_id;
(Only those Emplyees are joined Whose “mgr_id “ Are exist inside the branch table)

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.

SELECT employee.emp_id,employee.first_name, branch.branch_name


FROM employee
RIGHT JOIN branch
ON employee.emp_id = branch.mgr_id;

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

is not valid in MySQL/MariaDB. That’s why you're seeing:

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.

Here’s how you can rewrite your query:

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

-- RIGHT JOIN part


SELECT employee.emp_id, employee.first_name, branch.branch_name
FROM employee
RIGHT JOIN branch ON employee.emp_id = branch.mgr_id;

💡 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.

✅ What is a Nested Query?


A Nested Query (or Subquery) is a query inside another query.

We use it when we want to:

 Get results based on another result.


 Break a complex problem into smaller parts.

🧠 Simple Example: Who has the highest salary?


🔸 Table: employees

emp_id name salary


1 Ali 20000
2 Sana 30000
3 Hamza 40000
4 Ayesha 25000

✅ 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

✅ Types of Nested Queries


There are 3 common types:

1. Single Row Subquery

Returns only one value.

SELECT name
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
);

2. Multiple Row Subquery

Returns many values (use IN).

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
);

3. Nested Query in FROM clause

Used as a temporary table.

SELECT avg_salary
FROM (
SELECT AVG(salary) AS avg_salary
FROM employees
) AS avg_table;

🧪 Demo: Students and Marks


Table: students

id name marks
1 Ali 88
2 Sana 92
3 Usman 70
4 Hina 92

🎯 Task: Find names of students who got the highest marks.


SELECT name
FROM students
WHERE marks = (
SELECT MAX(marks)
FROM students
);

✅ Output:

name
Sana
Hina

🧩 Why use Nested Queries?


 To filter based on another result.
 To break complex queries into smaller steps.
 To solve problems where one query depends on another.

💡 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 SET NULL:-


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 SET NULL if we
basically if Deleting one of these Employees That mean the manager ID “mgr_id” that are
associated to that Employee is Going to be set NULL.

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.

DELETE FROM employee WHERE emp_id = 102

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

DELETE FROM branch WHERE branch_id = 2;

It is deleted the whole Row here.

Primary key cannot be NULL so we cannot Set the values of


primary key ON DELETE NULL. It Should be Preferred on the Foreign
key.
Great question! Let's break it down in simple terms so you understand why we use DROP
instead of DELETE to remove a table.

🔄 DELETE vs DROP – What’s the Difference?

Table Data Rollback possible (if


Command What it does
remains? remains? transaction)?
DELETE Removes rows (data only) ✅ Yes ❌ No ✅ Yes
Removes entire table
DROP ❌ No ❌ No ❌ No
structure and data

🔹 Why we don't use DELETE to remove a table:

Because DELETE is designed to remove records (rows) from a table, not the table itself.

Example:

DELETE FROM trigger_test;


✅ This will delete all rows inside trigger_test,
❌ But the table (its columns and schema) still exists.

🔹 To remove the entire table (structure + data), we use:


DROP TABLE trigger_test;

✅ This removes:

 All rows
 All columns
 All indexes, constraints, and the table definition

🧠 Think of it Like This:

 DELETE = Clear all data from a whiteboard


 DROP = Throw the entire whiteboard away

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

🔨 Trigger Syntax (MySQL/PostgreSQL Style)


CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- your SQL statements here
END;

 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)

🛠️Example 1: Audit Log on UPDATE

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
);

2. Create the Trigger


CREATE TRIGGER trg_after_salary_update
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
-- Only log if salary actually changed
IF OLD.salary <> NEW.salary THEN
INSERT INTO salary_changes(emp_id, old_salary, new_salary)
VALUES (OLD.emp_id, OLD.salary, NEW.salary);
END IF;
END;

3. Demo: What Happens?


▶️Initial Data

emp_id name salary

1 Ali 20,000

2 Sana 25,000

salary_changes (empty)

(no rows yet)

▶️Run an UPDATE

UPDATE employees
SET salary = 27_000
WHERE emp_id = 2;

▶️After the UPDATE

employees stays:

emp_id name salary

1 Ali 20,000

2 Sana 27,000

salary_changes now has:

change_id emp_id old_salary new_salary changed_at

1 2 25,000 27,000 2025-06-10 14:05:00

🧪 Example 2: Prevent Negative Balances (BEFORE DELETE)

1. Table: accounts

acct_id owner balance

101 Ayesha 1500

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

 Attempt: DELETE FROM accounts WHERE acct_id = 101;


 Result:
 ERROR 1644: Cannot delete account with positive balance.

 But deleting acct_id = 102 (balance = 0) succeeds.

💡 Key Takeaways

 Triggers let you enforce rules or maintain logs automatically.


 BEFORE triggers can validate or block changes.
 AFTER triggers can record or react to changes.
 Use NEW.col for the incoming values, OLD.col for existing ones.
 Be careful: too many triggers can make writes slower and logic harder to debug.

✅ 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.

✅ Full Query First (What You Wrote)


DELIMITER $$

CREATE
TRIGGER my_trigger BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
INSERT INTO trigger_test VALUES ('Added New Employee');
END$$

DELIMITER ;

🔍 What Is This Query Doing (In Simple Words)?


This SQL query creates a trigger that automatically runs whenever a new row is added to the
employee table. When that happens, it inserts a message into another table called
trigger_test.

🧠 Explanation of Each Keyword

🔹 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:

 DELIMITER $$ tells SQL:


"Don't treat ; as the end. Use $$ instead."

✅ This allows you to write multi-line code like the trigger.

🔹 CREATE TRIGGER my_trigger

 CREATE TRIGGER ➜ This means:


"I want to make a new trigger."
 my_trigger ➜ This is the name of your trigger. You can choose any name.

✅ So this line means:


"Create a new trigger named my_trigger."

🔹 BEFORE INSERT ON employee

This tells SQL when the trigger should run:

 BEFORE ➜ Run the trigger before data is inserted.


 INSERT ➜ This trigger runs when someone adds a new row.
 ON employee ➜ The trigger is connected to the employee table.

✅ 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."

✅ Example: If 3 employees are inserted, the trigger runs 3 times.

🔹 BEGIN ... END

This is the body of the trigger — the actual action it will perform.

Everything between BEGIN and END is what the trigger does.

🔹 INSERT INTO trigger_test VALUES ('Added New Employee');

This is the action that will happen every time a new employee is added.

 It adds the message 'Added New Employee' to a table called trigger_test.

✅ So every time a new employee is inserted, a message is stored in trigger_test.

🔹 END$$ and DELIMITER ;

 END$$ ➜ Marks the end of the trigger, using $$ (not ;) because we changed the
delimiter earlier.
 DELIMITER ; ➜ Now we reset the delimiter back to normal.

🧠 Summary (Like a Story)


"When someone adds a new row to the employee table, this trigger will automatically insert a
message into the trigger_test table before the new employee is saved."

✅ 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

What Our Trigger is Doing?

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.

INSERT employee VALUES(109,’HUZAIFA’,’NOOR’, ‘M’,‘2002-09-


05’,69000,106,3);
That is Our trigger_test table. When the employee is Inserted

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.

✅ Syntax to Delete a Trigger:


DROP TRIGGER trigger_name;

🧱 In Your Case:

You created a trigger named my_trigger. So, to delete it, the command is:

DROP TRIGGER my_trigger;

⚠️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;

You can also specify the database:


DROP TRIGGER IF EXISTS your_database_name.my_trigger;

💡 For PostgreSQL (just FYI, it's different!):

You must drop it from the table:

DROP TRIGGER my_trigger ON employee;

🧪 Tip:

Always check that the trigger exists using this:

SHOW TRIGGERS; (in MySQL)

ER Diagram intro
What is an ER Diagram?

Term Plain-English meaning


Entity A thing you care about—usually becomes a table.
Relationship How two things are connected.
Attribute A fact about a thing—usually becomes a column.
PK (Primary Key) Column that uniquely identifies each row.
FK (Foreign Key) Column that points to the PK in another table.

Think of an ER diagram (Entity-Relationship diagram) as a simple picture of your data


before you build the tables. It shows the boxes (entities), the arrows/lines (relationships), and
the little notes on the lines (how many of each).

Step-by-Step Mini Example

Imagine a very tiny school:

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

Visual (ASCII) ER Diagram 📋

+-----------+ +--------------+
| 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 |
| +-----------------------------+

 Boxes = entities (future tables).

1 student ↔ many enrollments; 1 course ↔ many enrollments ⇒ classic “junction”


 Lines/arrows = relationships.

table for a many-to-many link.

From Diagram to SQL (Demo)


-- 1. Create the main tables
CREATE TABLE student (
student_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);

CREATE TABLE course (


course_id INT PRIMARY KEY,
title VARCHAR(100),
credit_hours INT
);

-- 2. Create the relationship (junction) table


CREATE TABLE enrollment (
student_id INT,
course_id INT,
grade CHAR(2),
PRIMARY KEY (student_id, course_id), -- composite PK
FOREIGN KEY (student_id) REFERENCES student(student_id),
FOREIGN KEY (course_id) REFERENCES course(course_id)
);
Why three tables?
Because the many-to-many Student↔Course link cannot live in just two tables without
duplicate rows, so we use enrollment to store each pairing.

Populating and Querying (Quick Test)


-- Insert some rows
INSERT INTO student VALUES (1,'Ana','[email protected]'),
(2,'Ben','[email protected]');
INSERT INTO course VALUES (10,'Maths',3), (20,'History',4);

INSERT INTO enrollment VALUES (1,10,'A'), (1,20,'B'), (2,10,'B');

-- Simple join to see who takes what


SELECT s.name, c.title, e.grade
FROM enrollment e
JOIN student s ON s.student_id = e.student_id
JOIN course c ON c.course_id = e.course_id;

Result

name title grade


Ana Maths A
Ana History B
Ben Maths B

That single query shows how the three tables are tied together exactly like in the ER diagram.

Why Use ER Diagrams?

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):

✅ Meaning of Line Colors in Your ER Diagram:

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).

💡 Quick Explanation With Your Tables:

1. employee ➝ branch (Blue Line)

 This shows: Each employee belongs to one branch via branch_id (FK).
 Type: Normal FK (so it uses a blue line).

2. employee ➝ employee (Green Line)


 Field super_id points to another emp_id in the same employee table.
 Type: Self-reference (employee is supervised by another employee).
 That’s why it uses a green line.

3. works_with ➝ employee + client (Yellow Lines)

 This table connects employees and clients (many-to-many).


 The yellow color helps highlight it’s a junction table.

📌 Summary

 Blue Line = FK to another table


 Green Line = FK within the same table (self-referencing)
 Yellow Line = Junction table (many-to-many relationships)

Demo Tip (Try This Yourself):

1. Hover over a line → it shows the field names involved.


2. Click on a table → highlights all links related to that table.

Company Diagram

You might also like