0% found this document useful (0 votes)
12 views28 pages

? SQL Database Notes

SQL (Structured Query Language) is a standard language for managing and manipulating databases, primarily used with relational databases. It includes various commands categorized into DDL, DML, DCL, and TCL, which are used for defining structures, manipulating data, controlling access, and managing transactions, respectively. The document also explains concepts like tables, primary and foreign keys, and various SQL operations including joins and aggregate functions.

Uploaded by

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

? SQL Database Notes

SQL (Structured Query Language) is a standard language for managing and manipulating databases, primarily used with relational databases. It includes various commands categorized into DDL, DML, DCL, and TCL, which are used for defining structures, manipulating data, controlling access, and managing transactions, respectively. The document also explains concepts like tables, primary and foreign keys, and various SQL operations including joins and aggregate functions.

Uploaded by

uldesoleha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

By Mohan Barle...

🗄️ What is SQL?
SQL (Structured Query Language) is a standard language used to manage and
manipulate databases.
➡️ Used to store, retrieve, update, and delete data​
➡️ Works with Relational Databases
🗄️ SQL is the language used to communicate with and manage databases.
🏢 Real-Life Example
Think of a bank system 🏦
●​Customer details
●​Account balance
●​Transactions
All this data is stored in a database​
SQL is used to access and manage that data

What is a Database?
A database is an organized collection of data stored in tables.
Example table:

🌍 Where is SQL Used?


🏦 Banking systems
🛒 E-commerce websites
●​

📱 Mobile apps
●​

🏥 Hospitals
●​

🎓 Colleges
●​
●​
Almost every application that stores data uses SQL.
🏛️ What is RDBMS?
An RDBMS (Relational Database Management System) is a type of database
system that stores data in tables (rows and columns) and allows relationships

➡️
between those tables.​

➡️
Tables are connected​
Managed using SQL
🏛️ RDBMS is a database system that stores related data in connected
tables using SQL.
🛠️ Popular RDBMS Software
●​🐬 MySQL
●​🐘 PostgreSQL
●​🪟 Microsoft SQL Server
●​🏛️ Oracle Database
All of them use SQL language.

🗃️ What is a Database?
A database is an organized collection of data that is stored and can be easily
accessed, managed, and updated.

🏠 Real-Life Example
Think of a library 📚
●​Books are arranged properly
●​You can search by title or author
●​Records are maintained systematically
➡️ Library = Database​
➡️ Books = Data
🛠️ Types of Databases
🏛️ Relational Database
Stores data in related tables (uses SQL).
Examples:
🐬 MySQL
🐘 PostgreSQL
●​
●​

🌐 Non-Relational Database (NoSQL)


Stores data in flexible formats (JSON, documents, etc.)
Example:
●​🍃 MongoDB
📊 What is a Table in Database?
A table is a structured format used to store data in rows and columns inside a
database.

🏫 Real-Life Example
Think of a school attendance register 📘

This register is just like a database table.

🧱 Parts of a Table
📌 1️⃣ Column (Field)
●​Represents a category of data
●​Example: Name, Age, Salary

📌 2️⃣ Row (Record)


●​Represents a single entry
●​Contains data for each column

🛠️ Example SQL Command to Create Table


CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
🔑 What is a Primary Key?
A Primary Key is a column (or set of columns) in a table that uniquely identifies
each row.
➡️ No duplicates ❌​
➡️ No NULL values ❌​
➡️ Unique for every record ✅
🏫 Real-Life Example
Think of a Student Roll Number 🎓
Even if two students have the same name, their Roll Number is always unique.
➡️ Roll Number = Primary Key
🛠️ SQL Example
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
🔗 What is a Foreign Key?

🔗 What is a Foreign Key?


A Foreign Key is a column (or set of columns) in one table that refers to the
Primary Key of another table.
➡️ It creates a relationship between two tables​
➡️ Maintains data integrity
🧠 Rules of Foreign Key
●​🔗 Must refer to a Primary Key
●​🔄 Can have duplicate values
●​✅ Can contain NULL (if allowed)
●​🧩 A table can have multiple foreign keys

🛠️ SQL Example
CREATE TABLE Courses (
Course_ID INT PRIMARY KEY,
Course_Name VARCHAR(50)
);
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(50),
Course_ID INT,
FOREIGN KEY (Course_ID) REFERENCES Courses(Course_ID)
);

🟡 DDL – Data Definition Language


🏗️ What is DDL?
DDL (Data Definition Language) is a category of SQL commands used to define
and manage database structure.
➡️ Used to create, modify, and delete database objects​
➡️ Works on tables, databases, schemas
🧱 Common DDL Commands
1️⃣ CREATE: Used to create a new database or table
CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);

2️⃣ ALTER: Used to modify an existing table


ALTER TABLE Students
ADD Email VARCHAR(100);
✔️ Add / Modify / Drop columns
3️⃣ DROP: Used to delete a table or database permanently
DROP TABLE Students;
⚠️ Data will be lost permanently
4️⃣ TRUNCATE: Used to delete all records from a table
DROP TABLE Students;

✔️ Faster than DELETE​


✔️ Removes all rows​
❌ Cannot use WHERE
5️⃣ RENAME: Used to rename a table
RENAME TABLE Students TO College_Students;

🧠 Key Characteristics of DDL


●​🏗️ Changes database structure
●​🔄 Auto-commit (cannot rollback easily)
●​📊 Works on schema objects
—-------------------- DML – Data Manipulation Language

✏️ What is DML?
DML (Data Manipulation Language) is a category of SQL commands used to
manage and modify data inside tables.
➡️ Works on data (rows)​
➡️ Does NOT change table structure
🧰 Common DML Commands
1️⃣ INSERT: Used to add new records into a table.
INSERT INTO Students (ID, Name, Age)
VALUES (1, 'Mohan', 22);
✔️ Adds new row​
✔️ Can insert multiple rows
2️⃣ SELECT: Used to retrieve data from a table.
SELECT * FROM Students;

✔️ * means all columns​


✔️ Can use WHERE, ORDER BY, GROUP BY
3️⃣ UPDATE: Used to modify existing records.
UPDATE Students
SET Age = 23
WHERE ID = 1;

⚠️ Always use WHERE to avoid updating all rows


4️⃣ DELETE: Used to remove records from a table.
DELETE FROM Students
WHERE ID = 1;

✔️ Removes selected rows,⚠️ Without WHERE, deletes all rows


🧠 Key Characteristics of DML
●​📊 Works on table data
●​🔄 Changes can be rolled back (if not committed)
●​🧾 Uses transactions
—--------------------- DCL – Data Control Language

🔐 What is DCL?
DCL (Data Control Language) is a category of SQL commands used to control
access and permissions in a database.
➡️ Manages who can access what​
➡️ Controls user privileges​
➡️ Enhances database security
🛡️ Why DCL is Important?
●​🔒 Protects sensitive data
●​👤 Manages user roles

●​🏢 Used in enterprise systems


●​Controls read/write access

—----------------------🧰 Main DCL Commands

1️⃣ GRANT: Used to give permissions to users.

GRANT SELECT, INSERT

ON Students

TO user1;
✔️ Allows user1 to read and insert data
2️⃣ REVOKE: Used to remove permissions from users.

REVOKE INSERT

ON Students

FROM user1;
✔️ Removes insert permission
👤 Example Scenario
Imagine a company database 🏢
●​👨‍💼 Manager → Full access
●​👩‍💻 Employee → Only SELECT
●​👀 Guest → Limited access
DCL helps control these permissions.

🧠 Key Features of DCL


●​🔐 Works on user privileges
●​👥 Used with roles
●​🛡️ Prevents unauthorized access
●​📊 Important for security policies

—----------------🔄 TCL – Transaction Control Language

🔄 What is TCL?
TCL (Transaction Control Language) is a category of SQL commands used to
manage transactions in a database.
➡️ Controls changes made by DML commands​
➡️ Ensures data consistency​
➡️ Supports rollback & recovery
🔄 TCL manages transactions and ensures safe database operations.
🧠 What is a Transaction?
A transaction is a group of SQL operations executed as one unit.
Example:
💰 Transfer money from Account A
➕ Add money to Account B
●​
●​
Both must succeed together — otherwise, cancel everything.
—------------------- Main TCL Commands

1️⃣ COMMIT: Used to save changes permanently


COMMIT;
✔️ Makes changes final​
✔️Cannot undo after commit
2️⃣ ROLLBACK: Used to undo changes
ROLLBACK;
✔️ Reverts to last committed state
3️⃣ SAVEPOINT: Creates a point inside a transaction to rollback partially.
SAVEPOINT sp1;

4️⃣ ROLLBACK TO SAVEPOINT


ROLLBACK TO sp1;
✔️ Undo changes after that savepoint only
🧪 Example Scenario
INSERT INTO Accounts VALUES (101, 'Mohan', 5000);
SAVEPOINT sp1;
UPDATE Accounts SET Balance = 3000 WHERE ID = 101;
ROLLBACK TO sp1;
COMMIT;

🛡️ Why TCL is Important?


●​🔒 Maintains data integrity
●​💰 Critical for banking systems
●​ Supports ACID properties
📘 Important SQL Clauses & Keywords Explained
—---------------

1️⃣ SELECT: 🔎 Used to retrieve data from a table.


SELECT Name, Age FROM Students;
✔️ Fetch specific columns​
✔️ * for all columns
2️⃣ WHERE: Used to filter records.
SELECT * FROM Students
WHERE Age > 20;
✔️ Applies condition
3️⃣ DISTINCT: Removes duplicate values.
SELECT DISTINCT Course FROM Students;
✔️ Shows unique values only
4️⃣ ORDER BY: Sorts the result.
SELECT * FROM Students
ORDER BY Age DESC;
✔️ ASC (default)​
✔️ DESC
5️⃣ GROUP BY: Groups rows with the same values.
SELECT Course, COUNT(*)
FROM Students
GROUP BY Course;
✔️ Used with aggregate functions
6️⃣ HAVING: Filters grouped data.
SELECT Course, COUNT(*)
FROM Students
GROUP BY Course
HAVING COUNT(*) > 2;
✔️ Works after GROUP BY
7️⃣ LIMIT: Restricts number of rows returned.
SELECT * FROM Students
LIMIT 5;
✔️ Shows first 5 rows
8️⃣ ALIAS: Gives temporary name to column/table.
SELECT Name AS Student_Name
FROM Students;
✔️ Improves readability
9️⃣ IN: Checks multiple values.
SELECT * FROM Students
WHERE Course IN ('BCA', 'BBA');
✔️ Multiple comparisons
🔟 BETWEEN: Selects values in a range.
SELECT * FROM Students
WHERE Age BETWEEN 18 AND 25;
✔️ Inclusive range
1️⃣1️⃣ LIKE: Search using pattern matching.
SELECT * FROM Students
WHERE Name LIKE 'M%';

✔️ % → any characters​
✔️ _ → single character
1️⃣2️⃣ IS NULL
Checks for NULL values.
SELECT * FROM Students
WHERE Email IS NULL;
✔️ Finds missing data
🔹 Arithmetic Operators in SQL ➕➖✖️➗
—------------

Arithmetic operators are used to perform mathematical calculations on


numeric data in a database.
They work mainly with number columns like salary, marks, price, quantity, etc.

🧮 Examples
1️⃣ Addition (+)
SELECT Name, Salary + 2000 AS Increased_Salary
FROM Employees;
Adds 2000 to salary.

2️⃣ Subtraction (-)


SELECT Name, Salary - 500 AS Deducted_Salary
FROM Employees;
Subtracts 500 from salary.

3️⃣ Multiplication (*)


SELECT Name, Salary * 12 AS Annual_Salary
FROM Employees;
Calculates yearly salary.

4️⃣ Division (/)


SELECT Name, Salary / 30 AS Per_Day_Salary
FROM Employees;
Calculates daily salary.
🔹 Comparison Operators in SQL ⚖️
—-------------

Comparison operators are used to compare two values. They are mainly used in
the WHERE clause to filter records.

1️⃣ Equal To (=): Shows employees from IT department.


SELECT * FROM Employees
WHERE Department = 'IT';

2️⃣ Not Equal To (!= or <>): Shows employees not in HR.


SELECT * FROM Employees
WHERE Department <> 'HR';

3️⃣ Greater Than (>): Salary greater than 30000.


SELECT * FROM Employees
WHERE Salary > 30000;

4️⃣ Less Than (<): Employees younger than 25.


SELECT * FROM Employees
WHERE Age < 25;

5️⃣ Greater Than or Equal To (>=)


SELECT * FROM Employees
WHERE Salary >= 50000;

6️⃣ Less Than or Equal To (<=)


SELECT * FROM Employees
WHERE Age <= 30;
Logical Operators in SQL

Logical operators are used to combine multiple conditions in a SQL query.​


They are mostly used with the WHERE clause.

1️⃣ AND Operator: Returns records only if all conditions are true.
SELECT * FROM Employees
WHERE Salary > 30000 AND Department = 'IT';
Employees from IT department​
AND salary greater than 30000 Both conditions must be true.

2️⃣ OR Operator: Returns records if at least one condition is true.


SELECT * FROM Employees
WHERE Department = 'HR' OR Department = 'IT';
Employees from HR or IT

3️⃣ NOT Operator: Reverses the condition.


SELECT * FROM Employees
WHERE NOT Department = 'HR';
Employees not in HR

—--------------------Aggregate Functions in SQL

Aggregate functions perform calculations on multiple rows and return a single


value.
They are commonly used with:
●​GROUP BY
●​HAVING

1️⃣ COUNT():
Counts number of rows.
SELECT COUNT(*) FROM Employees;
Total number of employees
SELECT COUNT(Department) FROM Employees;
Counts non-NULL department values

2️⃣ SUM(): Adds numeric values.


SELECT SUM(Salary) FROM Employees;
Total salary of all employees

3️⃣ AVG(): Calculates average value.


SELECT AVG(Salary) FROM Employees;
Average salary

4️⃣ MIN(): Returns the smallest value.


SELECT MIN(Salary) FROM Employees;

5️⃣ MAX(): Returns the largest value.


SELECT MAX(Salary) FROM Employees;
📊 Using Aggregate Functions with GROUP BY
SELECT Department, COUNT(*) AS Total_Employees
FROM Employees
GROUP BY Department;
Shows employee count per department

🛑 Using HAVING with Aggregate Functions


SELECT Department, COUNT(*)
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
Shows departments having more than 5 employees
🔗 INNER JOIN in SQL
INNER JOIN is used to combine records from two tables and return only
matching rows based on a common column. If there is no match in either table,
that row will NOT appear in the result.

📌 Basic Syntax
SELECT columns
FROM Table1
INNER JOIN Table2
ON Table1.common_column = Table2.common_column;
🧾 Example
🔎 SQL Query
SELECT [Link], [Link]
FROM Customers
INNER JOIN Orders
ON [Link] = [Link];

🔹 LEFT JOIN (LEFT OUTER JOIN) in SQL


LEFT JOIN returns:
●​All records from the left table
●​ Matching records from the right table
●​ If no match → NULL values from the right table
LEFT JOIN returns all records from the left table and matching records from
the right table.

📌 Basic Syntax
SELECT columns

FROM Table1 (Left table)

LEFT JOIN Table2 (Right table)

ON Table1.common_column = Table2.common_column;
🧾 Example

SELECT [Link], [Link]


FROM Customers
LEFT JOIN Orders
ON [Link] = [Link];

🔹 RIGHT JOIN (RIGHT OUTER JOIN) in SQL


RIGHT JOIN returns:
●​ All records from the right table
●​ Matching records from the left table
●​If no match → NULL values from the left table

📌 Basic Syntax

SELECT columns
FROM Table1
RIGHT JOIN Table2
ON Table1.common_column = Table2.common_column;
Table2 = Right table (all records will appear)
🧾 Example

🔎 SQL Query
SELECT [Link], [Link]
FROM Customers
RIGHT JOIN Orders
ON [Link] = [Link];

🔹 FULL JOIN (FULL OUTER JOIN) in SQL


FULL JOIN returns:
●​ All records from the left table
●​ All records from the right table
●​ Matching records combined
●​Non-matching rows show NULL

📌 Basic Syntax

SELECT columns
FROM Table1
FULL JOIN Table2
ON Table1.common_column = Table2.common_column;
SELECT [Link], [Link]
FROM Customers
FULL JOIN Orders
ON [Link] = [Link];

🔄 SELF JOIN in SQL


SELF JOIN is a join where a table is joined with itself.
It is used when we want to compare rows within the same table.​
Mostly used for hierarchical data (manager–employee, parent–child).

📌 Basic Syntax
SELECT A.column_name, B.column_name
FROM TableName A
JOIN TableName B
ON A.common_column = B.common_column;

✔️ Same table​
✔️ Different aliases (A and B)
🧾 Example: Employee & Manager


Here:
●​Rahul is top manager (no manager)
●​Anjali & Mohan report to Rahul
●​Kiran reports to Anjali

🔎 Query
SELECT
[Link] AS Employee,
[Link] AS Manager
FROM Employees e
LEFT JOIN Employees m
ON [Link] = [Link];
NOMALIZATION IN SQL :

WHAT IS NORMALIZATION?
"Normalization means organizing data in a better way in the database. It removes
duplicate data and keeps it clean.
For example, instead of storing many values in one column, we separate them into different
rows and tables."

1️⃣ First Normal Form (1NF) in SQL


First Normal Form (1NF) means:
●​Each column contains only single (atomic) values
●​No multiple values in one cell
●​No repeating groups
●​Each row is unique (primary key should exist)
Simply: One cell = One value
2️⃣ Second Normal Form (2NF) in SQL
A table is in Second Normal Form (2NF) if:
1️⃣ It is already in 1NF​
2️⃣ There is no partial dependency​
3️⃣ Every non-key column depends on the entire primary key
Simple meaning:​
If a table has a composite primary key, then all non-key columns must depend on
the full key — not just part of it.

Example:
The Course Table ensures that COURSE_FEE depends only on COURSE_NO. The
Student-Course Table ensures there are no partial dependencies because it only relates
students to courses.

Third Normal Form (3NF)


Remove transitive dependencies. A column should depend only on the primary key, not
on another non-key column. This removes transitive dependencies and keeps data clean
and non-redundant.”

🧠 What is Transitive Dependency?


If column A → column B → column C​
Then column C is transitively dependent on column A (indirectly).

You might also like