SQL (Structured Query Language) is the standard programming language used to manage and manipulate relational databases. It is designed for performing tasks such as retrieving data, updating records, inserting new rows, and deleting data from a database.
SQL is both declarative and domain-specific, which means you describe what data you want to work with, not how to retrieve it. It’s supported by all major relational database management systems (RDBMS) such as:
MySQL
PostgreSQL
Oracle Database
Microsoft SQL Server
SQLite
IBM Db2
A simple example:
SELECT name, age FROM employees WHERE age > 30;
This query fetches names and ages of employees who are older than 30.
SQL plays a critical role in the world of data and application development. Here’s why it’s so important:
SQL is used across almost every RDBMS, which makes it a universal skill for developers, data analysts, and DBAs.
From banking systems to e-commerce websites, data is stored and retrieved using SQL. It enables real-time data processing, analysis, and reporting.
With SQL, users can filter, group, and aggregate data using simple yet powerful commands. It’s essential for business intelligence, reporting, and dashboards.
SQL is foundational for learning advanced technologies like:
Data Warehousing
Big Data tools (Hive, Presto)
ETL pipelines
Business analytics platforms (Tableau, Power BI)
SQL is among the top 3 most required technical skills for roles like:
Data Analyst
Backend Developer
Business Intelligence Analyst
Database Administrator
Data Engineer
Every time you log into a website, post a comment, or make a purchase, SQL is running in the background—storing user sessions, logging transactions, and querying user data.
Example:
Login credentials stored in a database
Product listings pulled using SELECT
queries
Organizations use SQL to analyze sales trends, generate performance reports, and track KPIs.
Example:
SELECT region, SUM(sales) FROM orders GROUP BY region;
This gives the total sales by region for business dashboards.
Banks and fintech platforms use SQL to:
Validate transactions
Generate statements
Detect fraud patterns
Manage customer data securely
SQL is used in:
Patient record management
Insurance claims processing
Risk modeling
Appointment scheduling
Online retailers use SQL to:
Track orders and inventory
Personalize product recommendations
Analyze shopping behavior
Power search and filter systems
HR departments rely on SQL to:
Manage employee databases
Calculate payroll
Track leaves, attendance, and performance reviews
Marketers use SQL to:
Segment customer data
Measure campaign performance
Predict churn and lifetime value (CLTV)
Learning platforms (like your eLearning site) use SQL to:
Track student progress
Manage course enrollments
Generate certificates and reports
To work effectively with SQL, it’s essential to understand how relational databases are structured and how they store data. This section covers the core building blocks: relational models, tables, rows, columns, primary keys, and foreign keys.
A relational database is a type of database that stores data in a structured format using tables. Each table represents a specific type of entity (e.g., customers, products, orders), and the data is organized in rows and columns.
Relational databases use relationships to link data across different tables. These relationships are maintained through keys (like primary and foreign keys).
Popular relational database management systems (RDBMS) include:
MySQL
PostgreSQL
Oracle Database
Microsoft SQL Server
SQLite
Relational databases follow the ACID principles:
Atomicity – Transactions are all or nothing
Consistency – Data remains valid before and after transactions
Isolation – Transactions do not interfere with each other
Durability – Committed data is permanently saved
A table is a collection of related data entries. It is composed of columns (fields) and rows (records).
Example – Students
Table:
StudentID | Name | Age | Grade |
---|---|---|---|
1 | John Smith | 20 | A |
2 | Emma Brown | 21 | B |
The table name is Students
.
Each column (StudentID, Name, Age, Grade) represents a field of the record.
Each row is a data record of a single student.
Defines the type of data stored. Each column has a name and data type (e.g., INT, VARCHAR).
Represents a single record in the table. A row contains values for each column.
A Primary Key is a unique identifier for each record in a table. It ensures that no two rows can have the same primary key value.
Characteristics of a Primary Key:
Must contain unique values
Cannot be NULL
Each table can have only one primary key
Example:
In the Students
table:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT
);
Here, StudentID
is the primary key. It uniquely identifies each student.
A Foreign Key is a field in one table that refers to the primary key in another table. It is used to create relationships between tables.
Example:
Let’s say you have a Courses
table and an Enrollments
table:
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100)
);
CREATE TABLE Enrollments (
EnrollmentID INT PRIMARY KEY,
StudentID INT,
CourseID INT,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
In this case:
StudentID
in Enrollments
is a foreign key referring to the Students
table.
CourseID
in Enrollments
is a foreign key referring to the Courses
table.
These keys ensure referential integrity, meaning:
You can’t enroll a student who doesn’t exist in the Students
table.
You can’t reference a course that hasn’t been defined in the Courses
table.
SQL provides a wide range of data types to define the kind of data each column can hold. Choosing the correct data type ensures data integrity, performance, and storage efficiency.
Numeric types are used to store whole numbers and decimal values.
Data Type | Description | Example Values |
---|---|---|
INT | Integer number (no decimal) | 1, 100, -25 |
SMALLINT | Smaller range of integers | 100, -300 |
BIGINT | Larger range of integers | 9999999999 |
DECIMAL(p, s) | Fixed precision number | 123.45 (p=5, s=2) |
NUMERIC(p, s) | Same as DECIMAL | 1000.00 |
FLOAT | Approximate decimal value (floating point) | 1.2345, 3.14e+05 |
REAL | Lower precision floating point | 3.14, -0.001 |
DOUBLE | Double precision floating point | 12345.6789 |
Use
INT
for whole numbers like age or quantity.
UseDECIMAL
orNUMERIC
for financial or precise values like prices or interest rates.
AvoidFLOAT
for currency—it may lose precision.
These types are used to store letters, numbers, and symbols as text.
Data Type | Description | Example |
---|---|---|
CHAR(n) | Fixed-length string (n characters) | ‘Y’ → stored as ‘Y ‘ |
VARCHAR(n) | Variable-length string up to n characters | ‘Hello’, ‘abc123’ |
TEXT | Large string of text (size may exceed VARCHAR) | Full paragraph, comments |
CHAR is good for fixed values like country codes (e.g., ‘US’).
VARCHAR is ideal for variable data like names or email addresses.
TEXT is best for long entries like descriptions or messages.
CREATE TABLE users (
username VARCHAR(50),
bio TEXT
);
Used to store calendar dates, times, and timestamps.
Data Type | Description | Example |
---|---|---|
DATE | Stores year, month, and day | ‘2025-07-16’ |
TIME | Stores hour, minute, second | ’14:30:00′ |
DATETIME | Stores both date and time | ‘2025-07-16 14:30:00’ |
TIMESTAMP | Stores date/time with timezone support | ‘2025-07-16T14:30:00Z’ |
YEAR | Stores a year (MySQL specific) | ‘2025’ |
Use these types for:
Birthdays → DATE
Order timestamps → TIMESTAMP
or DATETIME
Log records → TIMESTAMP
CREATE TABLE orders (
order_id INT,
order_date DATETIME
);
Boolean stores TRUE or FALSE values.
Data Type | Description | Example |
---|---|---|
BOOLEAN or BOOL | True/False flag | TRUE, FALSE, 1, 0 |
In many databases:
TRUE
is stored as 1
FALSE
is stored as 0
Use Boolean values for:
IsActive flags
IsDeleted or IsVerified fields
CREATE TABLE users (
user_id INT,
is_active BOOLEAN
);
SQL statements are grouped into four main categories based on their functionality: DDL, DML, DCL, and TCL. Understanding these categories helps you write more efficient and structured queries for database operations.
DDL commands are used to define and modify the structure of database objects like tables, schemas, indexes, etc. These changes affect the database schema.
Command | Description |
---|---|
CREATE |
Creates a new table, database, or index |
ALTER |
Modifies an existing object (add/remove column, etc.) |
DROP |
Deletes tables, views, databases, etc. |
TRUNCATE |
Removes all records from a table (faster than DELETE) |
RENAME |
Renames a table or column |
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Department VARCHAR(50)
);
DML commands allow you to manipulate (insert, update, delete) data in existing tables. These operations affect the records, not the schema.
Command | Description |
---|---|
SELECT |
Retrieves data from one or more tables |
INSERT |
Adds new rows to a table |
UPDATE |
Modifies existing records |
DELETE |
Removes rows from a table |
MERGE |
Combines INSERT and UPDATE in one step (supported in some RDBMS) |
INSERT INTO Employees (EmployeeID, Name, Department)
VALUES (1, 'John Smith', 'HR');
DCL commands manage access rights, permissions, and other controls of the database.
Command | Description |
---|---|
GRANT |
Gives privileges to users or roles |
REVOKE |
Removes previously granted permissions |
GRANT SELECT, INSERT ON Employees TO user123;
This allows user123
to read and insert data into the Employees
table.
TCL commands handle transactions, ensuring consistency and reliability of database operations. Transactions are useful when a group of DML operations must be treated as a single unit.
Command | Description |
---|---|
BEGIN |
Starts a transaction |
COMMIT |
Saves all changes made in the transaction |
ROLLBACK |
Undoes changes made in the current transaction |
SAVEPOINT |
Sets a point to roll back to within a transaction |
SET TRANSACTION |
Sets properties like isolation level |
BEGIN;
UPDATE Employees SET Department = 'Finance' WHERE EmployeeID = 1;
DELETE FROM Employees WHERE Department = 'Sales';
ROLLBACK;
This will undo both operations if something goes wrong.
In SQL, tables are the core structures that store data in rows and columns. To effectively manage databases, you need to understand how to create, modify, and delete tables, along with defining constraints to ensure data integrity.
The CREATE TABLE
command is used to create a new table by specifying the column names, data types, and constraints.
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(100) UNIQUE,
Department VARCHAR(50),
Salary DECIMAL(10,2) DEFAULT 50000,
Age INT CHECK (Age >= 18)
);
This table includes:
A primary key on EmployeeID
A NOT NULL constraint on Name
A UNIQUE constraint on Email
A DEFAULT salary
A CHECK constraint to ensure age is 18 or older
The ALTER TABLE
command allows you to modify an existing table. You can:
Add or remove columns
Change column data types
Add or drop constraints
ALTER TABLE Employees ADD JoinDate DATE;
ALTER TABLE Employees MODIFY Salary DECIMAL(12,2);
ALTER TABLE Employees DROP COLUMN JoinDate;
ALTER TABLE Employees ADD CONSTRAINT chk_salary CHECK (Salary > 0);
The DROP TABLE
command is used to permanently delete a table and all its data from the database.
DROP TABLE table_name;
DROP TABLE Employees;
Note: This action is irreversible—use with caution.
SQL constraints are rules applied to columns to enforce data integrity.
Constraint | Description |
---|---|
NOT NULL | Prevents NULL values in a column |
UNIQUE | Ensures all values in a column are different |
DEFAULT | Sets a default value for a column if no value is given |
CHECK | Ensures values meet a condition |
PRIMARY KEY | Uniquely identifies each row in the table |
FOREIGN KEY | Enforces referential integrity between tables |
Ensures the column must have a value.
Name VARCHAR(100) NOT NULL
Ensures all values in the column are different.
Email VARCHAR(100) UNIQUE
Automatically assigns a value if none is provided.
Salary DECIMAL(10,2) DEFAULT 50000
Validates values using a condition.
Age INT CHECK (Age >= 18)
Identifies each row uniquely. Combines NOT NULL + UNIQUE.
EmployeeID INT PRIMARY KEY
Links one table to another using a key.
CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50)
);
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(100), DeptID INT, FOREIGN KEY (DeptID) REFERENCES Departments(DeptID) );
Once you’ve created your tables, the next step is to insert, update, and delete data. These are key operations in the Data Manipulation Language (DML) category of SQL.
INSERT INTO
– Add New RecordsThe INSERT INTO
statement adds new rows into a table.
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
INSERT INTO Employees (EmployeeID, Name, Email, Department, Salary, Age)
VALUES (101, 'Alice Johnson', 'alice@example.com', 'HR', 60000, 28);
You can also insert multiple rows at once:
INSERT INTO Employees (EmployeeID, Name, Department)
VALUES
(102, 'Bob Smith', 'Finance'),
(103, 'Clara Brown', 'IT');
Tip: Always list column names to avoid issues if table structure changes.UPDATE
– Modify Existing RecordsThe UPDATE
statement modifies data that already exists in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Employees
SET Salary = 65000
WHERE EmployeeID = 101;
You can update multiple columns:
UPDATE Employees
SET Department = 'Operations', Age = 30
WHERE Name = 'Alice Johnson';
Important: Always use a WHERE
clause to avoid updating all rows.DELETE
– Remove RecordsThe DELETE
statement removes existing records from a table.
DELETE FROM table_name
WHERE condition;
DELETE FROM Employees
WHERE EmployeeID = 103;
If you omit the WHERE
clause:
DELETE FROM Employees;
This deletes all rows from the table—use with caution!
Operation | Purpose | Requires WHERE ? |
Risk Level |
---|---|---|---|
INSERT |
Add new row(s) | No | Low |
UPDATE |
Modify existing row(s) | Yes (recommended) | Medium to High |
DELETE |
Remove row(s) | Yes (recommended) | High |
Use Case | SQL Example |
---|---|
Add a new employee | INSERT INTO Employees (...) VALUES (...); |
Increase salaries by 10% | UPDATE Employees SET Salary = Salary * 1.10; |
Remove inactive users | DELETE FROM Users WHERE is_active = FALSE; |
Correct a user’s email | UPDATE Users SET Email = 'new@mail.com' WHERE ID=1; |
SELECT
in SQLThe SELECT
statement is the most commonly used SQL command. It allows you to query and retrieve data from one or more tables based on specific conditions.
SELECT
BasicsThe simplest form of retrieving data uses the SELECT
statement.
SELECT column1, column2, ...
FROM table_name;
SELECT Name, Department FROM Employees;
You can also select all columns using an asterisk *
:
SELECT * FROM Employees;
Tip: Use
*
for quick testing, but avoid it in production for performance and readability.
WHERE
Clause – Filter Your ResultsThe WHERE
clause is used to filter records that meet a specific condition.
SELECT column1, column2
FROM table_name
WHERE condition;
-- Find employees in the HR department
SELECT Name FROM Employees
WHERE Department = 'HR';
— Get employees with a salary above 50000
SELECT Name, Salary FROM Employees
WHERE Salary > 50000;
=
, !=
>
, <
, >=
, <=
BETWEEN
, IN
, LIKE
, IS NULL
, IS NOT NULL
SELECT * FROM Employees
WHERE Name LIKE 'A%'; -- Names starting with A
ORDER BY
– Sort Your ResultsUse ORDER BY
to sort the results in ascending (ASC
) or descending (DESC
) order.
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC|DESC];
-- Sort employees by salary in ascending order
SELECT Name, Salary FROM Employees
ORDER BY Salary ASC;
— Sort by department, then by name
SELECT * FROM Employees
ORDER BY Department ASC, Name ASC;
ASC is the default. You can omit it when sorting in ascending order.
LIMIT
and OFFSET
– Paginate ResultsUsed to restrict the number of records returned, especially useful for large datasets and pagination.
SELECT * FROM table_name
LIMIT number OFFSET start;
-- Get the first 5 rows
SELECT * FROM Employees
LIMIT 5;
— Skip the first 10 rows, then return the next 5
SELECT * FROM Employees
LIMIT 5 OFFSET 10;
LIMIT
is supported in MySQL, PostgreSQL, and SQLite. In SQL Server, use TOP
or FETCH NEXT
.
Comparison Operators: =, !=, <, >, BETWEEN, IN, LIKE
Also Read: SQL Interview Questions
SQL provides built-in functions to perform operations on data, such as aggregating values, manipulating strings, handling dates, and executing mathematical calculations. These functions simplify complex tasks and enhance query performance.
These functions perform a calculation on a set of values and return a single value—often used with GROUP BY
.
Function | Description | Example |
---|---|---|
SUM() |
Returns the total sum | SUM(Salary) |
AVG() |
Returns the average value | AVG(Age) |
COUNT() |
Returns the number of rows | COUNT(*) |
MIN() |
Finds the minimum value | MIN(Salary) |
MAX() |
Finds the maximum value | MAX(Age) |
SELECT COUNT(*) AS TotalEmployees,
AVG(Salary) AS AverageSalary,
MAX(Age) AS OldestEmployee
FROM Employees;
These are used to manipulate text data, such as names, addresses, or any VARCHAR fields.
Function | Description | Example |
---|---|---|
CONCAT() |
Combines two or more strings | CONCAT(FirstName, ' ', LastName) |
UPPER() |
Converts to uppercase | UPPER(Name) |
LOWER() |
Converts to lowercase | LOWER(Email) |
SUBSTRING() |
Extracts part of a string | SUBSTRING(Name, 1, 3) |
SELECT CONCAT(FirstName, ' ', LastName) AS FullName,
UPPER(Department) AS DeptUpper
FROM Employees;
SQL provides date and time functions to get current timestamps, calculate differences, or extract parts of a date.
Function | Description | Example |
---|---|---|
NOW() |
Returns current date & time | NOW() |
CURDATE() |
Returns current date only | CURDATE() |
DATEDIFF() |
Calculates difference between two dates | DATEDIFF(CURDATE(), HireDate) |
SELECT Name, HireDate,
DATEDIFF(CURDATE(), HireDate) AS DaysWorked
FROM Employees;
Use NOW()
for timestamp logs, and DATEDIFF()
for calculating durations.
These functions are used for numerical calculations, rounding, and formatting.
Function | Description | Example |
---|---|---|
ROUND() |
Rounds a number to given decimals | ROUND(123.456, 2) |
CEIL() |
Rounds up to the next whole number | CEIL(4.3) → 5 |
FLOOR() |
Rounds down to whole number | FLOOR(4.9) → 4 |
SELECT Salary,
ROUND(Salary * 0.1, 2) AS Bonus,
CEIL(Salary / 1000) AS SalaryInThousands
FROM Employees;
GROUP BY
and HAVING
in SQLWhen you need to analyze data in groups—such as by department, region, or category—you use the GROUP BY
clause. To filter aggregate results, you use HAVING
.
Together, these clauses help you generate powerful reports like total sales per region, average salary per department, or number of orders per customer.
GROUP BY
The GROUP BY
clause is used to group rows that have the same values in specified columns. It’s often used with aggregate functions like COUNT()
, SUM()
, AVG()
, etc.
SELECT column1, AGG_FUNCTION(column2)
FROM table_name
GROUP BY column1;
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department;
This groups employees by department and calculates the average salary for each group.
GROUP BY
Use Case | Query Example |
---|---|
Total employees per department | SELECT Department, COUNT(*) FROM Employees GROUP BY Department; |
Sum of sales per region | SELECT Region, SUM(Sales) FROM Orders GROUP BY Region; |
Average age per job title | SELECT JobTitle, AVG(Age) FROM Staff GROUP BY JobTitle; |
HAVING
HAVING
is like WHERE
, but it filters after grouping. You use it when you want to return only those groups that meet a specific condition.
WHERE
filters rows before grouping.HAVING
filters after grouping and aggregation.
SELECT column1, AGG_FUNCTION(column2)
FROM table_name
GROUP BY column1
HAVING AGG_FUNCTION(column2) condition;
SELECT Department, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
This returns only departments with more than 5 employees.
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 60000;
Returns departments where the average salary is greater than ₹60,000.
WHERE
vs HAVING
– Key DifferenceClause | When It Works | Used With | Filters By |
---|---|---|---|
WHERE |
Before GROUP BY |
Regular columns | Rows |
HAVING |
After GROUP BY |
Aggregate results | Groups/aggregates |
In real-world databases, data is normalized and split into multiple related tables. To fetch data across those tables, we use SQL joins.
Joins allow you to combine rows from two or more tables based on related columns—usually primary and foreign keys.
INNER JOIN
Returns only the matching rows from both tables based on the join condition.
SELECT A.column, B.column
FROM TableA A
INNER JOIN TableB B ON A.common_column = B.common_column;
SELECT Employees.Name, Departments.DeptName
FROM Employees
INNER JOIN Departments ON Employees.DeptID = Departments.DeptID;
Returns employees who are assigned to a department.
LEFT JOIN
(or LEFT OUTER JOIN
)Returns all rows from the left table, and matched rows from the right table. If no match, right-side columns show NULL
.
SELECT Employees.Name, Departments.DeptName
FROM Employees
LEFT JOIN Departments ON Employees.DeptID = Departments.DeptID;
Useful for finding employees even if their department is not assigned yet.
RIGHT JOIN
(or RIGHT OUTER JOIN
)Returns all rows from the right table, and matched rows from the left table. Non-matching left rows will return NULL
.
SELECT Employees.Name, Departments.DeptName
FROM Employees
RIGHT JOIN Departments ON Employees.DeptID = Departments.DeptID;
Useful for listing all departments—even those with no employees.
FULL OUTER JOIN
Returns all rows from both tables. Non-matching rows from either side return NULL
in columns from the other table.
Not supported in MySQL directly (use UNION
of LEFT
+ RIGHT
).
SELECT A.Name, B.DeptName
FROM Employees A
FULL OUTER JOIN Departments B ON A.DeptID = B.DeptID;
Shows a complete view of employees and departments—matched or not.
SELF JOIN
A table is joined with itself, often used for hierarchies (e.g., managers and employees).
SELECT E1.Name AS Employee, E2.Name AS Manager
FROM Employees E1
JOIN Employees E2 ON E1.ManagerID = E2.EmployeeID;
Get employee names along with their managers.CROSS JOIN
Returns the Cartesian product of two tables. Each row from the first table is paired with all rows from the second table.
SELECT A.Name, B.DeptName
FROM Employees A
CROSS JOIN Departments B;
Use with caution—this grows exponentially with table size.
SELECT e.Name, d.DeptName
FROM Employees e
INNER JOIN Departments d ON e.DeptID = d.DeptID;
SELECT e.Name
FROM Employees e
LEFT JOIN Departments d ON e.DeptID = d.DeptID
WHERE d.DeptID IS NULL;
SELECT d.DeptName
FROM Departments d
LEFT JOIN Employees e ON d.DeptID = e.DeptID
WHERE e.EmployeeID IS NULL;
A subquery (also known as a nested query) is a query inside another query. Subqueries help break down complex logic and are often used in SELECT
, WHERE
, and FROM
clauses to filter or compute data dynamically.
A scalar subquery returns a single value (one row, one column). It can be used in SELECT
, WHERE
, or SET
clauses.
SELECT Name, Salary,
(SELECT AVG(Salary) FROM Employees) AS AvgSalary
FROM Employees;
Adds the company-wide average salary next to each employee.
WHERE
:SELECT Name
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Lists employees who earn more than average.
A correlated subquery refers to a column from the outer query. It is executed once for each row of the outer query.
SELECT Name, Salary
FROM Employees e
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
WHERE Department = e.Department
);
Employees earning more than the average salary of their department.
Note: These can be slower on large datasets, but powerful when used carefully.
IN
, EXISTS
, ANY
, ALL
with SubqueriesThese operators let you compare values against sets of results from subqueries.
IN
– Value is in the list returned by the subquerySELECT Name
FROM Employees
WHERE DeptID IN (SELECT DeptID FROM Departments WHERE Location = 'Hyderabad');
Employees in departments based in Hyderabad.
EXISTS
– Returns true if subquery returns any rowSELECT Name
FROM Employees e
WHERE EXISTS (
SELECT 1
FROM Projects p
WHERE p.EmployeeID = e.EmployeeID
);
Employees who are assigned to any project.
ANY
– Compares value to any result from the subquerySELECT Name, Salary
FROM Employees
WHERE Salary > ANY (SELECT Salary FROM Employees WHERE Department = 'IT');
Employees earning more than at least one person in IT.
ALL
– Compares value to all results from the subquerySELECT Name
FROM Employees
WHERE Salary > ALL (SELECT Salary FROM Employees WHERE Department = 'HR');
🔍 Employees earning more than everyone in HR.
A view is a virtual table based on the result set of a SELECT
query. It doesn’t store data physically but allows you to simplify complex queries and improve data abstraction.
You can create a view to encapsulate a frequently used SQL query.
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
CREATE VIEW HighEarners AS
SELECT Name, Salary
FROM Employees
WHERE Salary > 80000;
Now you can use the view like a regular table:
SELECT * FROM HighEarners;
Benefit | Description |
---|---|
Simplicity | Simplifies complex joins or calculations |
Security | Exposes only selected columns/rows to users |
Reusability | Write once, use multiple times |
Abstraction | Shields users from schema or business logic changes |
You can perform INSERT
, UPDATE
, or DELETE
operations on a view, but only when:
The view is based on a single table
It does not contain aggregate functions, GROUP BY
, DISTINCT
, or JOIN
UPDATE HighEarners
SET Salary = Salary + 5000
WHERE Name = 'Alice Johnson';
Complex views are often read-only unless explicitly made updatable.
DROP VIEW HighEarners;
An index is a data structure that improves the speed of data retrieval on database tables. Think of it like an index in a book—it helps locate data faster.
An index is automatically created on:
Primary keys
Unique constraints
But you can create additional indexes to optimize query performance.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
CREATE INDEX idx_lastname
ON Employees (LastName);
Type | Description |
---|---|
Single-column Index | Index on one column only |
Composite Index | Index on two or more columns |
CREATE INDEX idx_dept_salary
ON Employees (Department, Salary);
Composite indexes are used only when the leading column(s) are in the WHERE
or ORDER BY
clause.
Benefit | Explanation |
---|---|
Faster SELECT queries | Indexes allow the database to find rows more quickly |
Optimized JOINs and WHERE clauses | Especially useful in large tables |
Efficient sorting | Helps with ORDER BY , GROUP BY , and filtering |
Limitation | Explanation |
---|---|
Slower write operations | Indexes must be updated with every INSERT , UPDATE , DELETE |
Consumes storage space | Extra disk space is required |
Too many indexes = bad | Can degrade performance instead of improving it |
Index columns used frequently in WHERE, JOIN, ORDER BY
Don’t over-index—create indexes only when necessary
Use composite indexes when queries filter using multiple columns
Avoid indexing columns with high update frequency unless necessary
DROP INDEX idx_lastname ON Employees;
A stored procedure is a reusable block of SQL code stored in the database and executed as needed. It can take input/output parameters and perform logic such as data updates, validations, and reporting.
DELIMITER $$
CREATE PROCEDURE GetHighEarners(IN min_salary INT)
BEGIN
SELECT Name, Salary FROM Employees
WHERE Salary > min_salary;
END $$
DELIMITER ;
CALL GetHighEarners(60000);
IN
– Passes value into procedure
OUT
– Returns value from procedure
INOUT
– Passes in and modifies value
CREATE PROCEDURE CountEmployees(OUT emp_count INT)
BEGIN
SELECT COUNT(*) INTO emp_count FROM Employees;
END;
Functions return a single value and are ideal for encapsulating business logic.
CREATE FUNCTION GetAnnualSalary(monthly_salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
RETURN monthly_salary * 12;
SELECT Name, GetAnnualSalary(Salary) AS AnnualSalary FROM Employees;
A trigger is a special kind of stored procedure that automatically executes in response to an event (INSERT
, UPDATE
, or DELETE
) on a table.
BEFORE – Executes before the operation happens
AFTER – Executes after the operation completes
CREATE TRIGGER before_insert_employee
BEFORE INSERT ON Employees
FOR EACH ROW
SET NEW.CreatedAt = NOW();
Row-level: Executes once for each row affected (default in MySQL, PostgreSQL)
Statement-level: Executes once per SQL statement (used in Oracle)
Use Case | Example |
---|---|
Audit Logging | Track inserts or deletes in log tables |
Automatic Timestamps | Set CreatedAt , UpdatedAt values |
Data Validation | Prevent invalid data insertions |
SQL transactions ensure that a group of statements are executed safely and atomically. Either all changes succeed, or none at all.
BEGIN;
UPDATE Accounts SET Balance = Balance – 500 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 2;
COMMIT;
If any step fails, use ROLLBACK
instead of COMMIT
.
Break a transaction into parts, allowing partial rollbacks.
SAVEPOINT Save1;
-- some SQL
ROLLBACK TO Save1;
Isolation levels determine how transactions interact with each other.
Level | Description |
---|---|
READ UNCOMMITTED | Can read uncommitted data |
READ COMMITTED | Only reads committed data |
REPEATABLE READ | Consistent reads during tx |
SERIALIZABLE | Full isolation, safest |
Locks are applied to rows, pages, or tables to prevent conflicts
EXPLAIN
Use EXPLAIN
before SELECT
, UPDATE
, or DELETE
to view the query execution plan.
EXPLAIN SELECT * FROM Employees WHERE DeptID = 2;
Helps identify table scans, inefficient joins, and missing indexes.
Use indexed columns in JOIN
and WHERE
Prefer INNER JOIN
over LEFT JOIN
when possible
Avoid joining unnecessary tables
SELECT *
Fetching all columns increases memory and reduces performance. Select only required columns:
SELECT Name, Salary FROM Employees;
Use batch updates/deletes
Avoid large transactions that lock many rows
Use LIMIT for pagination
Regularly analyze and optimize tables
Archive historical data into separate tables
eLearnCourses is a trusted destination for high-quality, industry-relevant online IT training. We are committed to empowering learners and professionals with the practical skills and knowledge they need to succeed in the digital era.
Training Delivered In Cities/Countries: Hyderabad, Bangalore, Mumbai, Delhi, Chennai, Pune, Texas, California, New Jersey, Virginia, London, Dubai (UAE), Toronto, Melbourne, Sydney, Singapore, and many more.
Powered by eLearnCourses. All rights reserved.