Dbms Mid-2 Unit-3 Longs Answers
Dbms Mid-2 Unit-3 Longs Answers
1. Union ( ∪ )
The Union operator combines the results of two queries
into a single result set. It returns all the rows from both
relations, removing duplicates.
Description:
Combines tuples from two relations, excluding
duplicates.
Both relations must have the same number of attributes
and corresponding attribute domains (data types).
Syntax:
SELECT column1, column2, ... FROM table1
UNION
SELECT column1, column2, ... FROM table2;
Example:
SELECT EmployeeID FROM Employees1
UNION
SELECT EmployeeID FROM Employees2;
This query will return all distinct EmployeeIDs from both
Employees1 and Employees2.
2. Intersection ( ∩ )
The Intersection operator returns only the rows that are
common to both relations.
Description:
Returns the common tuples between two relations.
Both relations must have the same number of attributes
and corresponding attribute domains.
Syntax:
SELECT column1, column2, ... FROM table1
INTERSECT
SELECT column1, column2, ... FROM table2;
Example:
SELECT EmployeeID FROM Employees1
INTERSECT
SELECT EmployeeID FROM Employees2;
This query will return only the EmployeeIDs that exist in
both Employees1 and Employees2.
3. Difference ( − or MINUS )
The Difference operator (also called Minus in some SQL
implementations) returns the rows that are in the first
relation but not in the second.
Description:
Returns tuples that are in the first relation but not in the
second.
Both relations must have the same number of attributes
and corresponding attribute domains.
Syntax:
SELECT column1, column2, ... FROM table1
MINUS
SELECT column1, column2, ... FROM table2;
Example:
SELECT EmployeeID FROM Employees1
MINUS
SELECT EmployeeID FROM Employees2;
This query will return EmployeeIDs that are in
Employees1 but not in Employees2.
4. Cartesian Product ( × )
The Cartesian Product operator returns the combined
rows of two relations. Each row from the first relation is
paired with each row from the second relation, producing
a new relation with all possible combinations.
Description:
It combines every tuple of the first relation with every
tuple of the second relation.
The result will have the number of columns equal to the
sum of columns of both relations.
Syntax:
SELECT * FROM table1
CROSS JOIN table2;
Example:
1. Simple View
A simple view is a view that is based on a single table and
does not include any complex operations such as joins,
subqueries, or groupings. It provides a straightforward
representation of data from a single table.
Key Points:
It is based on one table.
Typically used for security purposes, to expose only
specific columns or rows of a table.
It allows users to access a subset of data in a user-
friendly format.
Example of Simple View:
Suppose we have a table Employees:
EmpID EmpName Age Department
1 John 30 HR
2 Alice 25 IT
3 Bob 35 Finance
SQL Query to create a simple view:
CREATE VIEW EmployeeNames AS
SELECT EmpID, EmpName
FROM Employees;
Using the View:
SELECT * FROM EmployeeNames;
Result:
EmpID EmpName
1 John
2 Alice
3 Bob
This view simply exposes the EmpID and EmpName
columns from the Employees table.
2. Complex View
A complex view is a view that is created from multiple
tables and can include features such as joins, subqueries,
grouping, or aggregations. These views are used when data
from multiple tables needs to be combined or
transformed.
Key Points:
It can be based on more than one table.
May include operations like JOIN, GROUP BY, or ORDER
BY.
Can include subqueries, which allow for complex
filtering and calculations.
Example of Complex View:
Consider two tables: Employees and Departments.
Employees Table:
EmpID EmpName DeptID
1 John 10
2 Alice 20
3 Bob 10
Departments Table:
DeptID DeptName
10 HR
20 IT
SQL Query to create a complex view:
CREATE VIEW EmployeeDetails AS
SELECT E.EmpID, E.EmpName, D.DeptName
FROM Employees E
JOIN Departments D ON E.DeptID = D.DeptID;
Using the View:
SELECT * FROM EmployeeDetails;
Result:
EmpID EmpName DeptName
1 John HR
2 Alice IT
3 Bob HR
This view combines data from two tables: Employees and
Departments, showing which department each employee
belongs to.
3. Materialized View
A materialized view is a view that physically stores the
result of a query, unlike other views that are virtual and
dynamically calculated every time they are accessed.
Materialized views can be refreshed periodically to ensure
that they reflect the latest data from the underlying tables.
Key Points:
Stores the query result physically, improving
performance for complex queries.
Can be refreshed at regular intervals to update the data.
Useful for reporting purposes and data warehousing,
where real-time data is not critical.
Example of Materialized View:
If we wanted to create a materialized view based on the
Employees and Departments tables, the syntax would
depend on the database system. In Oracle, for instance:
CREATE MATERIALIZED VIEW EmployeeDetailsMaterialized
AS
SELECT E.EmpID, E.EmpName, D.DeptName
FROM Employees E
JOIN Departments D ON E.DeptID = D.DeptID;
In this case, the result of the query would be stored
physically, allowing for faster access to the employee and
department data. The materialized view can be refreshed
using:
REFRESH MATERIALIZED VIEW
EmployeeDetailsMaterialized;
4. Updatable View
An updatable view is a view that allows updates (inserts,
updates, or deletes) on the underlying table through the
view itself. However, not all views are updatable, especially
if they are based on complex queries involving joins,
aggregates, or non-key columns.
Key Points:
It allows users to modify the data in the underlying table
via the view.
A view is updatable only if it satisfies certain conditions
(e.g., not based on joins or aggregations).
Example of an Updatable View:
Consider the Employees table:
EmpID EmpName Age Department
1 John 30 HR
2 Alice 25 IT
You could create an updatable view like this:
CREATE VIEW EmployeeUpdate AS
SELECT EmpID, EmpName, Age
FROM Employees;
You can then update the employee's age through the view:
UPDATE EmployeeUpdate
SET Age = 31
WHERE EmpID = 1;
This would update the Age of the employee with EmpID =
1 in the underlying Employees table.
5. Read-Only View
A read-only view is a view that cannot be modified directly
through the view. Any attempt to insert, update, or delete
data through the view will result in an error. This type of
view is typically used for reporting or when the integrity of
the underlying data must be maintained.
Key Points:
Does not allow modification of the underlying data.
Often used for providing access to read-only data.
Example of Read-Only View:
CREATE VIEW EmployeeReadOnly AS
SELECT EmpID, EmpName, Age
FROM Employees;
In this case, users can query the view but cannot modify
the data through it.
1. One-to-Many Relationship
In a one-to-many relationship, one record in the parent
table can relate to many records in the child table. For
example, in a database with two tables, Department and
Employee, each department can have multiple employees,
but each employee can belong to only one department.
Steps to Create a One-to-Many Relationship:
1. Create the parent table (Department) with a Primary
Key.
2. Create the child table (Employee) and add a Foreign Key
referencing the primary key of the parent table.
Example:
Consider a Department table and an Employee table where
each department has multiple employees.
Step 1: Create the Department table:
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(100)
);
DeptID is the Primary Key of the Department table.
Step 2: Create the Employee table:
CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(100),
Age INT,
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);
DeptID in the Employee table is the Foreign Key that
references DeptID in the Department table.
Explanation:
The Department table represents the "parent" table
with the primary key DeptID.
The Employee table represents the "child" table with a
foreign key DeptID that creates a relationship with the
Department table.
The foreign key ensures that each employee belongs to a
valid department.
2. Many-to-One Relationship
A many-to-one relationship is essentially the reverse of a
one-to-many relationship. Many records in the child table
can reference the same record in the parent table.
In SQL, the many-to-one relationship is typically
represented using the same structure as the one-to-many
relationship. In the above example, many employees can
belong to the same department, but each employee is
assigned to one department.
3. Many-to-Many Relationship
In a many-to-many relationship, multiple records in one
table can be associated with multiple records in another
table. For example, in a database that tracks Students and
Courses, each student can enroll in multiple courses, and
each course can have multiple students.
To create a many-to-many relationship, we need to create
a junction table (also called a bridge table or association
table) that contains foreign keys referencing the primary
keys of the two tables involved in the relationship.
Steps to Create a Many-to-Many Relationship:
1. Create the two main tables (Student and Course) with
Primary Keys.
2. Create a junction table (StudentCourse) that contains
foreign keys referencing both the Student and Course
tables.
Example:
Step 1: Create the Student table:
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
StudentName VARCHAR(100)
);
StudentID is the Primary Key of the Student table.
Step 2: Create the Course table:
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100)
);
CourseID is the Primary Key of the Course table.
Step 3: Create the StudentCourse junction table:
CREATE TABLE StudentCourse (
StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES
Student(StudentID),
FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);
The junction table StudentCourse includes the foreign
keys StudentID and CourseID.
The Primary Key of the StudentCourse table is a
composite key made up of both StudentID and CourseID
to ensure that each student-course pair is unique.
Explanation:
A many-to-many relationship is created through the
StudentCourse table, which connects students to the
courses they are enrolled in.
Each student can have multiple entries in the
StudentCourse table (enrolled in many courses), and
each course can have multiple students.
4. One-to-One Relationship
In a one-to-one relationship, each record in one table
corresponds to one record in another table. This type of
relationship is less common but useful in scenarios like
dividing a large table for performance reasons or splitting
confidential data.
Steps to Create a One-to-One Relationship:
1. Create two tables where each table has a primary key.
2. Ensure that the foreign key in one table references the
primary key of the other table, and that it is unique.
Example:
Consider a Person table and a Passport table, where each
person has only one passport, and each passport is
assigned to only one person.
Step 1: Create the Person table:
CREATE TABLE Person (
PersonID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT
);
PersonID is the Primary Key of the Person table.
Step 2: Create the Passport table:
CREATE TABLE Passport (
PassportID INT PRIMARY KEY,
PersonID INT UNIQUE,
IssueDate DATE,
ExpiryDate DATE,
FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
);
PersonID in the Passport table is a Foreign Key
referencing the PersonID of the Person table.
The PersonID in the Passport table is also marked as
UNIQUE to ensure that each person can have only one
passport.
Explanation:
A one-to-one relationship exists between Person and
Passport, where each person can have one and only one
passport, and each passport is linked to one person.
1. COUNT()
Purpose: Returns the number of rows in a result set.
Syntax:
SELECT COUNT(column_name) FROM table_name;
Example:
SELECT COUNT(*) FROM Employees;
This returns the total number of employees in the
Employees table.
2. SUM()
Purpose: Returns the sum of values in a numeric
column.
Syntax:
SELECT SUM(column_name) FROM table_name;
Example:
SELECT SUM(Salary) FROM Employees;
This returns the total sum of the salaries of all employees.
3. AVG()
Purpose: Returns the average value of a numeric
column.
Syntax:
SELECT AVG(column_name) FROM table_name;
Example:
SELECT AVG(Salary) FROM Employees;
This returns the average salary of all employees.
4. MAX()
Purpose: Returns the maximum value from a set of
values in a column.
Syntax:
SELECT MAX(column_name) FROM table_name;
Example:
SELECT MAX(Salary) FROM Employees;
This returns the highest salary among all employees.
5. MIN()
Purpose: Returns the minimum value from a set of
values in a column.
Syntax
SELECT MIN(column_name) FROM table_name;
Example:
SELECT MIN(Salary) FROM Employees;
This returns the lowest salary among all employees.
6. GROUP_CONCAT() (MySQL-specific)
Purpose: Concatenates values from multiple rows into a
single string.
Syntax:
SELECT GROUP_CONCAT(column_name) FROM
table_name;
Example:
SELECT GROUP_CONCAT(DeptName) FROM Departments;
This returns a comma-separated list of all department
names in the Departments table.
Types of Subqueries:
1. Subquery in WHERE Clause: A subquery can be used in
the WHERE clause to filter the results based on a
condition.
2. Subquery in SELECT Clause: A subquery can be used in
the SELECT clause to compute a derived column.
3. Subquery in FROM Clause: A subquery can be used in
the FROM clause to create a temporary table for further
processing.
Syntax of a Subquery:
SELECT column_name(s)
FROM table_name
WHERE column_name OPERATOR (SELECT column_name
FROM table_name WHERE condition);
Here:
OPERATOR: Could be =, IN, BETWEEN, EXISTS, etc.
Subquery: The nested query inside parentheses.
Examples of Subqueries:
1. Subquery in WHERE Clause:
Let's consider a database with the following two tables:
Employees Table:
EmpID Name DeptID Salary
1 Alice 101 5000
2 Bob 102 6000
3 Charlie 103 4500
4 David 104 7000
5 Eve 102 5500
Departments Table:
DeptID DeptName
101 HR
102 IT
103 Sales
104 Marketing
Now, let's say we want to find the employees whose salary
is greater than the average salary in their department.
Query:
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees
WHERE DeptID = Employees.DeptID);
Explanation:
The subquery (SELECT AVG(Salary) FROM Employees
WHERE DeptID = Employees.DeptID) calculates the
average salary for each department.
The outer query selects employees whose salary is
greater than the average salary of their respective
department.
This query returns only the employees who meet this
condition.