KEMBAR78
Mysql | PDF | Sql | Software Design
0% found this document useful (0 votes)
17 views57 pages

Mysql

The document provides an overview of MySQL data types, including numeric, string, date and time, boolean, and their respective examples. It also covers SQL commands categorized into DDL, DML, DQL, DCL, and TCL, along with examples of keys and constraints in SQL. Additionally, it discusses SQL operators and aggregate functions with practical examples for each.

Uploaded by

Ajit s Adin
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)
17 views57 pages

Mysql

The document provides an overview of MySQL data types, including numeric, string, date and time, boolean, and their respective examples. It also covers SQL commands categorized into DDL, DML, DQL, DCL, and TCL, along with examples of keys and constraints in SQL. Additionally, it discusses SQL operators and aggregate functions with practical examples for each.

Uploaded by

Ajit s Adin
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/ 57

In MySQL, data types define the type of data a column can hold (e.g., numbers, text, dates).

Choosing the right data type is important for performance and storage.

Main Categories of MySQL Data Types


1. Numeric Data Types

Used for storing numbers.

Data Type Description Example


INT
Integer (whole number), range: -2,147,483,648 to 25
2,147,483,647
TINYINT Very small integer, range: -128 to 127 1
SMALLINT Small integer 32000
MEDIUMINT Medium integer 8 million
BIGINT Large integer 9223372036854775807

DECIMAL(M,D)
Exact decimal numbers (good for money), M = DECIMAL(10,2) →
total digits, D = decimals 12345.67
NUMERIC(M,D) Same as DECIMAL

FLOAT
Approximate floating-point number (7 digits 3.14
precision)
DOUBLE
Double precision floating-point number (15 3.1415926535
digits precision)

2. String (Character) Data Types

Data Type Description Example


CHAR(n) Fixed length string (padded with spaces), max 255 CHAR(5) → 'Hi '
VARCHAR(n) Variable length string, max 65535 VARCHAR(100)
TEXT Long text (up to 65,535 characters) Article
TINYTEXT Up to 255 characters
MEDIUMTEXT Up to 16,777,215 characters
LONGTEXT Up to 4,294,967,295 characters
BLOB Binary data (images, files)

3. Date and Time Data Types

Data Type Description Example


DATE Stores date (YYYY-MM-DD) 2025-07-20
2025-07-20
DATETIME Stores date and time 14:30:00

TIMESTAMP
Stores UTC date and time (auto-updates on insert/update if 2025-07-20
needed) 14:30:00
Data Type Description Example
TIME Stores time only (HH:MM:SS) 14:30:00
YEAR Stores year (YYYY) 2025

4. Boolean Data Type

 MySQL does not have a real BOOLEAN type. It is an alias for TINYINT(1) where 0 =
FALSE and 1 = TRUE.

Example Table with Data Types


sql
CopyEdit
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age TINYINT,
grade CHAR(2),
enrolled_date DATE
);

Would you like me to give you a cheat sheet PDF of all MySQL data types (with sizes and
examples) that you can download?

SQL COMMANDS

ChatGPT said:

SQL (Structured Query Language) commands are instructions used to interact with a
database—creating tables, inserting data, updating records, and more. SQL commands are
grouped into five main categories:

1. DDL (Data Definition Language)


These commands define or modify database structures like tables and schemas.

Command Description Example


CREATE DATABASE school;
CREATE Creates a new database or table. CREATE TABLE students (id INT
PRIMARY KEY, name VARCHAR(50));
Changes an existing table ALTER TABLE students ADD email
ALTER
structure (add/remove columns). VARCHAR(100);
Command Description Example
Deletes a database or table
DROP DROP TABLE students;
permanently.
Deletes all rows in a table but
TRUNCATE TRUNCATE TABLE students;
keeps the table structure.

2. DML (Data Manipulation Language)


These commands deal with data inside tables.

Command Description Example


Adds new rows into a INSERT INTO students (name, age) VALUES
INSERT ('Alice', 14);
table.
UPDATE students SET age = 15 WHERE name =
UPDATE Modifies existing data. 'Alice';
Removes rows from a DELETE FROM students WHERE age > 18;
DELETE
table.

3. DQL (Data Query Language)


This is mainly for retrieving data.

Command Description Example


SELECT Fetches data from a table. SELECT * FROM students;

You can filter data with WHERE, sort with ORDER BY, or limit results:

sql
CopyEdit
SELECT name, age FROM students WHERE grade = 'A' ORDER BY age DESC LIMIT 5;

4. DCL (Data Control Language)


These commands control access and permissions.

Command Description Example


Gives user access to the GRANT ALL ON school.* TO
GRANT 'user'@'localhost';
database.
REVOKE ALL ON school.* FROM
REVOKE Removes user permissions. 'user'@'localhost';

5. TCL (Transaction Control Language)


These commands handle transactions (a group of SQL statements).
Command Description Example
COMMIT Saves changes made in a transaction. COMMIT;
ROLLBACK Undoes changes made in a transaction. ROLLBACK;
SAVEPOINT Sets a point in a transaction to roll back to. SAVEPOINT sp1;

Most Common SQL Workflow Example


sql
CopyEdit
-- Create a database
CREATE DATABASE school;

-- Use the database


USE school;

-- Create a table
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
);

-- Insert data
INSERT INTO students (name, age, grade)
VALUES ('John Doe', 15, 'A');

-- Query data
SELECT * FROM students;

-- Update data
UPDATE students SET grade = 'B' WHERE id = 1;

-- Delete data
DELETE FROM students WHERE id = 1;

Would you like me to create a one-page "SQL Commands Cheat Sheet


(PDF)" that explains all commands with syntax and examples for quick
revision?

Types of Keys in SQL (with Examples)

1. Primary Key
 Definition: A column (or combination of columns) that uniquely identifies each
record in a table.
 Rules:
o Cannot have duplicate values.
o Cannot be NULL.
o Each table can have only one primary key.

Example:

sql
CopyEdit
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);

Here, student_id uniquely identifies every student.

2. Composite Key (or Compound Key)


 Definition: A primary key made up of two or more columns.
 Used when no single column is unique, but a combination of columns is unique.

Example:

sql
CopyEdit
CREATE TABLE enrollment (
student_id INT,
course_id INT,
enrollment_date DATE,
PRIMARY KEY (student_id, course_id)
);

Here, the combination of student_id and course_id uniquely identifies each row.

3. Foreign Key
 Definition: A column that links to the primary key of another table.
 Ensures referential integrity (data in one table must exist in the referenced table).

Example:

sql
CopyEdit
CREATE TABLE courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(100)
);

CREATE TABLE enrollment (


student_id INT,
course_id INT,
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

Here, course_id in enrollment must exist in courses.

4. Unique Key
 Definition: Ensures all values in a column are unique (like a primary key) but allows
one NULL value.
 A table can have multiple unique keys.

Example:

sql
CopyEdit
CREATE TABLE teachers (
teacher_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);

Here, no two teachers can have the same email.

5. Candidate Key
 Definition: Any column (or set of columns) that can potentially be a primary key.
 A table can have multiple candidate keys, but only one is chosen as the primary key.

Example:
In a table students(name, roll_number, email), both roll_number and email can
uniquely identify a student. Both are candidate keys, but one becomes the primary key.

6. Alternate Key
 Definition: Candidate keys that are not selected as the primary key.
 Example: If roll_number is chosen as the primary key in students, then email
becomes an alternate key.
7. Super Key
 Definition: Any column or combination of columns that uniquely identifies rows.
 Every primary key is a super key, but not every super key is a primary key.

Example:
In a students(student_id, email, phone) table:

 student_id is a super key.


 (email, phone) together can also be a super key (if both are unique together).

Example Table with Multiple Keys


sql
CopyEdit
CREATE TABLE students (
student_id INT PRIMARY KEY, -- Primary Key
email VARCHAR(100) UNIQUE, -- Unique Key
phone VARCHAR(15) UNIQUE,
name VARCHAR(100)
);

CREATE TABLE enrollment (


student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id), -- Composite Key
FOREIGN KEY (student_id) REFERENCES students(student_id) -- Foreign Key
);

Would You Like a Diagram?


Would you like me to create a diagram (ERD) that visually explains Primary Key,
Foreign Key, and their relationships using the students and courses example?

Types of Constraints in SQL (with


Examples)
1. NOT NULL
 Ensures that a column cannot have a NULL value.
 Useful when a column is mandatory.

Example:

sql
CopyEdit
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT
);

Here, name cannot be empty (NULL).

2. UNIQUE
 Ensures all values in a column are different.
 Unlike a primary key, a table can have multiple UNIQUE constraints.
 Allows one NULL value.

Example:

sql
CopyEdit
CREATE TABLE teachers (
teacher_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);

No two teachers can have the same email.

3. PRIMARY KEY
 A combination of NOT NULL and UNIQUE.
 Uniquely identifies each record in a table.
 A table can have only one primary key.

Example:

sql
CopyEdit
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(100)
);
4. FOREIGN KEY
 Creates a link between two tables.
 Ensures that the value in a column matches a value in another table’s primary key.

Example:

sql
CopyEdit
CREATE TABLE courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(100)
);

CREATE TABLE enrollment (


student_id INT,
course_id INT,
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

The course_id in enrollment must exist in courses.

5. CHECK
 Ensures that all values in a column meet a specific condition.
 Helps enforce business rules.

Example:

sql
CopyEdit
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT CHECK (age >= 5 AND age <= 18)
);

Here, age must be between 5 and 18.

6. DEFAULT
 Assigns a default value to a column if no value is provided.

Example:

sql
CopyEdit
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
grade VARCHAR(10) DEFAULT 'C'
);

If no grade is given, it will default to C.

7. AUTO_INCREMENT
 Automatically generates a unique number when a new record is inserted.
 Usually used with primary keys.

Example:

sql
CopyEdit
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);

When inserting a new record, id will be auto-generated.

Example Table with Multiple Constraints


sql
CopyEdit
CREATE TABLE students (
student_id INT AUTO_INCREMENT PRIMARY KEY, -- Primary Key + Auto
Increment
name VARCHAR(100) NOT NULL, -- Cannot be NULL
email VARCHAR(100) UNIQUE, -- Must be unique
age INT CHECK (age >= 5 AND age <= 18), -- Must be between 5 and
18
grade VARCHAR(10) DEFAULT 'C' -- Default value
);

Types of SQL Operators


1. Arithmetic Operators
Used for mathematical operations.

Operator Description Example


+ Addition SELECT 10 + 5; -- Result: 15
- Subtraction SELECT 10 - 5; -- Result: 5
* Multiplication SELECT 10 * 5; -- Result: 50
/ Division SELECT 10 / 5; -- Result: 2
% Modulus (remainder) SELECT 10 % 3; -- Result: 1

2. Comparison (Relational) Operators


Used to compare values.

Operator Description Example


= Equal to SELECT * FROM students WHERE age = 15;
!= or <> Not equal to SELECT * FROM students WHERE age != 15;
> Greater than SELECT * FROM students WHERE age > 10;
< Less than SELECT * FROM students WHERE age < 10;
>= Greater than or equal SELECT * FROM students WHERE age >= 10;
<= Less than or equal SELECT * FROM students WHERE age <= 10;

3. Logical Operators
Used for combining conditions in queries.

Operator Description Example


AND
All conditions must be SELECT * FROM students WHERE age > 10 AND
true grade = 'A';

OR
At least one condition is SELECT * FROM students WHERE age > 10 OR
true grade = 'A';
NOT Negates a condition SELECT * FROM students WHERE NOT grade = 'A';

4. BETWEEN Operator
 Checks if a value is within a range.

sql
CopyEdit
SELECT * FROM students WHERE age BETWEEN 10 AND 15;
5. IN Operator
 Checks if a value matches any value in a list.

sql
CopyEdit
SELECT * FROM students WHERE grade IN ('A', 'B', 'C');

6. LIKE Operator (Pattern Matching)


 Used with WHERE for string matching.
 Wildcards:
o % → matches any number of characters.
o _ → matches exactly one character.

Examples:

sql
CopyEdit
SELECT * FROM students WHERE name LIKE 'A%'; -- Names starting with A
SELECT * FROM students WHERE name LIKE '_n'; -- Names with second letter n

7. IS NULL / IS NOT NULL


 Checks for NULL values.

sql
CopyEdit
SELECT * FROM students WHERE email IS NULL;

8. ANY / ALL Operators


 Used with subqueries.

sql
CopyEdit
SELECT * FROM students WHERE age > ALL (SELECT age FROM students WHERE
grade = 'B');

9. EXISTS Operator
 Checks if a subquery returns any rows.

sql
CopyEdit
SELECT * FROM students s WHERE EXISTS (SELECT * FROM courses c WHERE
c.course_id = s.id);

10. String Operators


 CONCAT() is used for string joining:

sql
CopyEdit
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM students;

SELECT * FROM STUDENT LIMIT 3;


Only selects 3 records

AGGREGATE FUNCTIONS
In SQL, aggregate functions are built-in functions used to perform calculations on a group
of values and return a single value as the result. They are often used with the GROUP BY
clause to summarize data, like calculating totals, averages, counts, etc.

Common SQL Aggregate Functions (With


Examples)

1. COUNT()
 Purpose: Returns the number of rows in a set.
 Usage Example:

sql
CopyEdit
SELECT COUNT(*) AS total_students FROM students;

This will return the total number of rows (students) in the students table.

 With Condition:

sql
CopyEdit
SELECT COUNT(*) FROM students WHERE grade = 'A';
Counts how many students have grade A.

2. SUM()
 Purpose: Returns the total sum of a numeric column.
 Usage Example:

sql
CopyEdit
SELECT SUM(age) AS total_age FROM students;

Adds all the ages of the students.

 With Condition:

sql
CopyEdit
SELECT SUM(age) FROM students WHERE grade = 'A';

3. AVG()
 Purpose: Returns the average value of a numeric column.
 Usage Example:

sql
CopyEdit
SELECT AVG(age) AS average_age FROM students;

Gives the average age of all students.

4. MIN()
 Purpose: Returns the smallest value from a column.
 Usage Example:

sql
CopyEdit
SELECT MIN(age) AS youngest FROM students;

Finds the youngest student.

5. MAX()
 Purpose: Returns the largest value from a column.
 Usage Example:

sql
CopyEdit
SELECT MAX(age) AS oldest FROM students;

Finds the oldest student.

6. GROUP_CONCAT() (MySQL-specific)
 Purpose: Combines values from a column into a comma-separated string.
 Usage Example:

sql
CopyEdit
SELECT GROUP_CONCAT(name) AS all_students FROM students;

Might return: 'John, Sarah, Alex, Emma'.

Using Aggregate Functions with GROUP


BY
To get results for each group of values, combine aggregate functions with GROUP BY.

Example:

sql
CopyEdit
SELECT grade, COUNT(*) AS students_count
FROM students
GROUP BY grade;

This will count how many students are in each grade (A, B, C, etc.).

Using HAVING with Aggregate Functions


HAVING is used to filter aggregate results (like WHERE, but for groups).

Example:

sql
CopyEdit
SELECT grade, COUNT(*) AS students_count
FROM students
GROUP BY grade
HAVING COUNT(*) > 5;

This shows only grades where more than 5 students exist.

Complete Example Table


students table:

id name age grade


1 John 15 A
2 Sarah 16 B
3 Alex 15 A
4 Emma 14 A

Query Examples:

sql
CopyEdit
SELECT COUNT(*) FROM students; -- 4
SELECT AVG(age) FROM students; -- 15
SELECT MAX(age) FROM students; -- 16
SELECT MIN(age) FROM students; -- 14

ORDER BY CLAUSE
In SQL, the ORDER BY clause is used to sort the results of a query based on one or more
columns. By default, sorting is done in ascending order (ASC), but you can also sort in
descending order (DESC).

Syntax of ORDER BY
sql
CopyEdit
SELECT column1, column2
FROM table_name
ORDER BY column_name [ASC | DESC];

 ASC = Ascending order (default, from smallest to largest).


 DESC = Descending order (from largest to smallest).
1. Sorting by a Single Column
Example:

sql
CopyEdit
SELECT * FROM students
ORDER BY age ASC;

This will sort students from the youngest to oldest.

2. Sorting by Multiple Columns


Example:

sql
CopyEdit
SELECT * FROM students
ORDER BY grade DESC, age ASC;

 First, it sorts by grade in descending order.


 If two students have the same grade, they are sorted by age in ascending order.

3. Sorting by Column Position


Instead of column names, you can sort by the column index in the SELECT statement.

sql
CopyEdit
SELECT name, age, grade
FROM students
ORDER BY 2 DESC; -- Sort by the 2nd column (age) in descending order

(Not recommended in production because column order may change.)

4. Sorting with Expressions


You can also sort by calculated values:

sql
CopyEdit
SELECT name, age + 5 AS future_age
FROM students
ORDER BY future_age DESC;
5. ORDER BY with LIMIT
Often used together to get top or bottom results:

sql
CopyEdit
SELECT * FROM students
ORDER BY age DESC
LIMIT 3;

This returns the 3 oldest students.

6. ORDER BY with NULL values


 In MySQL, NULL values are considered smallest when sorting in ascending order.
 Example:

sql
CopyEdit
SELECT * FROM students
ORDER BY grade ASC;

Rows with NULL grade will appear first.

Example Table
students table:

id name age grade


1 John 15 A
2 Sarah 16 B
3 Alex 15 A
4 Emma 14 A

Query:

sql
CopyEdit
SELECT name, age, grade
FROM students
ORDER BY grade DESC, age ASC;

Result:
name age grade
Sarah 16 B
Emma 14 A
Alex 15 A
John 15 A

GROUP BY CLAUSE
The GROUP BY clause in SQL is used to group rows that have the same values in one or more
columns into summary rows. It is often used with aggregate functions (like COUNT(),
SUM(), AVG(), etc.) to perform operations on each group of data.

Key Points about GROUP BY


1. Groups rows that have the same values in specified columns.
2. Usually combined with aggregate functions to summarize data.
3. WHERE filters rows before grouping, while HAVING filters groups after grouping.
4. You can group by one or multiple columns.

Syntax of GROUP BY
sql
CopyEdit
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;

Example Table: students


id name age grade city
1 John 15 A Delhi
2 Sarah 16 B Mumbai
id name age grade city
3 Alex 15 A Delhi
4 Emma 14 A Bangalore
5 Mike 16 B Mumbai

Examples of GROUP BY
1. Count Students by Grade
sql
CopyEdit
SELECT grade, COUNT(*) AS student_count
FROM students
GROUP BY grade;

Output:

grade student_count
A 3
B 2

2. Average Age by Grade


sql
CopyEdit
SELECT grade, AVG(age) AS average_age
FROM students
GROUP BY grade;

Output:

grade average_age
A 14.67
B 16

3. Grouping by Multiple Columns


sql
CopyEdit
SELECT city, grade, COUNT(*) AS students
FROM students
GROUP BY city, grade;

Output:

city grade students


Delhi A 2
city grade students
Mumbai B 2
Bangalore A 1

GROUP BY with HAVING


 HAVING filters the result of groups, similar to how WHERE filters rows.

Example: Show grades that have more than 2 students:

sql
CopyEdit
SELECT grade, COUNT(*) AS student_count
FROM students
GROUP BY grade
HAVING COUNT(*) > 2;

Output:

grade student_count
A 3

4. Using GROUP BY with SUM()


sql
CopyEdit
SELECT grade, SUM(age) AS total_age
FROM students
GROUP BY grade;

Output:

grade total_age
A 44
B 32

Key Difference Between WHERE and


HAVING
 WHERE → Filters rows before grouping.
 HAVING → Filters the grouped result.

Example:
sql
CopyEdit
SELECT grade, COUNT(*) AS student_count
FROM students
WHERE city = 'Delhi'
GROUP BY grade
HAVING COUNT(*) > 1;

This counts students from Delhi, grouped by grade, but shows only groups with more than 1
student.

GENERAL ORDER OF CLAUSES


ChatGPT said:

In SQL, a query follows a specific order of execution for clauses, even though we write
them in a different order. Understanding this order is crucial because some clauses depend on
the output of others.

General Order of SQL Clauses (Logical


Execution Order)
When you write:

sql
CopyEdit
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING condition
ORDER BY column1
LIMIT number;

The logical execution order is actually:

1. FROM – Selects the table(s) to retrieve data from.


2. WHERE – Filters rows (row-level filtering).
3. GROUP BY – Groups the filtered rows.
4. HAVING – Filters groups (group-level filtering).
5. SELECT – Chooses the columns/expressions to display.
6. ORDER BY – Sorts the results.
7. LIMIT (or OFFSET) – Limits the number of rows in the output.
Example Table
students

id name age grade


1 John 15 A
2 Sarah 16 B
3 Alex 15 A
4 Emma 14 A
5 Mike 16 B

Example Query
sql
CopyEdit
SELECT grade, COUNT(*) AS student_count
FROM students
WHERE age >= 15
GROUP BY grade
HAVING COUNT(*) > 1
ORDER BY student_count DESC
LIMIT 1;

How SQL Executes This Step-by-Step:

1. FROM students → Take all rows from the students table.


2. WHERE age >= 15 → Filter rows: keep only rows where age is 15 or more.
3. GROUP BY grade → Group remaining rows by grade (A or B).
4. HAVING COUNT(*) > 1 → Only keep groups with more than 1 student.
5. SELECT grade, COUNT(*) AS student_count → Select the grade and count of
students.
6. ORDER BY student_count DESC → Sort the results by student_count (highest
first).
7. LIMIT 1 → Show only the top 1 result.

General Writing Order vs Execution Order


 We write:
SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
 SQL executes:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
UPDATE
What is happening?

You ran this query:

sql
CopyEdit
UPDATE student SET marks = 90 WHERE name = 'anil';

MySQL gave this error:

pgsql
CopyEdit
Error Code: 1175. You are using safe update mode and you tried to update a
table without a WHERE that uses a KEY column.

Why?

 MySQL "safe update mode" prevents accidental changes to many rows.


 It requires that your WHERE clause must use a key column (like a primary key, usually
an id column).
 name is not a key column, so MySQL refuses the update.

How to fix it quickly?

Option 1: Run these two commands

sql
CopyEdit
SET SQL_SAFE_UPDATES = 0; -- Turn off safe mode for this session

UPDATE student
SET marks = 90
WHERE name = 'anil';

SET SQL_SAFE_UPDATES = 1; -- (Optional) Turn safe mode back on

Option 2: Use the primary key (Recommended)

If your table has a primary key like id, do this:

sql
CopyEdit
UPDATE student
SET marks = 90
WHERE id = 3;
(This is safer, because id uniquely identifies one row.)

Why this matters?

If you forget the WHERE condition or use a non-unique column, MySQL might update all
rows.
Safe mode is just a guard against this.

In SQL, UPDATE and DELETE are Data Manipulation Language (DML) commands used to
modify or remove records in a table.

1. UPDATE Command
The UPDATE statement is used to modify existing records in a table.

Syntax of UPDATE
sql
CopyEdit
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

 SET: Specifies the columns and their new values.


 WHERE: Determines which rows will be updated.
o Important: Without WHERE, all rows will be updated.

Example: Update a Student’s Age


sql
CopyEdit
UPDATE students
SET age = 17
WHERE name = 'John';

This updates the age of student "John" to 17.

Example: Update Multiple Columns


sql
CopyEdit
UPDATE students
SET age = 17, grade = 'B'
WHERE name = 'Alex';

Update All Rows (No WHERE Clause)


sql
CopyEdit
UPDATE students
SET grade = 'C';

This changes all students' grades to C.

2. DELETE Command
The DELETE statement is used to remove rows from a table.

Syntax of DELETE
sql
CopyEdit
DELETE FROM table_name
WHERE condition;

 WHERE clause determines which rows will be deleted.


 If you omit WHERE, all rows will be deleted.

Example: Delete a Student


sql
CopyEdit
DELETE FROM students
WHERE name = 'Emma';

This removes the record where name is Emma.

Delete All Rows (Truncate vs Delete)


sql
CopyEdit
DELETE FROM students;

This deletes all records but keeps the table structure.

For faster deletion of all rows:

sql
CopyEdit
TRUNCATE TABLE students;

 TRUNCATE is faster than DELETE but cannot be rolled back (in most databases).

Key Difference Between UPDATE and


DELETE
Feature UPDATE DELETE
Action Modifies existing data Removes existing rows
SET Clause Required Not used
WHERE Optional (updates all rows if omitted) Optional (deletes all rows if omitted)
Rollback Can be rolled back Can be rolled back (unless TRUNCATE)

Examples for Practice


Assume the students table:

id name age grade


1 John 15 A
2 Sarah 16 B
3 Alex 15 A

1. Update Sarah’s grade to A:

sql
CopyEdit
UPDATE students SET grade = 'A' WHERE name = 'Sarah';

2. Delete all students with grade B:

sql
CopyEdit
DELETE FROM students WHERE grade = 'B';
DELETE
ChatGPT said:

The DELETE command in SQL is used to remove rows (records) from a table. It is part of
the Data Manipulation Language (DML).

Syntax of DELETE
sql
CopyEdit
DELETE FROM table_name
WHERE condition;

Important Notes:

 The WHERE clause is used to specify which rows should be deleted.


 If you omit WHERE, all rows in the table will be deleted (be careful!).
 The table structure remains intact; only the data is removed.

Examples of DELETE
1. Delete a Single Row
sql
CopyEdit
DELETE FROM students
WHERE name = 'John';

This deletes the record of student John.

2. Delete Based on a Condition


sql
CopyEdit
DELETE FROM students
WHERE age < 15;

This deletes all students who are younger than 15.

3. Delete All Rows (No WHERE Clause)


sql
CopyEdit
DELETE FROM students;

This deletes all rows from the students table but keeps the table structure.

DELETE vs TRUNCATE
 DELETE FROM table; – Deletes all rows one by one and can be rolled back (if
transaction is active).
 TRUNCATE TABLE table; – Deletes all rows instantly but cannot be rolled back in
most databases because it resets the table.

Example Table
students

id name age grade


1 John 15 A
2 Sarah 16 B
3 Alex 15 A

Query:

sql
CopyEdit
DELETE FROM students WHERE grade = 'B';

Result Table:

id name age grade


1 John 15 A
3 Alex 15 A

DELETE with JOIN


You can also delete rows using JOIN:

sql
CopyEdit
DELETE students
FROM students
JOIN classes ON students.id = classes.student_id
WHERE classes.class_name = 'Math';

This deletes students who are in the Math class.

CASCADING THE FOREIGN KEYS


Cascading Foreign Keys are a feature in SQL that allow automatic actions (such as DELETE
or UPDATE) on rows in child tables when related rows in the parent table are updated or
deleted. This ensures referential integrity between tables in a relational database.

What Are Cascading Foreign Keys?


A foreign key is a column (or set of columns) in one table that refers to the primary key in
another table. By using the ON DELETE or ON UPDATE clauses, we can define what happens to
the child table when changes occur in the parent table.

Types of Cascading Actions


When defining a foreign key, you can specify the following actions:

1. ON DELETE CASCADE – When a row in the parent table is deleted, all matching
rows in the child table are automatically deleted.
2. ON UPDATE CASCADE – When the primary key of a row in the parent table is
updated, the foreign key in the child table is automatically updated.
3. ON DELETE SET NULL – When a row in the parent table is deleted, the foreign
key in the child table is set to NULL (must allow NULL values).
4. ON UPDATE SET NULL – When a parent key is updated, the child’s foreign key is
set to NULL.
5. ON DELETE RESTRICT – Prevents deleting a parent row if child rows exist
(default behavior in many databases).
6. ON DELETE NO ACTION – Similar to RESTRICT, no change occurs.

Syntax of a Foreign Key with Cascade


sql
CopyEdit
CREATE TABLE child_table (
id INT PRIMARY KEY,
parent_id INT,
FOREIGN KEY (parent_id)
REFERENCES parent_table(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);

Example
Parent Table: departments
sql
CopyEdit
CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);

Child Table: employees


sql
CopyEdit
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);

Scenario 1: ON DELETE CASCADE

If we delete a department:

sql
CopyEdit
DELETE FROM departments WHERE dept_id = 1;

→ All employees in that department (dept_id = 1) will also be deleted automatically from
employees.

Scenario 2: ON UPDATE CASCADE

If we update a department ID:

sql
CopyEdit
UPDATE departments
SET dept_id = 10
WHERE dept_id = 1;

→ All employees with dept_id = 1 will have their dept_id automatically updated to 10.

Why Use Cascading Foreign Keys?


 Maintains data integrity automatically.
 Reduces the need for multiple manual DELETE or UPDATE queries.
 Ensures that no orphaned records exist in child tables.

When NOT to Use CASCADE


 When you want to manually control deletions or updates.
 When automatic deletions may cause accidental large-scale data loss.

ChatGPT said:

The error message you're seeing:

pgsql
CopyEdit
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (`college`.`teacher`, CONSTRAINT `teacher_ibfk_1` FOREIGN
KEY (`dept_id`) REFERENCES `dept` (`id`) ON DELETE CASCADE ON UPDATE
CASCADE)

means that you're trying to update the dept_id column in the teacher table to 1, but there is
no corresponding record in the dept table where id = 1.

Why this happens:

 A foreign key constraint ensures that the value of teacher.dept_id must exist in
dept.id.
 When you try UPDATE teacher SET dept_id = 1;, MySQL checks if 1 exists in
dept.id.
 If it doesn’t exist, the update fails with Error 1452.
ALTER COMMAND
ChatGPT said:

The ALTER command in SQL is used to modify the structure of an existing table or
database object (like adding/removing columns, changing data types, renaming columns,
etc.) without deleting the table data.

General Syntax
sql
CopyEdit
ALTER TABLE table_name
action;

Common Uses of ALTER TABLE


1. Add a New Column
sql
CopyEdit
ALTER TABLE students
ADD email VARCHAR(100);

This adds a new column email to the students table.

2. Add Multiple Columns


sql
CopyEdit
ALTER TABLE students
ADD (phone VARCHAR(15), address VARCHAR(255));

3. Modify an Existing Column


To change the data type or size of a column:

sql
CopyEdit
ALTER TABLE students
MODIFY age INT;

(In some databases like SQL Server, use ALTER COLUMN instead of MODIFY.)
4. Rename a Column
 MySQL:

sql
CopyEdit
ALTER TABLE students
CHANGE name student_name VARCHAR(100);

CHANGE old_column new_column new_data_type

 SQL Server:

sql
CopyEdit
EXEC sp_rename 'students.name', 'student_name', 'COLUMN';

5. Drop a Column
sql
CopyEdit
ALTER TABLE students
DROP COLUMN address;

This removes the address column from the students table.

6. Rename the Table


sql
CopyEdit
ALTER TABLE students
RENAME TO learners;

7. Add a Constraint
sql
CopyEdit
ALTER TABLE students
ADD CONSTRAINT unique_email UNIQUE (email);

8. Drop a Constraint
sql
CopyEdit
ALTER TABLE students
DROP CONSTRAINT unique_email;

(The constraint name must match what was given during creation.)

Example
Consider the students table:

sql
CopyEdit
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);

Add a column:
sql
CopyEdit
ALTER TABLE students ADD grade VARCHAR(5);

Modify column type:


sql
CopyEdit
ALTER TABLE students MODIFY name VARCHAR(150);

Rename column:
sql
CopyEdit
ALTER TABLE students CHANGE name student_name VARCHAR(150);

Key Points
 ALTER TABLE does not delete existing data.
 Be careful when using DROP COLUMN, as data in that column is lost.
 Renaming or modifying columns may affect existing queries, views, or stored
procedures.

TRUNCATE  VIMP
The TRUNCATE command in SQL is used to remove all rows from a table, but unlike DELETE,
it is a Data Definition Language (DDL) command and works differently.

What is TRUNCATE?
 TRUNCATE removes all records from a table instantly.
 It does not log individual row deletions like DELETE, making it much faster for
large tables.
 After truncation, the table structure (columns, constraints, etc.) remains intact.
 In most databases, the auto-increment counter (e.g., primary key IDs) is reset to 1.

Syntax of TRUNCATE
sql
CopyEdit
TRUNCATE TABLE table_name;

Key Characteristics of TRUNCATE


1. Faster than DELETE – It deallocates the data pages rather than deleting rows one by
one.
2. No WHERE clause – It always deletes all rows (unlike DELETE).
3. Resets identity (auto-increment) – In MySQL and some other RDBMS.
4. Cannot be rolled back (in many systems) – Unless executed in a transaction-
supported database.
5. Does not fire triggers – Unlike DELETE, which can invoke triggers.

TRUNCATE vs DELETE vs DROP


Feature TRUNCATE DELETE DROP
Type DDL DML DDL
Selected rows (WHERE) or all Entire table structure +
Removes All rows
rows data
Speed Very fast Slower (logs row by row) Fast (drops table)
WHERE? Not allowed Allowed Not applicable
Usually not
Rollback? Possible (with transactions) Not possible
possible
Resets ID? Yes No Not applicable
Example: Using TRUNCATE
Original Table: students

id name age grade


1 John 15 A
2 Sarah 16 B
3 Alex 15 A

Truncate Command:
sql
CopyEdit
TRUNCATE TABLE students;

After Execution:

The table is empty, but the structure remains:

id name age grade


(No rows)

When to Use TRUNCATE?


 When you want to quickly clear all data from a table.
 When you don’t need to log row deletions for rollback.
 When you don’t need to use WHERE conditions.

When NOT to Use TRUNCATE?


 When you want to delete only specific rows (use DELETE).
 When foreign key constraints exist (TRUNCATE may not work unless you disable
foreign key checks).
 When you want to trigger actions (TRUNCATE doesn’t fire DELETE triggers).

Example with AUTO_INCREMENT Reset


sql
CopyEdit
CREATE TABLE test (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);

INSERT INTO test (name) VALUES ('Alice'), ('Bob');

 Now IDs are 1 and 2.


 After TRUNCATE TABLE test;
→ If we insert a new record, its ID will start again from 1.

ROLLBACK IN THE MYSQL

Assume we have two tables, students and courses.

students table:

student_id name
1 John
2 Sarah
3 Alex

courses table:

course_id student_id course_name


101 1 Math
102 2 Science
103 1 History

In SQL, joins are used to combine records from two or more tables based on a related column
between them. Joins are essential in relational databases, as they allow you to retrieve data
that is spread across different tables.

Types of Joins in SQL


1. INNER JOIN
 Definition: Returns only the rows where there is a match in both tables.
 Usage: Used when you only want rows that have matching values in both tables.
Syntax of INNER JOIN:
sql
CopyEdit
SELECT column1, column2
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Example:

Assume we have two tables, students and courses.

students table:

student_id name
1 John
2 Sarah
3 Alex

courses table:

course_id student_id course_name


101 1 Math
102 2 Science
103 1 History

Query:

sql
CopyEdit
SELECT students.name, courses.course_name
FROM students
INNER JOIN courses
ON students.student_id = courses.student_id;

Result:

name course_name
John Math
John History
Sarah Science

2. LEFT JOIN (or LEFT OUTER JOIN)


 Definition: Returns all rows from the left table and the matched rows from the right
table. If no match is found, NULL values are returned for columns from the right table.
 Usage: Used when you want all records from the left table and the matching records
from the right table.
Syntax of LEFT JOIN:
sql
CopyEdit
SELECT column1, column2
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;

Example:

Query:

sql
CopyEdit
SELECT students.name, courses.course_name
FROM students
LEFT JOIN courses
ON students.student_id = courses.student_id;

Result:

name course_name
John Math
John History
Sarah Science
Alex NULL

Explanation:

 Alex does not have any course, so the course_name is NULL.

3. RIGHT JOIN (or RIGHT OUTER JOIN)


 Definition: Returns all rows from the right table and the matched rows from the left
table. If no match is found, NULL values are returned for columns from the left table.
 Usage: Similar to LEFT JOIN, but it returns all rows from the right table instead.

Syntax of RIGHT JOIN:


sql
CopyEdit
SELECT column1, column2
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

Example:
Query:

sql
CopyEdit
SELECT students.name, courses.course_name
FROM students
RIGHT JOIN courses
ON students.student_id = courses.student_id;

Result:

name course_name
John Math
John History
Sarah Science
NULL History

4. FULL OUTER JOIN


 Definition: Returns all rows when there is a match in either the left or right table. If
no match is found, NULL values are returned for columns of the table without a match.
 Usage: Useful when you need to combine the result of both LEFT JOIN and RIGHT
JOIN.

Syntax of FULL OUTER JOIN:


sql
CopyEdit
SELECT column1, column2
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;

Note: Not supported in all databases (e.g., MySQL doesn't natively support FULL OUTER
JOIN, but can be simulated).

Example:

Query:

sql
CopyEdit
SELECT students.name, courses.course_name
FROM students
FULL OUTER JOIN courses
ON students.student_id = courses.student_id;

Result:
name course_name
John Math
John History
Sarah Science
Alex NULL
NULL History

5. CROSS JOIN
 Definition: Returns the Cartesian product of two tables. It joins each row from the
first table with every row from the second table.
 Usage: Useful for generating combinations of rows, like pairing every product with
every customer.

Syntax of CROSS JOIN:


sql
CopyEdit
SELECT column1, column2
FROM table1
CROSS JOIN table2;

Example:

Query:

sql
CopyEdit
SELECT students.name, courses.course_name
FROM students
CROSS JOIN courses;

Result:

name course_name
John Math
John Science
John History
Sarah Math
Sarah Science
Sarah History
Alex Math
Alex Science
Alex History

Comparison of Joins
Join Type Returns When to Use
When you want rows with
INNER JOIN Only matching rows from both tables
matching values
All rows from the left table + matching When you need all rows from
LEFT JOIN
from the right the left table
All rows from the right table + matching When you need all rows from
RIGHT JOIN
from the left the right table
FULL OUTER All rows from both tables, with NULL for When you need all rows from
JOIN non-matching rows both tables
Cartesian product (all combinations of When you need all
CROSS JOIN
rows) combinations

Would You Like?


Would you like me to create 5 practice exercises for you to test your understanding of
different joins? This will include examples with INNER, LEFT, RIGHT, FULL OUTER,
and CROSS joins!

Ask ChatGPT

Self join
A self join is a special type of join where a table is joined with itself. This can be useful
when you need to compare rows within the same table. Typically, this is done using aliases to
differentiate the two instances of the table.

Why Use a Self Join?

 It allows you to relate rows within the same table.


 Commonly used for hierarchical data, such as employees and managers, or when one
row needs to reference another row in the same table.

Syntax of Self Join


sql
CopyEdit
SELECT A.column1, B.column2
FROM table_name A, table_name B
WHERE A.common_column = B.common_column;

 A and B are aliases for the same table.


 You use different aliases to refer to the same table to avoid confusion and maintain
clarity.

Example: Employee and Manager


Consider an employees table, where each employee has a manager who is also an employee.

employees table:

emp_id emp_name manager_id


1 John NULL
2 Sarah 1
3 Alex 1
4 Emma 2

In this table:

 John has no manager (manager_id = NULL).


 Sarah and Alex report to John (manager_id = 1).
 Emma reports to Sarah (manager_id = 2).

Self Join Query to Find Employees and Their Managers


sql
CopyEdit
SELECT A.emp_name AS Employee, B.emp_name AS Manager
FROM employees A, employees B
WHERE A.manager_id = B.emp_id;

Explanation:

 A and B are aliases representing two different instances of the employees table.
 The condition A.manager_id = B.emp_id means that the manager_id of an
employee in A must match the emp_id of an employee in B.

Result:

Employee Manager
Sarah John
Alex John
Emma Sarah

Self Join with Multiple Columns

You can also select multiple columns in the self join:

sql
CopyEdit
SELECT A.emp_name AS Employee, A.emp_id AS Emp_ID, B.emp_name AS Manager,
B.emp_id AS Manager_ID
FROM employees A, employees B
WHERE A.manager_id = B.emp_id;

Result:

Employee Emp_ID Manager Manager_ID


Sarah 2 John 1
Alex 3 John 1
Emma 4 Sarah 2

Self Join in a Hierarchical Structure


Self joins are particularly useful in hierarchical structures, like a company's organizational
chart, where employees report to managers who are also employees.

Example: Finding All Employees Reporting to a Manager

To find all employees reporting to John (emp_id = 1):

sql
CopyEdit
SELECT A.emp_name AS Employee
FROM employees A, employees B
WHERE A.manager_id = B.emp_id
AND B.emp_name = 'John';

Result:

Employee
Sarah
Alex

Key Points About Self Joins

 A self join is not a special SQL join type. It’s just a regular join applied to the same
table.
 You must use aliases to differentiate between the two instances of the table.
 Self joins are very useful for comparing rows within the same table, particularly for
hierarchical or relational data.

Would You Like?


Would you like me to create 5 practice problems with solutions on self joins, so you can
better understand how to use them in various scenarios like organizational hierarchies or
product relationships?

UNION
The UNION operator in SQL is used to combine the results of two or more SELECT
statements into a single result set, eliminating duplicates by default. It's often used when you
want to combine data from multiple tables that have the same structure (same number of
columns and compatible data types).

Key Characteristics of UNION:


 Removes duplicates by default.
 Combines results from multiple SELECT queries.
 Requires that the number of columns and their data types match in each SELECT
statement.
 The columns don't have to have the same names, but their data types must be
compatible.
Syntax of UNION
sql
CopyEdit
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;

 The number and data types of the columns in both SELECT statements should be the
same.
 UNION combines the result sets and removes duplicates by default.

Example: Combining Results from Two Tables


Consider the following two tables:

students table:

id name age
1 John 15
2 Sarah 16
3 Alex 15

teachers table:

id name age
1 Emma 30
2 Mike 35
3 Sarah 28

Query to Combine Both:


sql
CopyEdit
SELECT name, age FROM students
UNION
SELECT name, age FROM teachers;

Result:

name age
John 15
Sarah 16
name age
Alex 15
Emma 30
Mike 35
Sarah 28

 The result set includes unique records from both tables, removing duplicate values
(e.g., if both tables had a Sarah).

UNION ALL: Including Duplicates


The UNION ALL operator includes all duplicates and does not remove any rows from the
result set. This is used when you want to combine results from multiple queries but preserve
duplicates.

Example of UNION ALL:


sql
CopyEdit
SELECT name, age FROM students
UNION ALL
SELECT name, age FROM teachers;

Result:

name age
John 15
Sarah 16
Alex 15
Emma 30
Mike 35
Sarah 28
Sarah 28

 In this case, the second occurrence of Sarah in the teachers table is not removed
because we used UNION ALL.

Important Points:
1. Matching Columns: The number of columns in each SELECT must be the same and
the data types should be compatible.
o For example, you can't combine a VARCHAR column with an INT column unless
the data types are convertible.
2. Column Names: The column names in the final result set will be taken from the first
SELECT statement.
3. Sorting Results: You can use ORDER BY at the end of the entire query to sort the
combined result set.

sql
CopyEdit
SELECT name, age FROM students
UNION
SELECT name, age FROM teachers
ORDER BY age DESC;

Using UNION for Hierarchical Data


Consider two tables, employees and contractors, both containing employee data but with
slightly different structures:

employees table:

emp_id emp_name department


1 John IT
2 Sarah HR

contractors table:

cont_id cont_name department


1 Mike IT
2 Emma Marketing

Query to Combine Both:


sql
CopyEdit
SELECT emp_name, department FROM employees
UNION
SELECT cont_name, department FROM contractors;

Result:

emp_name department
John IT
Sarah HR
Mike IT
Emma Marketing
Difference Between UNION and UNION
ALL
Feature UNION UNION ALL
Duplicates Removes duplicate rows Keeps all rows, including duplicates
Performance Slower (due to removing duplicates) Faster (no duplicate removal)
Use Case Use when you need unique records Use when duplicates are acceptable

SUBQUERY
ChatGPT said:

A subquery (also known as a nested query or inner query) is a SQL query inside another
query. Subqueries are used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.

🔹 Types of Subqueries
Subqueries can appear in different clauses:

1. In the WHERE clause


2. In the FROM clause
3. In the SELECT clause

They are also classified by how they return values:

 Scalar Subquery: Returns a single value (one row, one column)


 Row Subquery: Returns a single row
 Column Subquery: Returns a single column with multiple rows
 Table Subquery: Returns a full table (used in FROM clause)

🔹 1. Subquery in WHERE Clause


Used to filter rows based on results from another query.
🔸 Example: Find employees who earn more than the average salary
sql
CopyEdit
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

 The subquery (SELECT AVG(salary) FROM employees) returns the average salary.
 The main query then finds employees who earn more than that.

🔹 2. Subquery in FROM Clause (Derived Table)


Used to treat the result of a subquery as a temporary table.

🔸 Example: Get departments and their average salaries


sql
CopyEdit
SELECT department, avg_salary
FROM (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
) AS dept_avg;

 The inner query calculates average salaries by department.


 The outer query selects from that derived table.

🔹 3. Subquery in SELECT Clause


Used to return a scalar value for each row in the result set.

🔸 Example: Show each employee and the average salary of their department
sql
CopyEdit
SELECT name,
department,
(SELECT AVG(salary)
FROM employees e2
WHERE e2.department = e1.department) AS dept_avg
FROM employees e1;

 For each employee, the subquery calculates the average salary of their department.
🔹 4. Subquery with IN / NOT IN
Used to filter rows based on membership in a list returned by a subquery.

🔸 Example: Find employees in departments that have managers


sql
CopyEdit
SELECT name
FROM employees
WHERE department IN (
SELECT department
FROM employees
WHERE role = 'Manager'
);

🔹 5. Correlated Subqueries
A correlated subquery depends on a value from the outer query. It is evaluated once per
row of the outer query.

🔸 Example: Find employees who earn more than the average salary of their
department
sql
CopyEdit
SELECT name, salary, department
FROM employees e1
WHERE salary > (
SELECT AVG(salary)
FROM employees e2
WHERE e1.department = e2.department
);

 This subquery is correlated, because it uses e1.department, which comes from the
outer query.

🔹 6. EXISTS / NOT EXISTS with Subquery


Checks whether the subquery returns any rows.

🔸 Example: Find departments that have at least one employee


sql
CopyEdit
SELECT DISTINCT department
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
WHERE e.department = d.department
);

✅ Subquery vs JOIN
Feature Subquery JOIN
Readability More readable for filtering More readable for combining rows
Performance Can be slower (especially correlated) Usually faster in large datasets
Use case Filtering, checking conditions Combining data from multiple tables

⚠️Subquery Limitations
 Some databases limit where subqueries can be used (e.g., not in LIMIT).
 Correlated subqueries can be slower — avoid if a join can do the job.

🧠 Summary
Subquery Type Use Case Returns
In WHERE Filter based on a condition Scalar, row, or column
In FROM Temporary table (derived table) Table
In SELECT Return a calculated value per row Scalar
IN, NOT IN Membership check List
EXISTS, NOT EXISTS Existence check Boolean (true/false)
Correlated Row-specific filtering Depends on outer query

VIEWS
:

🔍 SQL VIEWS – Explained in Detail

A VIEW in SQL is a virtual table based on the result of a SELECT query. It does not store
the data itself, but presents data from one or more tables in a structured and readable way.
🔷 What is a View?
 A view is like a window to a part of your database.
 It simplifies complex queries by hiding joins, filters, or calculated fields.
 You can select from a view just like you would from a regular table.

🔷 Syntax to Create a View


sql
CopyEdit
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

🔷 Example: Basic View


Suppose you have a students table:

id name age grade


1 John 15 A
2 Sarah 16 B
3 Mike 15 A

Create a view showing only Grade A students:


sql
CopyEdit
CREATE VIEW top_students AS
SELECT name, grade
FROM students
WHERE grade = 'A';

Querying the view:


sql
CopyEdit
SELECT * FROM top_students;

Result:

name grade
John A
Mike A
🔷 Why Use Views?
Benefit Description
🔹 Simplicity Hide complex joins and calculations
🔹 Security Restrict access to specific columns or rows
🔹 Reusability Write logic once, use it many times
🔹 Maintainability Change in view affects all referencing queries

🔷 Updating Data Through a View


If the view is based on a single table without aggregations, you can update the base table
through the view.

sql
CopyEdit
UPDATE top_students
SET grade = 'B'
WHERE name = 'John';

This updates the original students table, not the view itself.

🔸 But you cannot update views if:

 The view contains JOINs


 The view has aggregations (GROUP BY, SUM, etc.)
 The view uses DISTINCT or UNION

🔷 ALTER or DROP a View


Modify a view:
sql
CopyEdit
CREATE OR REPLACE VIEW top_students AS
SELECT name, grade, age
FROM students
WHERE grade = 'A';

Drop a view:
sql
CopyEdit
DROP VIEW top_students;

🔷 View with Joins Example


Suppose you have two tables:

employees

emp_id name dept_id


1 John 101
2 Sarah 102

departments

dept_id dept_name
101 IT
102 HR

Create a view showing employee names with their department names:


sql
CopyEdit
CREATE VIEW employee_departments AS
SELECT e.name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id;

🔷 Materialized Views (Note)


 Standard views are virtual and always reflect live data.
 Some systems (e.g., Oracle, PostgreSQL) support materialized views, which store
the results physically and can be refreshed periodically for performance.

🔷 Summary
Feature View Table
Stores Data? ❌ No (virtual) ✅ Yes
Updatable? ✅ Sometimes ✅ Always
Can Have Joins? ✅ Yes ✅ Yes
Purpose Simplify, secure, abstract Store and manage actual data

Why are views used in SQL?


Answer:

Views in SQL are used to simplify complex queries, improve security, and make data easier
to manage.

A view is like a virtual table based on a SQL query. It doesn't store data itself but shows data
from one or more tables.

We use views to:

 Reuse complex queries without rewriting them


 Hide sensitive columns from users (like salary)
 Make code easier to understand and maintain
 Provide a layer of abstraction so that underlying table changes don’t break
user queries

Views help organize and secure the database without duplicating data.

You might also like