0% found this document useful (0 votes)
15 views17 pages

Final DBMS Unit 5

Uploaded by

tinayetakundwa
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)
15 views17 pages

Final DBMS Unit 5

Uploaded by

tinayetakundwa
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
You are on page 1/ 17

Unit – 5 SQL (Structured Query Language)

Introduction to SQL
SQL (Structured Query Language) is a standardized programming language used for managing
and manipulating databases. It is used to communicate with relational databases by performing
various operations like data retrieval, insertion, updating, and deletion. SQL is essential for
interacting with databases like MySQL, PostgreSQL, Oracle, and SQL Server.

Overview of SQL
SQL operates through queries to interact with databases. The core operations that SQL
performs include:

• Data Definition Language (DDL): Defines the structure of the database, such
as CREATE, ALTER, and DROP.
Data Definition Language (DDL) refers to a set of SQL commands used to define, modify, and
manage database structures such as tables, schemas, indexes, and constraints. DDL commands
primarily deal with the creation, alteration, and removal of database objects. These operations
are essential for setting up the architecture of a database and maintaining its structure over
time.

Here are the main components of DDL:

1. CREATE:

o The CREATE statement is used to define new database objects, such as tables,
indexes, views, and schemas.

o Example:

CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

FirstName VARCHAR(50),

LastName VARCHAR(50),
HireDate DATE

);

2. ALTER:
o The ALTER statement modifies an existing database object, such as a table. It can
add, delete, or modify columns and constraints.

o Example:

ALTER TABLE Employees

ADD Email VARCHAR(100);

3. DROP:

o The DROP statement removes an existing database object, such as a table, index,
or view, permanently from the database.

o Example:

DROP TABLE Employees;

4. TRUNCATE:

o The TRUNCATE statement removes all rows from a table, but it does not remove
the table itself. It is typically faster than using DELETE because it does not log
individual row deletions.

o Example:

TRUNCATE TABLE Employees;

5. RENAME:

o The RENAME statement changes the name of a database object, such as a table
or column.

o Example:

RENAME TABLE Employees TO Staff;

6. COMMENT:

o The COMMENT statement is used to add a description to a database object (like


a table or column) to provide more context about the object.

o Example:

COMMENT ON COLUMN Employees.EmployeeID IS 'Unique identifier for each employee';

Characteristics of DDL:

• Permanent changes: Once executed, DDL statements make permanent changes to the
database structure.

• Implicit commit: In most database systems, DDL statements implicitly commit changes
to the database, meaning the changes cannot be rolled back using transaction control
commands like ROLLBACK.
• Structural impact: DDL commands alter the database schema and its objects,
influencing how data is stored, accessed, and managed.

Common DDL operations:

• Table creation (CREATE TABLE)

• Table modification (ALTER TABLE)

• Table deletion (DROP TABLE)

• Clearing a table's data (TRUNCATE TABLE)

• Data Manipulation Language (DML): Handles data retrieval and


manipulation, such as SELECT, INSERT, UPDATE, and DELETE.
Data Manipulation Language (DML) refers to the subset of SQL (Structured Query
Language) used for managing and manipulating data within the database. DML operations are
primarily focused on querying, inserting, updating, and deleting data in the database tables. Unlike
Data Definition Language (DDL), which deals with the structure of the database, DML focuses on the
actual data stored within the tables.

Here are the key DML commands:


1. SELECT
• The SELECT statement is used to retrieve data from one or more tables. It is the most
commonly used DML command for querying data.
• Example:
SELECT * FROM Employees;
This command retrieves all columns and rows from the Employees table.
2. INSERT
• The INSERT statement is used to add new rows of data into a table. You can insert data
into all or specific columns.
• Example (inserting all columns):
INSERT INTO Employees (EmployeeID, FirstName, LastName, HireDate)
VALUES (1, 'John', 'Doe', '2024-12-01');
• Example (inserting specific columns):
INSERT INTO Employees (FirstName, LastName)
VALUES ('Jane', 'Smith');
3. UPDATE
• The UPDATE statement is used to modify the existing data in one or more rows of a
table. It is usually combined with a WHERE clause to specify which rows should be
updated.
• Example:
UPDATE Employees
SET FirstName = 'John', LastName = 'Smith'
WHERE EmployeeID = 1;
This updates the FirstName and LastName for the employee with EmployeeID = 1.
4. DELETE
• The DELETE statement is used to remove rows from a table. Like the UPDATE
statement, it is usually combined with a WHERE clause to specify which rows should
be deleted.
• Example:
DELETE FROM Employees
WHERE EmployeeID = 1;
This deletes the row for the employee with EmployeeID = 1 from the Employees table.
5. MERGE (sometimes called UPSERT)
• The MERGE statement is a combination of INSERT, UPDATE, and DELETE. It allows you
to perform different actions based on whether a record already exists in a table or not.
It is useful for synchronizing data between tables.
• Example:
MERGE INTO Employees AS target
USING NewEmployees AS source
ON target.EmployeeID = source.EmployeeID
WHEN MATCHED THEN
UPDATE SET target.FirstName = source.FirstName
WHEN NOT MATCHED THEN
INSERT (EmployeeID, FirstName, LastName)
VALUES (source.EmployeeID, source.FirstName, source.LastName);
Characteristics of DML:
• Data-centric: DML focuses on the data contained in the database tables, not the
structure of the database itself.
• Transaction-based: DML operations can be rolled back or committed as part of a
transaction. Unlike DDL commands, which usually commit changes automatically, DML
commands can be grouped into transactions that are either committed (COMMIT) or
undone (ROLLBACK).
• Query-driven: Many DML operations (like SELECT) are designed for querying data,
making DML essential for data retrieval and reporting.
Common Use Cases for DML:
• Retrieving data for reports or analysis.
• Inserting new records for users, products, or other entities.
• Updating existing records based on changes (e.g., address or salary updates).
• Deleting obsolete or incorrect records.
In summary, DML plays a key role in managing the content of a database by allowing users to
insert, modify, delete, and retrieve data. These operations are fundamental for most
applications that interact with databases.

• Data Control Language (DCL): Manages access rights to the database, like
GRANT and REVOKE.
Data Control Language (DCL) refers to a subset of SQL (Structured Query Language) that
deals with permissions and access control to the data in a database. DCL commands are used to grant
or revoke user privileges to perform specific actions on database objects such as tables, views, or
procedures.

The two primary DCL commands are:


1. GRANT
• The GRANT statement is used to give specific privileges to a user or a group of users.
These privileges can include the ability to select, insert, update, delete, and execute
on various database objects.
• Example:
GRANT SELECT, INSERT ON Employees TO UserName;
This command gives the user UserName the ability to SELECT (read) and INSERT (add data)
into the Employees table.
• You can also grant permissions to roles or multiple users at once:
GRANT ALL PRIVILEGES ON Employees TO RoleName;
2. REVOKE
• The REVOKE statement is used to remove previously granted privileges from a user or
group of users. It essentially takes back the access or permission that was granted via
the GRANT command.
• Example:
REVOKE INSERT ON Employees FROM UserName;
This command removes the INSERT privilege (the ability to add records) from the user
UserName on the Employees table.
• You can also revoke multiple privileges:
REVOKE SELECT, DELETE ON Employees FROM UserName;
Characteristics of DCL:
• Security-focused: DCL is primarily concerned with the security and access control of
the database. It ensures that users or roles have the necessary permissions to interact
with the database objects.
• User-specific: DCL commands typically target specific users or roles and allow
database administrators to manage who can access and modify the data.
• Irreversible: Once REVOKE is applied, the privileges are taken away and cannot be
undone unless explicitly re-granted.
Common Privileges Granted:
• SELECT: The privilege to retrieve data from a table or view.
• INSERT: The privilege to insert new rows into a table.
• UPDATE: The privilege to modify existing data in a table.
• DELETE: The privilege to delete rows from a table.
• EXECUTE: The privilege to execute stored procedures or functions.
• ALL PRIVILEGES: A catch-all privilege that provides all possible permissions (can be
granted or revoked for tables, databases, etc.).
Common Use Cases for DCL:
• User management: Assigning and revoking privileges to control who can access or
modify certain data.
• Security control: Limiting user access to sensitive data by granting permissions only to
specific users or roles.
• Database administration: Ensuring proper access control policies are enforced in the
system for compliance or security reasons.
Example Use Case:
1. A database administrator might grant a user the ability to read from a table (using
GRANT SELECT), but deny them the ability to modify or delete the data.
2. Later, if the user's role changes or they no longer need access, the administrator can
revoke the SELECT privilege using the REVOKE command.
In summary, DCL plays a crucial role in managing database security by controlling user access
to data. It ensures that only authorized individuals can perform specific actions on the
database, thereby protecting sensitive information.

• Transaction Control Language (TCL): Deals with transactions, such


as COMMIT, ROLLBACK, and SAVEPOINT.
Transaction Control Language (TCL) is a subset of SQL used to manage transactions within a
database. A transaction is a sequence of one or more SQL operations executed as a single unit.
TCL commands are used to control the transaction's flow, ensuring data integrity and
consistency. They allow you to commit changes to the database or roll them back depending
on the situation.

The key TCL commands are:


1. COMMIT
• The COMMIT statement is used to save all the changes made during the
current transaction to the database. Once committed, the changes become
permanent and cannot be rolled back.
• Example:
COMMIT;
This command commits the current transaction, making all changes made during the
transaction (like INSERT, UPDATE, or DELETE) permanent in the database.
2. ROLLBACK
• The ROLLBACK statement is used to undo any changes made during the current
transaction. It reverts the database to its state before the transaction started.
• Example:
ROLLBACK;
If an error occurs or if a certain condition isn't met, you can use this command to
discard all changes made in the current transaction.
3. SAVEPOINT
• The SAVEPOINT statement is used to set a savepoint within a transaction. A
savepoint is a point in the transaction to which you can later roll back. It allows
for partial rollback, meaning you can undo changes made after the savepoint
without rolling back the entire transaction.
• Example:
SAVEPOINT savepoint_name;
This command sets a savepoint named savepoint_name within the current
transaction.
4. ROLLBACK TO SAVEPOINT
• The ROLLBACK TO SAVEPOINT statement is used to roll back the transaction to
a specific savepoint, undoing all changes made after that point but preserving
changes made before it.
• Example:
ROLLBACK TO SAVEPOINT savepoint_name;
This command undoes all changes made after the specified savepoint, but leaves the
rest of the transaction intact.
5. SET TRANSACTION
• The SET TRANSACTION statement is used to configure the properties of the
current transaction. It allows you to set the isolation level, whether the
transaction should be read-only, and other transaction-related parameters.
• Example:
SET TRANSACTION READ WRITE;
This command sets the transaction to allow both reads and writes. Alternatively, you
can use READ ONLY to make the transaction read-only.
Characteristics of TCL:
• Atomicity: Ensures that a series of operations within a transaction are
executed as a single unit. If any part of the transaction fails, the whole
transaction is rolled back.
• Consistency: Ensures that the database moves from one consistent state to
another after each transaction.
• Isolation: Ensures that operations of one transaction are isolated from others,
preventing conflicts (achieved through transaction isolation levels).
• Durability: Once a transaction is committed, its changes are permanent, even
in the case of a system failure.
Transaction Lifecycle:
1. Start a transaction: A transaction begins when an operation is performed (such
as INSERT, UPDATE, DELETE, or SELECT), and changes are made to the
database.
2. Execute operations: A series of SQL commands are executed within the
transaction.
3. Commit or Rollback: After all operations are executed, the transaction is either
committed (making changes permanent) or rolled back (undoing all changes).
Common Use Cases for TCL:
• Error handling: If a transaction encounters an error midway, the changes can
be rolled back to avoid incomplete or incorrect data being committed.
• Multiple updates: When performing multiple updates or changes in one
transaction, TCL ensures that either all changes are saved, or none of them are,
preserving data integrity.
• Partial undo: Using SAVEPOINT and ROLLBACK TO SAVEPOINT, you can undo
part of the transaction while retaining other changes, useful for complex
operations.
Example:
Let’s say you are transferring money between two bank accounts. You might need to
ensure that the deduction from one account and the addition to another are part of
the same transaction.
BEGIN TRANSACTION;

UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1;


UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2;

COMMIT;
If something goes wrong (e.g., the second update fails), you can roll back the entire
transaction:
ROLLBACK;
This ensures that the balance deduction is undone, and no money is lost.
Summary:
TCL is crucial for ensuring the integrity and consistency of data in databases by
allowing the user to control transactions effectively. Through COMMIT, ROLLBACK,
SAVEPOINT, and SET TRANSACTION, TCL ensures that all changes to the database are
performed correctly and that any errors can be managed without leaving the database
in an inconsistent state.

Basic Queries in SQL


Basic queries in SQL focus on retrieving data from a database:
1. SELECT: The primary query to retrieve data.
2. SELECT column1, column2 FROM table_name;
3. WHERE: Filters records based on conditions.
4. SELECT * FROM employees WHERE age > 30;
5. ORDER BY: Sorts results based on a column.
6. SELECT * FROM products ORDER BY price DESC;
7. DISTINCT: Retrieves unique values.
8. SELECT DISTINCT city FROM customers;

Basic SQL Queries are the foundation of interacting with a database. These queries are used to perform
operations like retrieving, inserting, updating, and deleting data. Here's an overview of some of the most
common SQL queries you'll encounter when working with a relational database:
1. SELECT Query
The SELECT statement is used to retrieve data from one or more tables. It's the most basic and frequently
used query in SQL.
• Basic SELECT Query:

SELECT column1, column2, ... FROM table_name;


• Example:

SELECT FirstName, LastName FROM Employees;


This will retrieve the FirstName and LastName columns from the Employees table.
• Selecting All Columns:

SELECT * FROM Employees;


The * wildcard selects all columns from the Employees table.
2. WHERE Clause
The WHERE clause is used to filter records based on a specific condition.
• Basic SELECT with WHERE:

SELECT * FROM Employees WHERE Department = 'Sales';


This will retrieve all rows from the Employees table where the Department column is equal to 'Sales'.
• Multiple Conditions with AND/OR:

SELECT * FROM Employees WHERE Department = 'Sales' AND Salary > 50000;
This will return all employees in the 'Sales' department with a salary greater than 50,000.
3. INSERT INTO Query
The INSERT INTO statement is used to add new rows of data to a table.
• Basic INSERT Query:

INSERT INTO Employees (FirstName, LastName, Department, Salary)

VALUES ('John', 'Doe', 'Sales', 60000);


This inserts a new row into the Employees table with the provided values for FirstName, LastName,
Department, and Salary.
4. UPDATE Query
The UPDATE statement is used to modify existing records in a table.
• Basic UPDATE Query:

UPDATE Employees

SET Salary = 65000

WHERE EmployeeID = 1;
This updates the Salary for the employee with EmployeeID = 1 to 65,000.
• Multiple Columns Update:

UPDATE Employees

SET Salary = 70000, Department = 'Marketing'


WHERE EmployeeID = 2;
This updates both Salary and Department for the employee with EmployeeID = 2.
5. DELETE Query
The DELETE statement is used to remove records from a table.
• Basic DELETE Query:

DELETE FROM Employees WHERE EmployeeID = 3;


This deletes the row where EmployeeID = 3 from the Employees table.
• Delete All Rows in a Table:

DELETE FROM Employees;


This will delete all rows in the Employees table but will not remove the table itself.
6. ORDER BY Clause
The ORDER BY clause is used to sort the result set by one or more columns, either in ascending (ASC) or
descending (DESC) order.
• Basic ORDER BY Query:

SELECT * FROM Employees ORDER BY Salary DESC;


This retrieves all employees sorted by Salary in descending order.
• Ordering by Multiple Columns:

SELECT * FROM Employees ORDER BY Department ASC, Salary DESC;


This orders the employees first by Department in ascending order, and within each department, by Salary
in descending order.
7. LIMIT Clause (or TOP in some databases)
The LIMIT clause is used to specify the number of records to return in the result set. (In some databases
like SQL Server, you use TOP instead.)
• Basic LIMIT Query:

SELECT * FROM Employees LIMIT 5;


This retrieves the first 5 rows from the Employees table.
• LIMIT with OFFSET (Pagination):

SELECT * FROM Employees LIMIT 5 OFFSET 10;


This retrieves 5 rows starting from the 11th row (pagination).
8. DISTINCT Keyword
The DISTINCT keyword is used to return unique (non-duplicate) values in a result set.
• Basic DISTINCT Query:

SELECT DISTINCT Department FROM Employees;


This retrieves a list of unique departments from the Employees table, removing any duplicates.
9. LIKE Operator
The LIKE operator is used to search for a specified pattern in a column, typically with wildcard characters
such as % and _.
• Basic LIKE Query:

SELECT * FROM Employees WHERE FirstName LIKE 'J%';


This retrieves all employees whose FirstName starts with 'J'.
• Using Wildcards:
o %: Represents zero or more characters.
o _: Represents a single character.

SELECT * FROM Employees WHERE LastName LIKE '_oe'; -- Finds 'Joe', 'Doe', etc.
10. BETWEEN Operator
The BETWEEN operator is used to filter the result set within a specified range.
• Basic BETWEEN Query:

SELECT * FROM Employees WHERE Salary BETWEEN 50000 AND 70000;


This retrieves employees whose salary is between 50,000 and 70,000.
11. GROUP BY Clause
The GROUP BY clause is used to group rows that have the same values into summary rows, like calculating
the sum or average for each group.
• Basic GROUP BY Query:

SELECT Department, AVG(Salary) AS AverageSalary FROM Employees

GROUP BY Department;
This calculates the average salary for each department in the Employees table.
12. HAVING Clause
The HAVING clause is used to filter groups created by GROUP BY, and it works similarly to the WHERE
clause but operates on aggregated data.
• Basic HAVING Query:

SELECT Department, AVG(Salary) AS AverageSalary

FROM Employees

GROUP BY Department

HAVING AVG(Salary) > 60000;


This retrieves departments where the average salary is greater than 60,000.

Summary of Basic SQL Queries:


• SELECT: Retrieve data from one or more tables.
• INSERT INTO: Add new rows to a table.
• UPDATE: Modify existing data in a table.
• DELETE: Remove data from a table.
• ORDER BY: Sort the result set.
• WHERE: Filter records based on conditions.
• LIMIT: Limit the number of rows returned.
• DISTINCT: Retrieve unique values.
• LIKE: Search for a pattern.
• BETWEEN: Filter results within a range.
• GROUP BY: Group records and perform aggregate functions.
• HAVING: Filter groups created by GROUP BY.

Advanced Queries in SQL


Advanced SQL queries can involve multiple conditions and operations, such as:
1. JOIN: Combines rows from two or more tables based on related columns.
2. SELECT employees.name, departments.department_name
3. FROM employees
4. JOIN departments ON employees.department_id = departments.department_id;
5. SUBQUERIES: Nested queries inside a main query.
6. SELECT name FROM employees
7. WHERE department_id = (SELECT department_id FROM departments WHERE
department_name = 'HR');
8. GROUP BY: Groups rows sharing a property to apply aggregate functions.
9. SELECT department, COUNT(*) FROM employees GROUP BY department;
10. HAVING: Filters groups after GROUP BY (used with aggregate functions).
11. SELECT department, COUNT(*) FROM employees GROUP BY department HAVING
COUNT(*) > 10;

Functions in SQL
SQL offers various functions for performing calculations and transformations on data:
1. Aggregate Functions: Operate on multiple rows of data and return a single value.
o COUNT(), SUM(), AVG(), MIN(), MAX()
2. SELECT AVG(salary) FROM employees;
3. String Functions: Manipulate string data.
o CONCAT(), SUBSTRING(), UPPER(), LOWER(), TRIM()
4. SELECT CONCAT(first_name, ' ', last_name) FROM employees;
5. Date Functions: Handle date and time values.
o NOW(), DATE_ADD(), DATE_SUB(), DATEDIFF()
6. SELECT DATE_ADD(order_date, INTERVAL 5 DAY) FROM orders;

Basic Data Retrieval


This refers to the foundational operation in SQL: extracting data from tables using the SELECT
statement. It includes:
• Retrieving all columns: SELECT * FROM table_name;
• Retrieving specific columns: SELECT column1, column2 FROM table_name;
• Filtering data using conditions: SELECT column1 FROM table WHERE condition;

Aggregation
Aggregation refers to summarizing or grouping data based on certain attributes using functions
like:
1. COUNT(): Counts the number of rows.
2. SUM(): Adds up numerical values.
3. AVG(): Calculates the average value.
4. MIN() / MAX(): Finds the minimum or maximum value in a group.
Example:
SELECT department, COUNT(*) AS num_employees
FROM employees

GROUP BY department;

Categorization
Categorization involves grouping data into categories based on conditions or range of values:
1. CASE WHEN: Used for conditional categorization.
2. SELECT name,
3. CASE
4. WHEN age < 20 THEN 'Teen'
5. WHEN age BETWEEN 20 AND 40 THEN 'Adult'
6. ELSE 'Senior'
7. END AS age_group
8. FROM employees;
9. GROUP BY: Used to categorize and aggregate data based on specific columns.
10. SELECT department, AVG(salary) FROM employees GROUP BY department;

Updates in SQL
SQL allows modifications to the data in tables using the following statements:
1. UPDATE: Modifies existing records.
2. UPDATE employees SET salary = 50000 WHERE employee_id = 3;
3. DELETE: Removes records from a table.
4. DELETE FROM employees WHERE age < 30;
5. INSERT INTO: Adds new records to a table.
6. INSERT INTO employees (name, age, department_id) VALUES ('John Doe', 28, 2);

Views in SQL
A view is a virtual table based on the result set of a SQL query. It allows users to simplify
complex queries and organize data in a structured manner. A view does not store data itself but
retrieves data from underlying tables.
1. Creating a View:
2. CREATE VIEW employee_view AS
3. SELECT name, age, department FROM employees WHERE age > 30;
4. Using a View:
5. SELECT * FROM employee_view;

Different Types of Views


There are two main types of views:
1. Simple Views: Represent data from a single table or a basic query without complex joins
or aggregations.
2. Complex Views: Involve multiple tables, joins, subqueries, and aggregate functions.

Theoretical Updatability of Views


• Updatable Views: Views that allow data modifications like INSERT, UPDATE, or DELETE.
Generally, simple views are updatable as long as they map directly to a single table.
• Non-updatable Views: Complex views, such as those involving multiple tables, joins,
aggregate functions, or distinct clauses, are generally not updatable, as changes cannot
be applied back to the underlying data directly.
For a view to be updatable, it must adhere to certain rules like:
• The view must select columns from only one table.
• The view must not use aggregate functions or group by clauses.
• There must be no DISTINCT, JOIN, or UNION operations.

You might also like