Database
A Database is just a place to store information in an
organized way so we can find and use it easily later.
✅ The notebook = Your Database
✅ Each page = A Table
✅ Each row = One students’s info (a record)
✅ Each column = A detail about the student (name, roll_no, class)
Types of Databases
A database is like a place to keep your stuff organized, right?
But there are different kinds of boxes (types)
for keeping that stuff depending on how you want to organize it.
Relational Database (the “Neat Box”)
Tools: MySQL, PostgreSQL
NoSQL Database (the “Flexible Box”)
Tools: MongoDB,Cassandra
Relational Database Management System
✅
✅ Relational = Uses tables (like grids or spreadsheets)
✅ Database = A place to store information
✅ Management System = A tool to organize and control the data
So, an RDBMS is a system that helps us store, organize, and connect data in tables.
SQL (Structured Query Language)
IT is a standard language used to manage and interact with databases.
Types
✅ Data Definition Language (DDL)
✅ Data Manipulation Language (DML)
✅ Data Control Language (DCL)
✅ Transaction Control Language (TCL)
✅ Data Query Language (DQL)
Installation of MySQL Server & Workbench
Windows
Mac
Data Types in SQL
Data Type Description Minimum Value Maximum Value
TINYINT Very small whole number -128 127
TINYINT UNSIGNED Only positive small numbers 0 255
SMALLINT Small whole number -32,768 32,767
SMALLINT UNSIGNED Only positive small numbers 0 65,535
MEDIUMINT Medium-size whole number -8,388,608 8,388,607
MEDIUMINT UNSIGNED Only positive medium numbers 0 16,777,215
INT / INTEGER Standard whole number -2,147,483,648 2,147,483,647
INT UNSIGNED Only positive whole number 0 4,294,967,295
BIGINT Very large whole number -9,223,372,036,854,770,000 9,223,372,036,854,770,000
BIGINT UNSIGNED Only positive large number 0 18,446,744,073,709,500,000
FLOAT Approximate number with decimals ~ -3.4E38 ~ 3.4E38
DOUBLE Bigger, more precise than FLOAT ~ -1.7E308 ~ 1.7E308
DATE Just the date YYYY-MM-DD 22 Apr 2025
TIME Just the time of day HH:MM:SS 14:30:00
DATETIME Date and time together YYYY-MM-DD HH:MM:SS 2025-04-22 14:30:00
YEAR Only the year YYYY 2025
CHAR(n) Fixed-length text Always exactly n chars 'Hi ' (with spaces)
VARCHAR(n) Variable-length text Up to n chars 'Hello'
TEXT Large text No strict limit (varies) Long paragraph
TINYTEXT Very small text Max ~255 characters 'Short msg'
MEDIUMTEXT Medium-sized text Max ~16 million chars Article or blog
LONGTEXT Very large text Max ~4 billion chars Full novel
✅ Data Definition Language (DDL)
it's used to define and manage the structure of your database.
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME
Command What it does Real-World Example
CREATE Makes a new table/database Build a new toy box
ALTER Changes the structure (add/remove column) Add drawer to toy box
DROP Deletes the entire table Smash the toy box
TRUNCATE Empties all data inside the table Throw out all toys, keep the box
RENAME Changes the name of the table Give your toy box a new name
1. CREATE
building a brand-new toy box (a table)
✅ Syntax:
CREATE TABLE Students (
ID INT,
Name VARCHAR(50),
Age INT
);
2. ALTER
you already built a toy box, and now you want to
change somethings.
✅ Syntax:
ALTER TABLE Students ADD Grade VARCHAR(2);
3. DROP
This is like smashing your block tower to the ground
it's gone forever!
✅ Syntax:
DROP TABLE Students;
4. TRUNCATE
it will throw all the toys out but keep the box.
✅ Syntax:
TRUNCATE TABLE Students;
5. RENAME
Giving it a new name
✅ Syntax:
RENAME TABLE Students TO Kids;
✅ Data Manipulation Language (DML)
DML is about playing with the toys inside
adding them, changing them, or taking them out!
1. INSERT – Add new toys
2. UPDATE – Fix or change toys
3. DELETE – Remove a toy
1. INSERT
You got a new toy and want to add it to your toy box.
✅ Syntax:
INSERT INTO ToyBox (ToyID, ToyName, ToyType)
VALUES (1, 'Teddy Bear', 'Stuffed');
You added a toy with:
ID: 1
Name: Teddy Bear
Type: Stuffed
2. UPDATE
Change Something About a Toy
✅ Syntax:
UPDATE ToyBox
SET ToyType = 'Plush'
WHERE ToyID = 1;
You found the toy with ToyID = 1.
You changed its type from "Stuffed" to "Plush".
3. DELETE
Throw a Toy Away
✅ Syntax:
DELETE FROM ToyBox
WHERE ToyID = 1;
You found the toy with ID 1 and took it out of the box.
✅ Data Control Language (DCL)
If DDL was for building your toy box
DML was for playing with the toys inside
then DCL is about giving permission to others:
✅ Who can see your toy box?
✅ Who can add or remove toys?
✅ Who can’t touch anything at all?
It’s like being the Toy Box Boss 👑
1. GRANT – Give someone permission
2. REVOKE – Take that permission away
1. GRANT
Let a Friend Use Your Toy Box
✅ Syntax:
GRANT SELECT, INSERT ON ToyBox TO Sam;
You gave Sam permission to:
SELECT → Look at the toys in your box
INSERT → Add new toys to your box
2. REVOKE
Take Permission Back
✅ Syntax:
REVOKE INSERT ON ToyBox FROM Sam;
You told Sam: “You can no longer add toys,
but He can still look at them.”
Full Toy Box SQL Story
1. You build the toy box → CREATE
2. You add toys → INSERT
3. You peek inside → SELECT
4. You change toys → UPDATE
5. You remove toys → DELETE
6. You let friends play → GRANT
7. You stop them if needed → REVOKE
✅ Transaction Control Language (TCL)
Imagine you're playing with your toy box and doing many things one after another:
Adding toys
Removing some
Changing a few
But you only want to save these changes if everything goes well.
If something goes wrong — like you dropped a toy or broke one — you want to undo everything.
That’s where TCL helps!
COMMIT – Save all your changes
ROLLBACK – Undo your changes
SAVEPOINT – Set a checkpoint to go back to
1.COMMIT
Save Your Work
✅ Example:
INSERT INTO ToyBox VALUES (1, 'Car', 'Vehicle');
INSERT INTO ToyBox VALUES (2, 'Doll', 'Stuffed');
COMMIT;
2.ROLLBACK
Undo Everything
✅ Example:
INSERT INTO ToyBox VALUES (3, 'Robot', 'Electronic');
INSERT INTO ToyBox VALUES (4, 'Ball', 'Outdoor');
ROLLBACK;
3.SAVEPOINT
Set a Checkpoint
✅ Example:
INSERT INTO ToyBox VALUES (5, 'Puzzle', 'Brain');
SAVEPOINT Save1;
INSERT INTO ToyBox VALUES (6, 'Yo-Yo', 'Outdoor');
INSERT INTO ToyBox VALUES (7, 'RC Car', 'Electronic');
ROLLBACK TO Save1;
✅ Data Query Language (DQL)
SELECT - Ask for whats inside the toy box.
Examples: -
SELECT * FROM ToyBox;
SELECT ToyName FROM ToyBox;
SELECT * FROM ToyBox WHERE ToyType = 'Vehicle';
SELECT COUNT(*) FROM ToyBox;
Query Example What it Does
SELECT * FROM ToyBox; Shows all the toys
SELECT ToyName FROM ToyBox; Shows only toy names
WHERE ToyType = 'Vehicle'; Filters only Vehicle toys
ORDER BY ToyName; Sorts toys by name
COUNT(*) Counts total number of toys
GROUP BY ToyType Groups toys by their type
HAVING
The HAVING clause is used to filter groups created by the GROUP BY clause. It's similar to WHERE, but WHERE
filters rows before grouping, while HAVING filters groups after grouping.
SELECT customer, SUM(amount) AS total_spent
FROM sales_data
GROUP BY customer
HAVING SUM(amount) > 30;
SQL Functions
Aggregate Functions
Function Description
SUM() Adds up all the values
AVG() Calculates average
COUNT() Counts the number of values
MAX() Finds the maximum value
MIN() Finds the minimum value
Scalar Functions
Function Description
UPPER(str) Converts to uppercase
LOWER(str) Converts to lowercase
LENGTH(str) Returns number of characters
Date Functions
Function Description
NOW() Current date and time
CURDATE() Current date
YEAR(date) Extracts year from date
MONTH(date) Extracts month from date
SQL Joins
Join Type Description
INNER JOIN Returns matching rows from both tables
LEFT JOIN Returns all rows from the left table and matching rows from the right
RIGHT JOIN Returns all rows from the right table and matching rows from the left
FULL OUTER JOIN Returns all rows when there is a match in one of the tables
CROSS JOIN Returns the cartesian product (all combinations)
SELF JOIN A table is joined with itself
1. INNER JOIN
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;
2. LEFT JOIN
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;
3. RIGHT JOIN
SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;
4. FULL OUTER JOIN
SELECT e.name, d.dept_name
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.dept_id;
5. CROSS JOIN
SELECT e.name, d.dept_name
FROM employees e
CROSS JOIN departments d;
6. SELF JOIN
SELECT e.name AS employee,
m.name AS manager
FROM
employees e
LEFT JOIN
employees m ON e.manager_id = m.emp_id;
SQL Keys
Key Type Purpose
Primary Key Uniquely identifies each row in a table
Foreign Key Links one table to another
Unique Key Ensures all values in a column are unique (except NULLs)
Composite Key Combines two or more columns to uniquely identify a row
Primary Key
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50),
age INT);
Foreign Key
CREATE TABLE enrollments (
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
Unique Key
CREATE TABLE teachers (
teacher_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
Composite Key
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
SQL Constraints
Constraint Description
NOT NULL Column cannot have a NULL value
CHECK Ensures the values meet a condition
DEFAULT Sets a default value if none is provided
NOT NULL
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL
);
DEFAULT
CREATE TABLE orders (
order_id INT PRIMARY KEY,
status VARCHAR(20) DEFAULT 'Pending'
);
CHECK
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
age INT CHECK (age >= 18)
);
SQL View
A custom lens to look at data
A saved query that acts like a table
emp_id name dept salary
1 Alice HR 60000
2 Bob IT 75000
3 Charlie HR 58000
CREATE VIEW hr_employees AS
SELECT name, salary
FROM employees
WHERE dept = 'HR';
SELECT * FROM hr_employees;
SQL Index
An Index is like the index in a book
it helps you find data faster in a table.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
ALTER TABLE table_name
DROP INDEX index_name;
Stored Procedure in SQL
A Stored Procedure is a named set of SQL statements
that you save in the database and can call later.
OneShot Querie
create database xyz;
use xyz;
CREATE TABLE Students (
ID INT,
Name VARCHAR(50),
Age INT
);
ALTER TABLE Students
ADD Grade VARCHAR(2);
ALTER TABLE Students
drop Grade;
RENAME TABLE Students TO Kids;
INSERT INTO Kids (ID, Name, Age)
VALUES (1, 'Teddy Bear', 22);
TRUNCATE TABLE Kids;
drop table Kids;
CREATE TABLE ToyBox
(ToyID int, ToyName varchar(100), ToyType varchar(100));
INSERT INTO ToyBox (ToyID, ToyName, ToyType)
VALUES (1, 'Teddy Bear', 'Stuffed');
INSERT INTO ToyBox (ToyID, ToyName, ToyType)
VALUES (1, 'Teddy Bear', 'Stuffed'),
(2, 'Teddy Bearr', 'block'),
(3, 'Teddy Bearrr', 'Stuffed'),
(4, 'Teddy Bearrrr', 'block');
INSERT INTO ToyBox (ToyID, ToyName)
VALUES (1, 'Teddy Bearrrrr');
UPDATE ToyBox
SET ToyType = 'Plush'
WHERE ToyID = 1;
SET SQL_SAFE_UPDATES = 0;
DELETE FROM ToyBox
WHERE ToyID = 1;
GRANT SELECT, INSERT ON ToyBox TO Sam;
CREATE USER Sam IDENTIFIED BY 'password';
GRANT SELECT, INSERT ON ToyBox TO Sam;
SHOW GRANTS FOR Sam;
REVOKE INSERT ON ToyBox FROM Sam;
drop user Sam;
BEGIN;
delete from ToyBox;
INSERT INTO ToyBox (ToyID, ToyName)
VALUES (1, 'Teddy Bearrrrr');
SAVEPOINT before_more_toys;
SELECT * FROM xyz.ToyBox;
ROLLBACK TO SAVEPOINT before_more_toys;
INSERT INTO ToyBox (ToyID, ToyName)
VALUES (2, 'Car');
rollback;
COMMIT;
SELECT * FROM ToyBox ORDER BY ToyID desc;
SELECT ToyName FROM ToyBox;
SELECT ToyID FROM ToyBox WHERE ToyType = 'Stuffed';
SELECT ToyType, count(*) FROM ToyBox GROUP BY ToyType;
SELECT customer, AVG(amount) AS AVG_spent
FROM sales_data
GROUP BY customer
HAVING AVG_spent > 10;
SELECT customer, amount FROM sales_data WHERE amount = (SELECT min(amount) FROM sales_data);
select length('SHRIDHAR');
select day('2025-04-23');
SELECT e.name, d.dept_name
FROM employeess e
INNER JOIN departments d ON e.dept_id = d.dept_id;
SELECT e.name, d.dept_name
FROM employeess e
LEFT JOIN departments d ON e.dept_id = d.dept_id
UNION
SELECT e.name, d.dept_name
FROM employeess e
RIGHT JOIN departments d ON e.dept_id = d.dept_id;
SELECT e.name, d.dept_name
FROM employeess e
CROSS JOIN departments d;
SELECT e.name AS employee,
m.name AS manager
FROM
employeess e
INNER JOIN
employeess m ON e.manager_id = m.emp_id;
CREATE TABLE studentss (
student_id INT PRIMARY KEY default 5,
name VARCHAR(50),
age INT);
insert into students values(1,'shridhar',27);
insert into studentss(name,age) values('shree',25);
CREATE TABLE enrollments (
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
insert into enrollments values(1);
CREATE TABLE teachers (
teacher_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
CREATE TABLE enrollmentss (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
CREATE TABLE userss (
user_id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL default 'ABC'
);
insert into userss(user_id) values(1);
CREATE TABLE employeees (
emp_id INT PRIMARY KEY,
age INT CHECK (age >= 18)
);
insert into employeees values(1,15);
CREATE VIEW pen_value AS
SELECT customer, amount
FROM sales_data
WHERE product = 'Pen';
select * from pen_value;
drop view pen_value;
CREATE INDEX youtubee
ON youtube_channel_stats (subscribers);
select * from youtube_channel_stats where subscribers > 100000;
call youtube.empty();
call lakhsubs(600000);