DBMS Iib III
DBMS Iib III
Types
of SQL Commands. SQL Operators and Their Procedure. Tables, Views and Indexes. Queries and
Sub Queries. Aggregate Func ons. Insert, Update and Delete Opera ons, Joins, Unions,
Intersec on, Minus, Cursors, Triggers, Procedures in SQL/PL SQL.
___________ .
SQL :
SQL (Structured Query Language) is used to perform opera ons on the records stored in the
database, such as upda ng, inser ng, dele ng, etc.
History of SQL
Paper "A Rela onal Model of Data for Large Shared Data Banks" was published by "E.F.
Codd" in 1970.
1970s: Developed by ‘Raymond and Donald’ IBM as SEQUEL.
1986-1987: Standardized by ANSI and ISO.
1990s: Became widely used in RDBMS like Oracle and MySQL.
2000s: Con nued enhancements, adding new features like XML and recursive queries.
2010s & Beyond: Added support for JSON and temporal data.
SQL vs NO-SQL
SQL No-SQL
3. These databases are ver cally scalable. 3. These databases are horizontally scalable.
4. The database type of SQL is in the form of 4. The database type of No-SQL is in
tables, i.e., in rows and columns. documents, key-value, and graphs.
5. It follows the ACID model. (Atomicity, 5. It follows the BASE model. (Basically
Consistency, Isola on, Durability) Available, So state, Eventual consistency)
6. Complex queries are easily managed in the 6. NoSQL databases cannot handle complex
SQL database. queries.
Defining the Structure: Use CREATE statements to set up databases and tables.
Inser ng Data: Use INSERT to add new records to tables.
Querying Data: Use SELECT to retrieve data from tables, with various clauses for filtering
and sor ng.
Upda ng Data: Use UPDATE to modify exis ng records.
Dele ng Data: Use DELETE to remove records from tables.
| 40 |
Managing Transac ons: Use BEGIN, COMMIT, and ROLLBACK to control transac on
integrity.
Crea ng Indexes: Use CREATE INDEX to improve query performance.
Process of SQL:
Triggers in SQL
Triggers in SQL are special stored procedures that automa cally execute or "trigger" in
response to certain events on a par cular table or view, such as INSERT, UPDATE, or
DELETE opera ons.
Components:
Event: The event that ac vates the trigger (INSERT, UPDATE, DELETE).
Condi on: The condi on that must be met for the trigger to execute.
Ac on: The set of SQL statements that are executed when the trigger is ac vated.
Types of Triggers:
1. Before Triggers: Execute before an INSERT, UPDATE, or DELETE opera on.
CREATE TRIGGER before_update_customers
BEFORE UPDATE ON Customers
FOR EACH ROW
BEGIN
SET NEW.last_updated = NOW();
END;
| 41 |
2. A er Triggers: Execute a er an INSERT, UPDATE, or DELETE opera on.
CREATE TRIGGER a er_delete_orders
AFTER DELETE ON Orders
FOR EACH ROW
BEGIN
INSERT INTO ArchiveOrders (order_id, deleted_at)
VALUES (OLD.order_id, NOW());
END;
3. Instead of Triggers: Execute in place of INSERT, UPDATE, or DELETE opera ons, o en used
with views.
Query
A query is a request for informa on or data retrieval from a DBMS, typically wri en in
SQL, to extract specific data by specifying criteria or condi ons. User can decide how to
use informa on logically.
Type of Database Query:
1. Select Query: Retrieves data from one or more tables.
Example: SELECT * FROM Employees;
2. Ac on Query: ac ons on the data such as inser ng, upda ng, or dele ng records.
Examples: INSERT INTO Employees (id, name) VALUES (1, 'Alice');
UPDATE Employees SET name = 'Alice Johnson' WHERE id = 1;
DELETE FROM Employees WHERE id = 1;
3. Join Query: Combines rows from two or more tables based on a related column.
SELECT Employees.name, Projects.project_name
FROM Employees
JOIN Projects ON Employees.id = Projects.employee_id;
4. Aggregate Query: Use aggregate func ons (average, count, min, max and sum).
Computes summary sta s cs.
Example: SELECT AVG(salary) FROM Employees;
5. Parameter Query: Requires input from the user to execute specific condi on.
Example: SELECT * FROM Employees WHERE id = ?;
6. Cross-tab Query: Summarizes data in a matrix format.
Example: Crea ng pivot tables in SQL.
| 42 |
SQL Data Types
Data types are used to represent the nature of the data that can be stored in the database
table. Some important SQL data types:
Numeric Data Types:
1. INT: Integer values, no decimal points. (123, -456, …)
2. FLOAT: Floa ng-point number, supports decimal points. (123.45, -678.90, …)
3. DECIMAL: Fixed-point number, precise decimal values. (123.45, …)
4. BIGINT: Large integer values. (1234567890, …)
String Data Types:
1. VARCHAR: Variable-length strings. ('Hello', 'World',..)
2. CHAR: Fixed-length strings.
3. TEXT: Large text blocks.
Date and Time Data Types:
1. DATE: Date values (YYYY-MM-DD).
2. TIME: Time values (HH:MM:SS).
3. DATETIME: Combina on of date and me.
Boolean Data Type:
1. BOOLEAN: True or False values.
Other Data Types:
1. BLOB: Binary large object, for storing binary data.
2. ENUM: A string object with a value chosen from a list of permi ed values.
3. SET: Similar to ENUM, but can hold mul ple values.
SQL Literals: Literals in SQL are fixed values that are used directly in SQL statements. They can be
of various data types, including numeric, string, date/ me, and boolean. Literals are
useful for specifying constant values in queries, such as condi ons in WHERE …
Example:
Numeric Literals: SELECT * FROM Products WHERE price > 100;
String Literals: SELECT * FROM Employees WHERE first_name = 'John';
Date/Time Literals: SELECT * FROM Orders WHERE order_date = '2023-11-17';
Boolean Literals: SELECT * FROM Projects WHERE is_ac ve = TRUE;
SQL Constraints: Constraints use with the CREATE TABLE statement, or with the ALTER TABLE
statement. Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table.
Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combina on of a NOT NULL and UNIQUE. Uniquely iden fies each
row in a table
• FOREIGN KEY - Prevents ac ons that would destroy links between tables
• CHECK - Ensures that the values in a column sa sfies a specific condi on
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
| 43 |
Type of SQL Statement: DDL, DML, TCL, DCL
DDL (Data Defini on Language): that define the structure and schema of a database.
Ex CREATE, ALTER, DROP, DESC, TRUNCATE, RENAME, COMMENT…
CREATE: Creates a new table, view, or other database object.
Example: CREATE TABLE Employees (id INT, name VARCHAR(100));
ALTER: Modifies an exis ng database object, such as a table.
Example: ALTER TABLE Employees ADD COLUMN salary DECIMAL(10,2);
ALTER TABLE Employees CHANGE Phone Mobile VARCHAR(15);
DROP: Deletes a table, view, or other database object.
Example: DROP TABLE Employees;
DESC: Describe detailed informa on about the columns in a table.
Example: DESC Employees;
TRUNCATE: Delete all rows from table. This opera on is faster than DELETE.
TRUNCATE cannot be rolled back.
Example: TRUNCATE TABLE Employees;
RENAME: change the name of a table or index.
Example: RENAME TABLE Employees TO Workers;
COMMENT: Add comments to the data dictionary
Example: COMMENT 'comment-TEXT' ON TABLE Employees;
DML (Data Manipula on Language): used to manipulate data stored in a database.
Ex. SELECT, INSERT, UPDATE, DELETE, LOCK, CALL, EXPLAIN PLAN…
DML are basically two types:
i. Procedural DML – Nondeclara ve DML –
request to specify what data are needed and how to get those data.
ii. Declara ve DML – Nonprocedural DML –
it is also called as Nonprocedural DML, require to specify what data are
needed without specifying how to get
SELECT: Retrieves data (rows) from the database.
Example: SELECT * FROM Employees;
INSERT: Adds new data (rows) into the database.
Example: INSERT INTO Employees (id, name) VALUES (1, 'Alice');
UPDATE: Modifies exis ng data (rows) within the database.
Example: UPDATE Employees SET name = 'Ankit' WHERE id = 1;
DELETE: Removes data (rows) from the database.
Example: DELETE FROM Employees WHERE id = 1;
TCL (Transac on Control Language): used to manage transac ons in a database.
Transac ons group a set of tasks into a single execu on unit. Each transac on begins with a
specific task and ends when all the tasks in the group are successfully completed. If any of the
tasks fail, the transac on fails. Transac on has only two results: success or failure.
BEGIN: Starts a transac on.
COMMIT: Saves the changes made by a transac on.
ROLLBACK: Undoes the changes made by a transac on.
SAVEPOINT: Sets savepoint within a transac on. par al rollbacks to savepoint
Example: BEGIN;
INSERT INTO Students (first_name, last_name) VALUES ('Alice', 'Johnson');
SAVEPOINT savepoint1;
INSERT INTO Students (first_name, last_name) VALUES ('Bob', 'Williams');
ROLLBACK TO savepoint1;
COMMIT;
| 44 |
DCL (Data Control Language): used to control access to data in the database.
GRANT: Gives users access privileges (SELECT, INSERT, UPDATE, DELETE)
to the database. You can use ‘ALL PRIVILEGES’ for all.
Example: GRANT SELECT, INSERT ON Employees TO ‘User1’;
GRANT ALL PRIVILEGES ON Students TO ‘User2’;
REVOKE: Removes access privileges from the database.
Example: REVOKE INSERT ON Employees FROM ‘User1’;
SQL OPERATORS: SQL operators are used to perform opera ons on data in SQL queries.
1. Arithme c Operators: Perform mathema cal opera ons on numerical data
Addi on (+): Adds two values.
SELECT basic+td+da+hra AS total FROM Salary;
Subtrac on (-): Subtracts one value from another.
SELECT price–loss AS Different FROM Shop;
Mul plica on (*): Mul plies two values.
SELECT price*quan ty AS Cost FROM Shop;
Division (/): Divides one value by another.
SELECT 10 / 5;
Modulus (%): Returns the remainder of a division.
SELECT 10 % 3;
2. Comparison Operators: Compare two values and return a Boolean result (TRUE or FALSE).
Equal to (=): Checks if two values are equal.
Not equal to (<> or !=): Checks if two values are not equal.
Greater than (>): Checks if one value is greater than another.
Less than (<): Checks if one value is less than another.
Greater than or equal to (>=): Checks if value is greater than or equal to another.
Less than or equal to (<=): Checks if one value is less than or equal to another.
Example: SELECT * FROM Students WHERE score >= 75;
3. Logical Operators: Used to combine mul ple condi ons in a WHERE clause.
AND: Returns TRUE if both condi ons are true.
OR: Returns TRUE if at least one of the condi ons is true.
NOT: Negates a condi on.
Example: SELECT * FROM Students WHERE NOT grade = 'F';
SELECT * FROM Students WHERE grade = 'A' OR grade = 'B';
4. Bitwise Operators: Perform bit manipula on on integer data.
AND (&): Performs a bitwise AND opera on. Example: SELECT 6 & 3;
OR (|): Performs a bitwise OR opera on. Example: SELECT 6 | 3;
XOR (^): Performs a bitwise XOR opera on. Example: SELECT 6 ^ 3;
NOT (~): Performs a bitwise NOT opera on. Example: SELECT ~6;
5. Other Operators
LIKE: Used for pa ern matching. Pa ern searching
% Stand for any number of characters, _ stand for one character.
SELECT * FROM Students WHERE first_name LIKE '_J%';
SELECT * FROM Students WHERE first_name NOT LIKE '_J%';
IN: Checks if a value matches any value in a list.
SELECT * FROM Students WHERE grade IN ('A', 'B', 'C');
SELECT * FROM Students WHERE grade NOT IN ('A', 'B', 'C');
BETWEEN: Checks if a value falls within a specified range. range searching
| 45 |
SELECT * FROM Students WHERE score BETWEEN 70 AND 90;
SELECT * FROM Students WHERE score NOT BETWEEN 70 AND 90;
IS NULL: Checks if a value is NULL.
SELECT * FROM Students WHERE email IS NULL;
IS NOT NULL: Checks if a value is not NULL.
SELECT * FROM Students WHERE email IS NOT NULL;
SYNTAX 1:
SELECT [DISTINCT] column_name1, column_name2, .…, column_nameN
[FROM table_name]
[WHERE condi on]
[ORDER BY order_column_name1 [ASC | DESC], ....] [LIMIT number [ OFFSET skip]];
SYNTAX 2:
SELECT column1, aggregate_func on(column2)
FROM table_name
[WHERE condi on]
GROUP BY column1
[HAVING condi on_with_aggregate_func on(column2)]
[ORDER BY aggregate_func on(column2) [DESC | ASC] …];
SQL COMMANDS
1. USE Statement
This SQL statement selects the exis ng SQL database. Before performing the opera ons on
the database table, you have to select the database from the mul ple exis ng databases.
Syntax USE database_name;
Example USE CollegeDB;
Example:
CREATE TABLE City (
c_id INT PRIMARY KEY AUTO_INCREMENT,
c_name VARCHAR(50) DEFAULT 'Ghaziabad',
pincode INT NOT NULL
);
| 46 |
course_id INT,
city_id INT,
PRIMARY KEY(student_id),
FOREIGN KEY(city_id) REFERENCES City(c_id),
UNIQUE (aadhar, apaar_id),
CHECK(age>4 AND age < 18),
CHECK (aadhar REGEXP '^[0-9]{12}$'),
);
In this create query : REGEXP regular expression pa ern that matches exactly 12 digits.
3. DESCRIBE Statement
This SQL statement tells something about the specified table or view in the query.
Syntax:
DESCRIBE table_name | view_name;
Example :
DESCRIBE Student;
Result:
Field Type Null Key Default Extra
student_id INT NO PRI NULL auto_increment
| 47 |
5. INSERT INTO clluse:
used to add new rows of data into a table.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO Students (name, age, course_id, city_id, city, DOJ)
VALUES ('Ankit yadav', 21, 101, 1, ‘Ghaziabad’, '2002-05-14');
Mul ple records
INSERT INTO Students (name, age, course_id, city_id, city, DOJ)
VALUES ('Suresh Shah', 18, 101, 1, ‘Delhi’, '2000-05-15');
VALUES ('Anoop Singh', 20, 101, 1, ‘Varanasi’, '2003-06-17');
VALUES ('Ravi Panday', 22, 101, 1, ‘Kanpur’, '2001-04-19');
6. SELECT clause:
Fetch all columns and rows from a table.
SELECT * FROM Students;
Fetch specific columns from a table.
SELECT name, mob, email FROM Students;
7. Aggregate func on
SELECT MAX(age) FROM Student;
SELECT MIN(age) FROM Student;
SELECT AVG(age) FROM Student;
SELECT COUNT(id) FROM student WHERE address=’ghaziabad’;
SELECT SUM(recipt_fee) AS Total_fee_recived FROM student WHERE date = '2024-11-15';
8. DISTINCT clause: Remove duplicate rows in the result set.
SELECT DISTINCT id, name FROM Students;
9. WHERE clause:
Filter records based on specific (records value) condi ons.
SELECT name, mob
FROM Students
WHERE address = ‘GZB’ OR address=’NDLS’;
10. ORDER BY clause:
Sort ascending or descending the results by one or more columns. (by default Ascending ASC)
SELECT name, address FROM Students ORDER BY name;
SELECT name, f_name FROM Students ORDER BY name ASC, f_name DESC;
SELECT name, mob FROM Students WHERE address = ‘GZB’ ORDER BY name ASC;
11. LIMIT clause:
The LIMIT clause specifies the maximum number of rows to return.
SELECT columns FROM table LIMIT number_of_rows;
SELECT * FROM Students LIMIT 10;
SELECT name, marks FROM Result ORDER BY marks DESC LIMIT 5;
12. OFFSET clause:
This clause specifies the number of rows to skip before star ng to return rows. It is o en used in
conjunc on with LIMIT. Useful in Pagina on (web page shoe number of records per page).
SELECT name, marks FROM Result ORDER BY marks DESC LIMIT 5 OFFSET 3;
13. GROUP BY clause:
Group rows that have the same values in specified columns
SELECT region, SUM(sales_amount) AS total_sales
FROM Sales
| 48 |
GROUP BY region
14. HAVING clause:
Filter groups based on a condi on (used with GROUP BY).
SELECT region, SUM(sales_amount) AS total_sales
FROM Sales
GROUP BY region
HAVING SUM(sales_anount) > 10000;
If specific product, then use WHERE clause:
SELECT region, SUM (sales_amount) AS total_sales
FROM Sales
WHERE product=’mobile’
GROUP BY region
HAVING SUM(sales_anount) > 10000;
15. UPDATE Statement:
This SQL statement changes or modifies the stored data in the SQL database.
UPDATE table_name
SET column_name1 = new_value_1, column_name2 = new_value_2, ....
[ WHERE CONDITION ];
16. DELETE Statement:
This SQL statement deletes the stored data from the SQL database.
DELETE FROM table_name
[ WHERE CONDITION ];
17. DROP Statement
This SQL statement deletes or removes the table and the structure, views, permissions, and
triggers associated with that table.
Delete table:
DROP TABLE Students;
Delete database:
DROP DATABASE CollegeDB;
Delete column:
ALTER TABLE Students DROP COLUMN email;
Delete index:
DROP INDEX idx_email ON Students;
Delete view:
DROP VIEW EventGroup;
Delete Foreign key:
ALTER TABLE Students DROP FOREIGN KEY _city;
18. TRUNCATE TABLE Statement
This SQL statement deletes all the stored records from the table of the SQL database.
TRUNCATE TABLE table_name;
19. JOIN:
Combine rows from two or more tables based on a related column.
Main Types of Join:
Natural Join (no conditional check, join same name all columns: implicit join)
Inner Join (combine where join condition is met, explicit specification of join columns)
Equi join
Non Equi join OR Conditional join OR theta join
Self-join
Outer Join
| 49 |
Left outer join OR left join
Right outer join OR right join
Full outer join OR outer join
Cross Join
| 50 |
What is VIEW?
A view is a virtual rela on, whose contents are derived from already exis ng rela ons and
it does not exist in physical form.
The contents of view are determined by execu ng a query based on any rela on and it
does not form the part of database schema. Each me a view is referred to, its contents
are derived from the rela ons on which it is based.
A view can be used like any other rela on that is, it can be queried, inserted into, deleted
from and joined with other rela ons or views. Views can be based on more than one
rela on and such views are known as complex views.
Syntax for crea ng view:
CREATE VIEW view_name
AS SELECT * FROM table_name
WHERE Category IN (‘a ribute1’, ‘a ribute2’);
Example : Command to create a view consis ng of a ributes Book_ tle, Category, Price and P_ID
of the BOOK rela on, Pname and State of the PUBLISHER rela on can be specified as
CREATE VIEW BOOK_3
AS SELECT BOOK_ tle, Category, Price, BOOK.P_ID, Pname, State
FROM BOOK, PUBLISHER
WHERE BOOK.P_ID = PUBLISHER.P_ID;
What is INDEXES?
Indexes are special lookup tables that the database search engine can use to speed up
data retrieval. An index helps to speed up SELECT queries and WHERE clauses, but it slows
down data input, with the UPDATE and the INSERT statements.
Indexes can be created or dropped with no effect on the data.
Indexes are used to retrieve data from the database more quickly. The users cannot see
the indexes; they are just used to speed up searches/ queries.
Syntax:
CREATE INDEX index_name
ON TABLE column;
where the index is the name given to that index and TABLE is the name of the table on which that
index is created and column is the name of that column for which it is applied.
Syntax for crea ng unique index is :
CREATE UNIQUE INDEX index_name
ON TABLE column;
To remove an index from the data dic onary by using the DROP INDEX command.
Syntax:
DROP INDEX index_name;
| 51 |
Type of Indexing:
1. Single level indexing: it is created for the main file, marking the end of the
indexing process
A. Primary indexing: index on primary key. Index file have two column, first
primary key and second pointer (based address of block). Number of
entries in this index file = number of block acquired by the main file
(Sparse indexing).
B. Clustered indexing: index on some non key a ribute. Number of entries in
this index file = number of unique value of the a ribute on which indexing
is done.it is the example of sparse as well as dense indexing.
C. Secondary indexing: main file is ordered according to the a ribute on
which indexing is done (unordered). It can be done on key or non key
a ribute. Number of entries in the index file is same as the number of
entries in the main file (Dense indexing).
2. Mul ple level indexing: involves crea ng an index for the index file and con nually
repea ng this procedure un l only a single block.
Dense vs Sparse indexing :
Dense indexing : an entry in the index file for every search key value in main file. Require
more space to store index record itself. some me number of record main file > number of
search key in main file, for example if search key is repeated.
Sparse indexing: if index entry is created only for some records of the main file, then it is
called sparse index. Number of index entries in the index file < number of records in the
main file.
NOTE: dense and sparse are not complementary to each other, some mes it is possible
that a record is both dense and sparse.
What is SUB-QUERY:
A sub-query is a SQL query nested inside a larger query. Sub-queries must be enclosed
within parenthesis. The sub-query can be used with the SELECT, INSERT, UPDATE, or
DELETE statement along with the operators like =, >, <, >=, <=, IN, ANY, ALL, BETWEEN.
A sub-query is usually added within the WHERE clause of another SQL SELECT statement.
A sub-query is also called an inner query while the statement containing a sub-query is
also called an outer query. The inner query executes first before its parent query so that
the result of an inner query can be passed to the outer query.
Syntax of SQL sub-query : A sub-query with the IN operator,
SELECT column_names
FROM table_name1
WHERE column_name IN (SELECT column_name FROM table_name2 WHERE condi on);
Example : We have the following two tables ‘student’ and ‘marks’ with common field ‘StudentID’.
Student (StudentID, Name), Marks(StudentID,Total_marks)
Now considering table ‘Student’, we want to write a query to iden fy all students who get more
marks than the student whose StudentID is ‘V002’, but we do not know the marks of ‘V002’.
So, consider another table ‘Marks’ containing total marks of the student and apply query
considering both tables.
SQL code with sub-query :
SELECT a.StudentID, a.Name, b.Total_marks
FROM student a, marks b
WHERE a.StudentID = b.StudentID AND b.Total_marks >
(SELECT Total_marks
| 52 |
FROM marks
WHERE StudentID = ‘V002’);
Dynamic SQL :
on the other hand, enables the construc on of SQL statements dynamically at run me. It
allows the crea on of more flexible and adaptable applica ons, where SQL statements
can be generated and executed based on changing condi ons or user inputs. This makes
it possible to create more complex and adaptable database opera ons, though it might
be more suscep ble to SQL injec on a acks if not handled carefully.
Preparing a dynamic SQL statement compiles it, and subsequent uses of the prepared
statement use the compiled version. SQL defines standards for embedding dynamic SQL
calls in a host language, such as C, as in the following example,
char * sqlprog = “update account set balance = balance * 1.05
where account_number = ?”;
EXEC SQL prepare dynprog from : sqlprog;
char account[10] = “A-101”;
EXEC SQL execute dynprog using : account
| 53 |
1. Query Submission: The user submits a query to the database management system
(DBMS).
2. Query Parsing: The DBMS parses the query to check for syntax errors and to iden fy
the query type (e.g., SELECT, INSERT, UPDATE, DELETE).
3. Query Op miza on: The DBMS op mizes the query to improve performance. This
involves selec ng the most efficient access method, join order, and other query execu on
parameters.
4. Query Execu on: The DBMS executes the op mized query. This involves accessing the
relevant data, performing any necessary calcula ons, and returning the results to the
user.
5. Query Results: The DBMS returns the query results to the user.
Detailed Steps:
1. Parser: The parser breaks the query into its cons tuent parts, such as keywords,
iden fiers, and operators.
2. Seman c Analyzer: The seman c analyser checks the query for seman c errors, such as
referencing non-existent tables or columns.
3. Query Op mizer: The query op mizer selects the most efficient query execu on plan.
This involves es ma ng the cost of different plans and selec ng the one with the lowest
cost.
4. Query Executor: The query executor executes the op mized query plan. This involves
accessing the relevant data, performing any necessary calcula ons, and returning the
results to the user.
5. Result Forma er: The result forma er formats the query results into a readable
format.
| 54 |
i) Find the average age of the sailor who are eligible for vo ng for each ra ng level that
has at least two sailors.
ii) Find the name of sailors who have reserved both red and a green boat.
ii) Find the sailor_id of sailors who have reserved a red boat.
Q.4. Consider the following employee database
Employee(emp_no, name, emp_city),
company(emp_no, company_name, salary).
i.) Write a SQL query to display Employee name and company name.
ii) Write a SQL query to display employee name, employee city, company name and salary
of all the employee whose salary > 10000.
iii) Write a query to display all the employees working in ‘XYZ’company.
Q.5. Consider the following employee database
Employee(empName, street, city),
work (empName, companyName, salary),
company(companyNmae, city),
manages(empName, management).
i.) Find the name of all employees who work for First Bank corpora on.
ii) Find the names, street addresses and ci es of residence of all employees who work for
First Bank corpora on and earn more than 200000 per annum.
iii) Find the names of all employees in this database who live in the same city as the
company for which they work.
Q6. Consider the following rela ons (primary keys are underlined).
Account(acc_no, balance, branch_name),
depositor(acc_no, cust_no),
Customer(cust_no, name, city),
loan(loan_no, amt, branch_name),
borrower(cust_no, loan_no).
i) Find all customer_no and loan_no who have a loan at the ‘Perryridge’ branch.
ii) Find all the customer who have an account but no loan at the bank.
iii) Find branch_name and average account balance where average account balance is
grater then 1000.
Q7. Consider the following rela ons (primary keys are underlined).
Employee (emp_id, emp_name, mangr_id, hire_date, salary, commission, dept_id)
Department (dept_id, dept_name, loca on_id),
Loca on (loca on_id, address, city).
i) Show all employee whose salary is grater then 6000.
ii) Show all employee whose name contain ‘A’ like ‘BLAKE’.
iii) Show all employee whose hire-date day is ‘Monday’
Ans. (SELECT * FROM Employee WHERE DAYNAME(hire_date) = 'Monday')
iv) Show the employee name salary with there department name.
v) Show the employee name and manager name where employee are hired before
manager.
vi) Show the employees whose city is Ghaziabad.
v) Show all department number and department name where there are no employee.
Q.7. Explain query language and its type.
Q.8. Write short note on SQL. Explain various characteris cs of SQL.
Q.9. Explain union, intersec on and minus opera on with example?
Q.10. Briefly describe Join operator and its type with example in SQL.
Q.11. Describe triggers. Explain different type of triggers in SQL. Why Triggers are needed?
| 55 |
Unit: 3
Data Base Design & Normaliza on: Func onal dependencies, normal forms, first, second, third
normal forms, BCNF, inclusion dependence, loss less join decomposi ons, normaliza on using
FD, MVD, and JDs, alterna ve approaches to database design
Data Base Design
Database design and normaliza on are fundamental aspects of crea ng an efficient,
scalable, and robust database system. They ensure that the data is stored in a structured
way, reducing redundancy and improving data integrity.
Database Design
1. Requirements Analysis
Define the Purpose: Understand the needs and requirements of the database. What kind
of data will be stored? How will it be used?
Gather Requirements: This includes understanding the business processes, data flow, and
repor ng needs.
2. Conceptual Design
En ty-Rela onship (ER) Diagram: Create an ER diagram to visually represent the en es,
a ributes, and rela onships. This helps in understanding the data structure and the
rela onships between different data.
3. Logical Design
Define Tables and Columns: Convert the ER diagram into a logical model. Define the
tables, columns, data types, and constraints.
Primary and Foreign Keys: Iden fy primary keys for unique iden fica on of records and
foreign keys to establish rela onships between tables.
4. Physical Design
Database Schema: Create the database schema based on the logical design. This involves
crea ng tables, indexes, views, and other database objects.
Normaliza on: Apply normaliza on techniques to eliminate redundancy and ensure data
integrity.
Determinant (X): The a ribute(s) on the le side of the func onal dependency. It
determines the values of the dependent a ribute.
Dependent (Y): The a ribute(s) on the right side of the func onal dependency. Its values
are determined by the determinant.
| 56 |
Type of Func onal Dependency:
1. Full Func onal Dependency
AB then, non prime a ribute B is dependent on candidate key A.
2. Par al Func onal Dependency
R(A,B,C,D) if ABD In this case AB is candidate key
and AC part of candidate key A determinates non prime a ribute C.
A Par al Func onal Dependency occurs when, non prime a ribute is dependent only on a
part of candidate key.
3. Transi ve Dependency
A transi ve dependency occurs when there is an indirect rela onship between a ributes.
Non prime a ribute to non prime a ribute.
R(A,B,C) if A→B and BC (only A is prime a ribute B,C are non prime a ribute)
Thus, non prime a ribute B determinates non prime a ributes C.
FD Importance
Ensuring Data Integrity: Func onal dependencies help ensure data consistency by
enforcing constraints that must hold true across the database.
Normaliza on: They are essen al for the process of normaliza on, which aims to reduce
data redundancy and eliminate undesirable characteris cs like anomalies in data
opera ons.
Schema Design: Understanding func onal dependencies helps in designing the schema of
a rela onal database, ensuring that it is efficient and effec ve in querying and managing
data.
| 57 |
Closure of a set of func onal Dependency:
The closure of a set of func onal dependencies (FDs) is a fundamental concept in rela onal
database theory. It involves finding all FDs that can be inferred from a given set of FDs using
Armstrong's axioms. The closure helps in determining key a ributes, performing normaliza on,
and ensuring data integrity.
Steps to Compute the Closure
1. Ini alize:
o Start with the given set of func onal dependencies FF.
2. Apply Armstrong's Axioms:
o Use the following axioms repeatedly to infer new func onal dependencies:
1. Reflexivity: If Y⊆X, then X→Y
2. Augmenta on: If X→Y, then XZ→YZ for any Z.
3. Transi vity: If X→Y and Y→Z, then X→Z.
3. Add Inferred FDs:
o Add the newly inferred func onal dependencies to the set un l no more new
dependencies can be inferred.
Armstrong’s Axioms: also known as Func onal dependency Axions or Deriva on Rule or
Inference Axioms or Logical Deduc on Rule:
Armstrong axioms are a set of rules used to infer func onal dependencies in a rela onal
database. They were first introduced by William W. Armstrong in 1974.
1. Reflexivity:
X={PQRS} and Y={PQ} then XY and YY or XX
If X is a set of a ributes, then X → X. This axiom states that every set of a ributes is
func onally dependent on itself.
3. Transi vity:
X={PQRS} and Y={PQ} and Z={Q}
If X → Y and Y → Z, then X → Z. This axiom states that if X func onally determines Y, and Y
func onally determines Z, then X func onally determines Z.
4. Union:
If X → Y and X → Z, then X →YZ.
5. Decomposi on or Project rule:
If X → YZ then X →Y and XZ.
6. Pseudo Transi ve rule:
X={PQRS}, Y={PQ}, Z={T}, W={PQT}, and XZ={PQRST}
If X → Y and YZ → W, then XZ →W.
7. Composi on rule:
X={PQRS}, Y={PQ}, Z={STU}, W={ST} , YZ={PQST}
If X Y and Z W, then XZ YW.
Anomalies Related To Rela onal Database : Rela onal databases, while powerful and widely
used, can some mes encounter certain anomalies or issues during data opera ons. These
anomalies can affect the integrity, consistency, and efficiency of the data.
| 58 |
1. Inser on Anomaly
An independent pice of informa on can not be recorded into rela on unless an irrelevant
informa on must be inserted together at the same me.
This usually happens when data is being inserted into a table that includes fields that are
par ally dependent on the primary key.
Example:
StudentID StudentName CourseID CourseName
1 John Doe 101 Math
2 Jane Smith 102 Science
If you want to add a new course to the database without enrolling any students, an
inser on anomaly would prevent this because the StudentID and StudentName fields
cannot be le empty.
2. Dele on Anomaly
The dele on of a pice of informa on uninten onally removes other informa on.
Anomaly occurs when the dele on of certain data results in the unintended loss of
addi onal data that should be retained.
Example:
StudentID StudentName CourseID CourseName
1 John Doe 101 Math
If John Doe is the only student enrolled in Math, dele ng his record would also delete
informa on about the Math course.
3. Modifica on Anomaly or Update Anomaly
An update anomaly occurs when mul ple instances of the same data exist, and upda ng
one instance requires upda ng all instances to maintain consistency. This can happen
when redundant data is stored in mul ple places.
Example: In the student-course table, if the course name changes from "Math" to
"Mathema cs," every instance of the course name must be updated:
StudentID StudentName CourseID CourseName
1 John Doe 101 Mathema cs
2 Jane Smith 102 Science
| 61 |
A er 5NF:
Suppliers-Parts: Parts-Projects: Suppliers-Projects:
SupplierID PartID PartID ProjectID SupplierID ProjectID
1 101 101 1001 1 1001
2 102 102 1002 2 1002
1 103 103 1003 1 1003
4NF and 5NF: Address mul -valued dependencies and join dependencies. These are less
common in prac ce but important for certain complex scenarios.
Importance of Normal Forms OR Purpose of Normaliza on:
Reduce Redundancy: Helps in elimina ng duplicate data.
Improve Data Integrity: Ensures the accuracy and consistency of data over its lifecycle.
Ease of Maintenance: Simplifies database updates and maintenance.
Enhanced Performance: Improves query performance by structuring data efficiently.
INCLUSION DEPENDENCE
Inclusion dependence, also commonly referred to as referen al integrity constraint in
rela onal database management, ensures that a set of values in one dataset (usually a
subset) must exist within another set of values in a different dataset. This concept is
integral to maintaining the consistency and validity of data across related tables.
Key Concepts
1. Defini on:
o An inclusion dependency constraint ensures that every value in one set A (typically
a foreign key column) must also be present in another set B (typically a primary
key column).
o Formally, if set A is included in set B, it is denoted as A⊆B.
2. Prac cal Applica on:
o Foreign Key Constraint: A prac cal example of inclusion dependence is the foreign
key rela onship between tables. For example, in a student-course database, every
student_id in the enrollments table must exist in the students table.
3. Types:
o Simple Inclusion Dependence: Direct inclusion of one a ribute set within another.
o Mul valued Inclusion Dependence: Where mul ple values from one set relate to
values in another set.
Examples
Example 1: Simple Inclusion Dependence
Consider a Students table and an Enrollments table:
Students Table
student_id student_name
1 John Doe
2 Jane Smith
Enrollments Table
enrollment_id student_id course_id
100 1 CS101
101 2 MA101
The student_id in the Enrollments table must exist in the Students table, ensuring
referen al integrity.
TeamMembers Table
member_id project_id
101 1
102 1
103 2
Here, each project_id in the TeamMembers table should exist in the Projects table,
allowing mul ple team members to be assigned to each project.
| 63 |
When joined on the common a ribute, the original rela on R is reconstructed:
A B C D
1 2 3 4
2 3 4 5
| 64 |
In this example, the Student ID a ribute has a mul valued dependency on the Course ID
a ribute, because for each Student ID, there are mul ple Course IDs associated with it.
Types of Mul valued Dependencies:
1. Trivial MVD: An MVD is trivial if the dependent a ribute is a subset of the determining
a ribute.
2. Non-Trivial MVD: An MVD is non-trivial if the dependent a ribute is not a subset of the
determining a ribute.
Importance of Mul valued Dependencies:
1. Database Design: MVDs play a crucial role in database design, as they help to iden fy
rela onships between a ributes.
2. Data Normaliza on: MVDs are used to normalize data and eliminate data redundancy.
3. Query Op miza on: MVDs can be used to op mize queries by reducing the number
of joins required.
Significance:
MVDs are important for ensuring data integrity and reducing redundancy.
They lead to Fourth Normal Form (4NF), which removes mul valued dependencies.
| 65 |
Use Case: Great for visualizing and designing the database schema at a high level.
Example: Diagrams showing en es like Customer, Order, and Product, and their
rela onships.
2. Object-Oriented Database Design
Concept: Uses objects, similar to object-oriented programming, to represent data and
rela onships.
Use Case: Ideal for applica ons that require complex data representa ons and
opera ons.
Example: Classes like Customer, Order, and Product with methods and a ributes.
3. Unified Modeling Language (UML)
Concept: A standardized modeling language used to create detailed diagrams of so ware
systems.
Use Case: Useful for both database design and so ware development.
Example: Use case diagrams, class diagrams, and ac vity diagrams.
4. Normaliza on Theory
Concept: Focuses on reducing redundancy and ensuring data dependencies are properly
enforced.
Use Case: Ensures efficient and consistent data storage.
Example: Applying normal forms (1NF, 2NF, 3NF, etc.) to decompose tables.
5. Domain-Key Normal Form (DKNF)
Concept: Ensures that all constraints are domain constraints or key constraints.
Use Case: Provides a more rigorous approach to normaliza on.
Example: Ensuring that all a ributes are either part of a key or constrained by domain
rules.
6. Knowledge-Based Approaches
Concept: Uses knowledge bases to assist in the design process.
Use Case: Helps in automa ng parts of the design process and providing expert guidance.
Example: Tools that suggest schema designs based on predefined knowledge bases.
Other Approach: Fuzzy Database Models, Geographical Informa on Systems (GIS),…
Each approach has its own advantages and is suitable for different types of applica ons. The
choice of approach depends on the specific requirements of the project, such as the complexity
of data, the need for spa al analysis, or the level of precision required.
| 66 |
BD then B+=D total (B)+= BD
then (B)+= BD
Super Key : Set of a ribute using which we can iden fy each tuple uniquely is called super key.
Candidate Key: Minimal set of a ributes using which we can iden fy each tuple uniquely is
called Candidate key. A super key is called candidate key if it’s no proper subset is a super key.
Also called minimal super key.
Prime a ribute : a ribute that are member of at least one candidate key are called Prime
a ribute. and other a ribute that are not member of candidate key called non prime a ribute.
R(ABCD) and F{ABCD} then A and B is prime a ribute. and C,D are non prime a ribute.
Composite Key: it is a key compound of more then one column some me it is known as
concatenated key. ABC then AB is composit key.
Secondary key : it is a key used to speed up the search and retrieval contrary to primary key does
not necessary contain unique values. Ex. Gender , class, sec on, …
| 67 |
C+=C,D,A,B then C is a candidate key.
D+=D,A,B,C then D is a candidate key.
Then all (A,B,C,D) are candidate key.
Q. Find all candidate key:
R(ABCDE)
F{AB, BCD, EC, DA}
Ans:
A+=A,B then A is not candidate key.
In this FD only A,B,C,D are determined but E are not determine
Thus E must present in Candidate key.
{AE}+=A,B,E,C,D then AE is a candidate key.
+
{BE} =B,E,C,D,A then BE is a candidate key.
+
{CE} =C,D,A,B,E then CE is a candidate key.
{DE}+=E,D,A,B,C then DE is a candidate key.
Then all (AE,BE,CE,DE) are candidate key.
Q. Find candidate key in given op on:
R(ABCDEF) and F{CF, EA, ECD, AB}
(a) CD
(b) EC
(c) AE
(d) AC
Ans:
{CD}+ ={C,F,D}
{EC}+ ={E,C,F,D,A,B}
{AE}+ ={A,E,B}
{AC}+ ={A,C,B,F}
Thus, EC is candidate key Op on (b) EC
Q. Which of the following FD is not implied by the given set:
R(A,B,C,D,E) and F{AB, AC, CDE, BD, EA}
(a) CDAC
(b) BDCD
(c) BCCD
(d) ACBC
Ans:
{CD}+ ={C,D,E,A,B}
{BD}+ ={D,B}
{BC}+ ={B,C,D,E,A}
{AC}+ ={A,C,B,D,E}
Thus, Op on (b) BDCD is not implied.
Equivalence of two FD sets:
F1 and F2 are equivalent if
F1+ = F2+
Or F1 ⊆ F2+ and F2 ⊆ F1+
Q. R(ABCD) And FDs F1{AC, CB, BD}, F2{ABD, CAD, BC} Are they equivalent?
Ans:
F2 cover F1 F1 F2 F1 cover F2
A+=A,B,D,C AC ABD A+=C,A,B
B+=C,B,D,A BD BC B+=B,D
C+=C,A,D CB CAD C+=C,B,D
| 68 |
F2 cover F1 And F1 cover F2 not equal then Both FD are not equivalent.
Q. R(A,C,D,E,H) And FDs F1{AC, ACD, EAD, EH}, F2{ACD, EAH} Find which FD is
super set?
Ans:
F2 cover F1 F1 F2 F1 cover F2
+
A =A,C,D AC ACD A+=C,D,A
AC+=A,C,D ACD
E =E,A,H,C,D EAD EAH E+=E,A,H,C,D
+
EH
In F2 cover F1 A+ and {AC}+ are equal
F2 cover F1 And F1 cover F2 equal then Both FD are equivalent.
We know that in Set theory A ⊆ B and B ⊆ A then A=B then F1=F2
Find Lossless / lossy
Q. Rela on R=(V,W,X,Y,Z) with FD: ZV, WY, VWX, is the decomposi on of R1 and R2 is
lossless? R1=(V,W,X) and R2=(V,Y,Z)
V W X Y Z
R1 a1 a2 a3 b14 b15
R2 a1 b22 b23 a4 a5
Ans. A er applying the FD VWX then new matrix :
V W X Y Z
R1 a1 a2 a3 b14 b15
R2 a1 b22 \ a2 b23\a3 a4 a5
Now, all elements of R2 are fill with a’s. Now we stop.
Hence it is a loss less join decomposi on.
Q. Rela on R=(V,W,X,Y,Z) with FD: ZV, WY, XYZ, VWX is the decomposi on of R1 and R2
is lossless? R1=(V,W,X) and R2=(X,Y,Z)
V W X Y Z
R1 a1 a2 a3 b14 b15
R2 B21 b22 a3 a4 a5
Ans. A er applying the FD WY and ZV then new matrix :
V W X Y Z
R1 a1 a2 a3 b14 \ a4 b15
R2 a1 a a3 a4 a5
Now, all elements of R2 are not fill with a’s.
Hence it is a lossy join decomposi on.
Q. Rela on R=(A,B,C,D,E,F,G,H) with FD: ABC, BCD, EF, GF, HA, FGH is the
decomposi on of R1 and R2 is lossless? R1=(A,B,C,D) R2=(A,B,C,E,F) and R3=(A,D,F,G,H)
A B C D E F G H
R1 a1 a2 a3 a4 b15 b16 b17 b18
R2 a2 a2 a3 b24 a5 a6 b27 b28
R3 a1 b32 33 a4 b35 a6 a7 a8
Ans. A er applying the FD BCD then new matrix :
| 69 |
A B C D E F G H
R1 a1 a2 a3 a4 b15 b16 b17 b18
R2 a2 a2 a3 b24 \a4 a5 a6 b27 b28
R3 a1 b32 33 a4 b35 a6 a7 a8
Now, all elements of R2 are not fill with a’s.
Hence it is a lossy join decomposi on.
| 70 |