Mysql
Mysql
Choosing the right data type is important for performance and storage.
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)
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
MySQL does not have a real BOOLEAN type. It is an alias for TINYINT(1) where 0 =
FALSE and 1 = TRUE.
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:
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;
-- 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;
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
);
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)
);
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
);
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:
Example:
sql
CopyEdit
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT
);
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
);
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)
);
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)
);
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'
);
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)
);
3. Logical Operators
Used for combining conditions in queries.
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');
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
sql
CopyEdit
SELECT * FROM students WHERE email IS NULL;
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);
sql
CopyEdit
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM students;
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.
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;
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;
4. MIN()
Purpose: Returns the smallest value from a column.
Usage Example:
sql
CopyEdit
SELECT MIN(age) AS youngest FROM students;
5. MAX()
Purpose: Returns the largest value from a column.
Usage Example:
sql
CopyEdit
SELECT MAX(age) AS oldest FROM students;
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;
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.).
Example:
sql
CopyEdit
SELECT grade, COUNT(*) AS students_count
FROM students
GROUP BY grade
HAVING COUNT(*) > 5;
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];
sql
CopyEdit
SELECT * FROM students
ORDER BY age ASC;
sql
CopyEdit
SELECT * FROM students
ORDER BY grade DESC, age ASC;
sql
CopyEdit
SELECT name, age, grade
FROM students
ORDER BY 2 DESC; -- Sort by the 2nd column (age) in descending order
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;
sql
CopyEdit
SELECT * FROM students
ORDER BY grade ASC;
Example Table
students table:
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.
Syntax of GROUP BY
sql
CopyEdit
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;
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
Output:
grade average_age
A 14.67
B 16
Output:
sql
CopyEdit
SELECT grade, COUNT(*) AS student_count
FROM students
GROUP BY grade
HAVING COUNT(*) > 2;
Output:
grade student_count
A 3
Output:
grade total_age
A 44
B 32
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.
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.
sql
CopyEdit
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING condition
ORDER BY column1
LIMIT number;
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;
sql
CopyEdit
UPDATE student SET marks = 90 WHERE name = 'anil';
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?
sql
CopyEdit
SET SQL_SAFE_UPDATES = 0; -- Turn off safe mode for this session
UPDATE student
SET marks = 90
WHERE name = 'anil';
sql
CopyEdit
UPDATE student
SET marks = 90
WHERE id = 3;
(This is safer, because id uniquely identifies one row.)
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;
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;
sql
CopyEdit
TRUNCATE TABLE students;
TRUNCATE is faster than DELETE but cannot be rolled back (in most databases).
sql
CopyEdit
UPDATE students SET grade = 'A' WHERE name = 'Sarah';
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:
Examples of DELETE
1. Delete a Single Row
sql
CopyEdit
DELETE FROM students
WHERE name = 'John';
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
Query:
sql
CopyEdit
DELETE FROM students WHERE grade = 'B';
Result Table:
sql
CopyEdit
DELETE students
FROM students
JOIN classes ON students.id = classes.student_id
WHERE classes.class_name = 'Math';
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.
Example
Parent Table: departments
sql
CopyEdit
CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);
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.
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.
ChatGPT said:
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.
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;
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);
SQL Server:
sql
CopyEdit
EXEC sp_rename 'students.name', 'student_name', 'COLUMN';
5. Drop a Column
sql
CopyEdit
ALTER TABLE students
DROP COLUMN address;
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);
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;
Truncate Command:
sql
CopyEdit
TRUNCATE TABLE students;
After Execution:
students table:
student_id name
1 John
2 Sarah
3 Alex
courses table:
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.
Example:
students table:
student_id name
1 John
2 Sarah
3 Alex
courses table:
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
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:
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
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.
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
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.
employees table:
In this table:
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
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:
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
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.
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).
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.
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
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).
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;
employees table:
contractors table:
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:
The subquery (SELECT AVG(salary) FROM employees) returns the average salary.
The main query then finds employees who earn more than that.
🔸 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.
🔹 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.
✅ 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
:
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.
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
sql
CopyEdit
UPDATE top_students
SET grade = 'B'
WHERE name = 'John';
This updates the original students table, not the view itself.
Drop a view:
sql
CopyEdit
DROP VIEW top_students;
employees
departments
dept_id dept_name
101 IT
102 HR
🔷 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
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.
Views help organize and secure the database without duplicating data.