Characteristics of SQL:
1. Simple Language: SQL is an easy-to-understand, English-
like language used for managing and querying data in
databases.
2. Data Retrieval: SQL allows users to fetch specific data
from a database using commands like SELECT.
3. Data Manipulation: SQL can modify data using
commands like INSERT, UPDATE, and DELETE.
4. Data Definition: SQL defines database structures (like
tables, indexes, and views) using commands like CREATE
and ALTER.
5. Data Control: SQL provides commands (GRANT,
REVOKE) to control data access, ensuring that only
authorized users can access or modify data.
6. Standardized Language: SQL is a standardized language,
meaning it is universally recognized and used across
different database systems.
7. Transaction Control: SQL supports transaction
management with commands like COMMIT and
ROLLBACK, ensuring data integrity during operations.
8. Scalable: SQL can handle large amounts of data, making
it suitable for both small applications and large
enterprise databases.
9. Relational-Based: SQL operates on relational databases,
where data is organized in tables with rows and
columns.
10. Declarative Language: SQL focuses on "what" data
is needed rather than "how" to get it, making it easier to
work with.
Advantages of SQL:
1. Easy to Learn: SQL has a straightforward syntax that is
close to English, making it easy to learn and use.
2. Efficient Data Retrieval: SQL allows quick and efficient
data retrieval from large databases, enabling faster
decision-making.
3. Data Manipulation: SQL can easily handle tasks like
inserting, updating, and deleting data within databases.
4. Standardized Language: SQL is a widely accepted
standard, meaning it works consistently across most
database management systems (DBMS).
5. Multiple Database Support: SQL can interact with
various databases like MySQL, PostgreSQL, Oracle, and
SQL Server.
6. Transaction Control: SQL supports transactions,
allowing you to control and manage complex operations
with commands like COMMIT and ROLLBACK.
7. Data Security: SQL has built-in security features to
protect data, allowing permissions to be set for different
users.
8. Scalability: SQL databases can handle large amounts of
data, making them suitable for applications of all sizes,
from small projects to enterprise-level solutions.
Disadvantages of SQL:
1. Complexity for Beginners: Although easy for basic tasks,
SQL can become complex for advanced queries and
large databases, which may be challenging for
beginners.
2. Limited Control Over Database: SQL is declarative,
meaning it focuses on "what" you want to retrieve, not
"how" the database does it, limiting control over query
optimization.
3. Costly Licensing: Some SQL-based DBMS (like Oracle or
SQL Server) can be costly, especially for enterprise use,
compared to open-source alternatives.
4. Hardware Demands: Large SQL databases may require
powerful hardware to handle complex queries and
maintain performance.
5. Not Ideal for All Data Types: SQL is less suitable for
handling non-relational data (like JSON or XML) and
unstructured data, which are better handled by NoSQL
databases.
6. Vendor Lock-In: Switching from one SQL database to
another can sometimes be challenging due to slight
syntax differences between vendors.
7. Rigid Schema: SQL databases require a predefined
schema, which makes it difficult to handle changes in
data structure on the fly.
SQL Literals :
In SQL, literals are fixed values used in queries, like numbers or text,
without the need for computation. Here are the main types of literals
used in SQL:
1. String Literals:
o These are text values used in SQL.
o String literals are written within single quotes, like 'Hello'
or 'SQL is great'.
o Useful when searching, inserting, or comparing text data
in queries.
2. Numeric Literals:
o These represent numbers in SQL, like integers (e.g., 100)
or decimal numbers (e.g., 45.67).
o Numeric literals are used for calculations, comparisons, or
when setting a number value in a column.
o They don’t require quotes.
3. Date and Time Literals:
o These represent specific dates or times, like '2024-11-14'
for a date or '12:30:00' for a time.
o Dates and times are enclosed in single quotes and follow
specific formats (like YYYY-MM-DD for dates).
o Useful in queries when filtering or inserting data related
to dates and times.
4. Boolean Literals:
o Boolean literals represent truth values, typically TRUE or
FALSE.
o They are useful in logical comparisons or to represent
binary (yes/no) states in queries.
5. Null Literal:
o NULL is a special literal in SQL representing the absence of
a value.
o It is used to indicate missing or unknown data.
o NULL is unique because it represents no value, not zero or
an empty string.
View in SQL :
In SQL, a view is like a virtual table that displays data from one or
more real tables in the database. It doesn’t store data itself but
shows data based on a specific query.
Key Points About Views:
1. Virtual Table: A view acts as a table but doesn’t store data. It
just displays data from other tables based on a predefined
query.
2. Simplifies Complex Queries: Views can simplify complex
queries by storing them as a view, so you can retrieve complex
data with a simple query on the view.
Let’s say we have a table called Employees that stores information
about employees in a company.
Employees Table:
EmployeeID Name Department Salary Age
1 John Doe HR 50000 30
2 Jane Smith IT 60000 25
3 Sam Brown Finance 55000 28
4 Alice Lee IT 65000 32
Creating a View:
Let’s create a view to show only employees from the IT department.
Syntax-
CREATE VIEW view_name AS
SELECT * FROM Employees WHERE Department = 'IT';
Here –
CREATE VIEW IT_Employees AS
SELECT EmployeeID, Name, Salary
FROM Employees
WHERE Department = 'IT';
Benefits of Using the View:
You don’t have to filter the Employees table for IT employees every
time; you can simply query IT_Employees.
INDEX in SQL :
In SQL, an index is a special data structure that helps speed up the retrieval of
data from a database table. It works like an index in a book, allowing the
database to find data quickly without scanning the entire table.
Example of Index:
Let’s assume we have the following Employees table:
EmployeeID Name Department Salary
1 John Doe HR 50000
2 Jane Smith IT 60000
3 Sam Brown Finance 55000
4 Alice Lee IT 65000
Syntax to Create index :
CREATE INDEX idx_name ON Employees(Name);
Without an Index:
If you want to search for an employee named "Jane Smith", the database will
check each row in the table to find it. This can take time if the table has many
rows.
With an Index:
If we create an index on the Name column, the database can quickly jump to
the location of "Jane Smith" instead of checking every row.
Now, the database can use this index to find Jane Smith much faster.
Example Query with Index:
If you search for Jane Smith:
SELECT * FROM Employees WHERE Name = 'Jane Smith';
Queries & Subqueries in SQL :
A subquery in SQL is a query inside another query. It allows you to use the
result of one query to filter or modify another query.
How Does It Work?
A subquery runs first, and its result is used by the outer (main) query. You can
think of it as asking a question and using the answer to get more information.
Key Points:
A subquery is usually enclosed in parentheses ( ).
It can be used in SELECT, INSERT, UPDATE, or DELETE queries.
It helps in situations where you need to perform multiple operations or
comparisons.
Example:
Let’s say we have two tables:
1. Employees Table:
EmployeeID Name Salary
1 John Doe 50000
2 Jane Smith 60000
3 Sam Brown 55000
4 Alice Lee 65000
2. Departments Table:
DepartmentID DepartmentName
1 HR
2 IT
3 Finance
Now, let’s say you want to find the employees whose salary is greater than the
average salary of all employees.
Without a Subquery:
You would first need to calculate the average salary and then use it in your
query.
With a Subquery:
Avgsalrary = 57500
You can calculate the average salary within the same query using a subquery:
SELECT Name, Salary FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Output:
The result will be employees who earn more than the average salary.
Name Salary
Jane Smith 60000
Alice Lee 65000
Aggregate Function in SQL :
In SQL, aggregate functions are used to perform calculations on a group of
values and return a single value. These functions are helpful when you need to
summarize or analyze data, like finding totals, averages, or counts.
Common Aggregate Functions:
1. COUNT(): Counts the number of rows in a table or group.
2. SUM(): Adds up the values of a column.
3. AVG(): Calculates the average of a column's values.
4. MAX(): Finds the highest value in a column.
5. MIN(): Finds the lowest value in a column.
Example:
Let’s take the following Employees table:
EmployeeID Name Salary
1 John Doe 50000
2 Jane Smith 60000
3 Sam Brown 55000
4 Alice Lee 65000
1. COUNT(): Count the number of employees.
SELECT COUNT(*) AS TotalEmployees FROM Employees;
Explanation:
COUNT(*) counts all rows in the Employees table.
It returns 4 because there are 4 employees.
2. SUM(): Find the total salary of all employees.
SELECT SUM(Salary) AS TotalSalary FROM Employees;
Explanation:
SUM(Salary) adds up all the salaries in the Salary column.
It returns 240000 (50000 + 60000 + 55000 + 65000).
3. AVG(): Find the average salary of employees.
SELECT AVG(Salary) AS AverageSalary FROM Employees;
Explanation:
AVG(Salary) calculates the average salary of the employees.
It returns 60000 (240000 ÷ 4).
4. MAX(): Find the highest salary.
SELECT MAX(Salary) AS HighestSalary FROM Employees;
Explanation:
MAX(Salary) finds the highest salary.
It returns 65000, which is Alice Lee’s salary.
5. MIN(): Find the lowest salary.
SELECT MIN(Salary) AS LowestSalary FROM Employees;
Explanation:
MIN(Salary) finds the lowest salary.
It returns 50000, which is John Doe’s salary.
Cursor in SQL :
A cursor is a database object used to retrieve, manipulate, and navigate
through a result set (the rows returned by a query) one row at a time. Cursors
are useful when you need to process each row individually in complex
operations.
Imagine you have a list of employees, and you want to check each employee
one by one to see if their salary is above a certain amount.
A cursor helps you do that in SQL. It lets you move through the rows one at a
time, like flipping through pages in a book.
We have an Employees table:
EmployeeID Name Salary
1 John Doe 50000
2 Jane Smith 60000
3 Sam Brown 55000
If we want to print each employee's name and salary one by one, we can use
a cursor.
Steps:
1. Declare a cursor that selects the data we want.
DECLARE cursor_name CURSOR FOR SELECT * FROM
table_name
2. Open the cursor to start using it.
OPEN cursor_connection
3. Fetch each row (i.e., employee's name and salary) one by one.
FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE n/RELATIVE n
FROM cursor_name
4. Close the cursor when done. CLOSE cursor_name
There are two types of cursors :
a. Implicit cursors :
i. These are created by default when DML statements like, INSERT,
UPDATE, and DELETE statements are executed.
ii. They are also created when a SELECT statement that returns just
one row is executed.
b. Explicit cursors :
i. They must be created when we are executing a SELECT statement
that returns more than one row.
ii. When we fetch a row the current row position moves to next row.
Trigger in SQL :
A trigger is a special type of SQL procedure that automatically runs
(or "fires") when a certain event happens in the database.
A trigger is a procedure (code segment) that is executed
automatically when some specific events occur in a table/view of a
database.
Types of Triggers:
1. DDL Trigger
2. DML Trigger
3. Logon Trigger
DDL Triggers :
The Data Definition Language (DDL) command events such as Create_table,
Create_view, drop_table, Drop_view, and Alter_table cause the DDL triggers to
be activated.
create trigger safety
on database
for
create_table,alter_table,drop_table
as
print 'you can not create,drop and alter table In database.
DML Triggers :
The Data uses manipulation Language (DML) command events that begin with
Insert, Update, and Delete set off the DML triggers. corresponding to
insert_table, update_view, and delete_table.
create trigger deep
on emp
for
insert,update ,delete
as
print 'you can not insert,update and delete this table i'
rollback;
DML Triggers are of two types :
1. After Trigger –
. AFTER Trigger Example:
Let’s say we want to automatically log every time a salary is updated in the
Employees table into a separate SalaryChanges table.
First, create the SalaryChanges table:
CREATE TABLE SalaryChanges (
EmployeeID INT,
OldSalary INT,
NewSalary INT,
ChangeDate DATETIME
);
Now, create the AFTER Trigger:
Create an AFTER Trigger
CREATE TRIGGER LogSalaryChangeAfterUpdate
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
INSERT INTO SalaryChanges (EmployeeID, OldSalary, NewSalary,
ChangeDate)
VALUES (OLD.EmployeeID, OLD.Salary, NEW.Salary, NOW());
END;
2. Instead of Trigger –
INSTEAD OF Trigger Example:
Let’s say we want to prevent direct deletion of an employee record from the
Employees table, but instead, mark the employee as "inactive" in a Status
column instead of deleting them.
First, modify the Employees table to add a Status column:
ALTER TABLE Employees ADD Status VARCHAR(10) DEFAULT 'Active';
Now, create the INSTEAD OF Trigger:
Create an INSTEAD OF Trigger
CREATE TRIGGER PreventDeleteInsteadOfDelete
INSTEAD OF DELETE ON Employees
FOR EACH ROW
BEGIN
UPDATE Employees
SET Status = 'Inactive'
WHERE EmployeeID = OLD.EmployeeID;
END;
Logon Triggers :
Logon Triggers are used to monitor and control user logins to the SQL Server
instance. These triggers allow you to perform specific actions when a user logs
in, such as enforcing security policies, auditing, or restricting access.
CREATE TRIGGER LogLogin
ON ALL SERVER
FOR LOGON
AS
BEGIN
PRINT 'User has logged in: ' + ORIGINAL_LOGIN();
END;
Procedures in SQL/PL SQL :
What is a Procedure in PL/SQL?
A procedure in PL/SQL is a set of SQL and PL/SQL statements that perform a
specific task. You can think of it like a recipe: you define the steps, and
whenever you need to follow those steps, you just call (or execute) the
procedure. Procedures help you save time and avoid writing the same SQL
code repeatedly.
Key Features of Procedures:
Reusable: Once created, you can call a procedure any number of times.
Encapsulate Logic: Procedures allow you to group multiple SQL
commands and PL/SQL code into a single unit.
Can have Parameters: Procedures can accept input (IN), provide output
(OUT), or both (IN OUT) parameters.
Basic Syntax of a Procedure:
Here’s how you create a procedure in PL/SQL:
CREATE PROCEDURE procedure_name
[parameter_name datatype, ...]
AS
BEGIN
-- PL/SQL code (SQL statements or logic)
END;
Example of a Simple Procedure:
Suppose we want to create a procedure that adds a new employee to an
Employees table.
CREATE PROCEDURE AddEmployee (
p_emp_id IN INT,
p_name IN VARCHAR,
p_salary IN DECIMAL
)
AS
BEGIN
INSERT INTO Employees (EmployeeID, Name, Salary)
VALUES (p_emp_id, p_name, p_salary);
END;
In this example:
Input Parameters (p_emp_id, p_name, p_salary) are values that you
pass when calling the procedure.
The procedure inserts a new employee into the Employees table.
Calling the Procedure:
EXEC AddEmployee(101, 'John Doe', 50000);
This command will insert a new employee with ID 101, name John Doe, and
salary 50000 into the table.
Advantages of Procedures:
1. Code Reusability:
o You write the code once in the procedure and can reuse it
multiple times.
o Reduces redundancy in code.
2. Modular Approach:
o Breaks down a large program into smaller, manageable chunks
(procedures), making it easier to maintain.
3. Improved Performance:
o Compiling once: The procedure is compiled once and stored in the
database. So, it runs faster each time you call it.
4. Better Security:
o You can control access to the underlying data. Users can execute
the procedure without directly accessing the tables.
5. Easier Maintenance:
o If you need to change a part of your logic, you only need to
change the procedure, not every place in your application where
the logic is used.
Disadvantages of Procedures:
1. Complexity:
o Procedures can sometimes become complex if they have too
many parameters or complicated logic, making them harder to
understand and maintain.
2. Limited Flexibility:
o Procedures are typically designed for specific tasks. They can be
harder to adapt if your logic changes significantly.
3. Harder Debugging:
o Debugging a procedure can be more challenging because the logic
is hidden inside the procedure. You may need to write additional
logging or error-handling code to track issues.
4. Overhead in Management:
o Managing many procedures in large databases can become
difficult, especially if the procedures interact with each other or if
they change frequently.
Difference Between Embedded SQL And Dynamic SQL :