Final DBMS Unit 5
Final DBMS Unit 5
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.
1. CREATE:
o The CREATE statement is used to define new database objects, such as tables,
indexes, views, and schemas.
o Example:
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:
3. DROP:
o The DROP statement removes an existing database object, such as a table, index,
or view, permanently from the database.
o Example:
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:
5. RENAME:
o The RENAME statement changes the name of a database object, such as a table
or column.
o Example:
6. COMMENT:
o Example:
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.
• 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.
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 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 * 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:
UPDATE Employees
WHERE EmployeeID = 1;
This updates the Salary for the employee with EmployeeID = 1 to 65,000.
• Multiple Columns Update:
UPDATE Employees
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:
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:
FROM Employees
GROUP BY Department
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;
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;