0% found this document useful (0 votes)
18 views

Dbms

dbms concepts

Uploaded by

Adilyt ytt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Dbms

dbms concepts

Uploaded by

Adilyt ytt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Q1a) Describe natural join and equi join operations. Give examples.

(6
marks)
 Natural Join: Combines two relations and automatically matches tuples
with the same values in common attributes. No condition is explicitly
provided, as matching is implicit based on attribute names.
o Example:

sql
Copy code
SELECT * FROM Employee NATURAL JOIN Department;
 Equi Join: A specific type of join where matching is based on a condition
that equates columns from both relations. The condition uses equality (=).
o Example:

sql
SELECT * FROM Employee E, Department D WHERE E.dept_id = D.dept_id;
Q1b) Demonstrate the division operation with an example. (4 marks)
 Division Operation: The division operator is used when you want to
retrieve tuples from one relation that are related to all tuples in another
relation.
o Example: Assume two relations:

 R(A, B): {(1, 2), (1, 3), (2, 2), (2, 3)}
 S(B): {(2), (3)}
The division operation R ÷ S would return {(1), (2)}, because both 1 and 2 are
associated with every value in S.

Q2a) Explain aggregate function and grouping in relational algebra. (6


marks)
 Aggregate Functions: Used to perform calculations on a set of tuples,
like sum, count, average, max, and min.
o Example:

sql
SELECT AVG(salary) FROM Employee;
 Grouping: Allows grouping of data based on one or more attributes and
then applying aggregate functions.
o Example:

sql
SELECT dept_id, AVG(salary) FROM Employee GROUP BY dept_id;
Q2b) Discuss the use of recursive closure operations. Give examples. (4
marks)
 Recursive Closure Operations: Used in situations like transitive
closures where recursion is needed, such as determining the hierarchy in
employee-manager relationships.
o Example: In SQL, recursive queries can be handled using Common
Table Expressions (CTEs).
sql
WITH RECURSIVE EmployeeHierarchy AS (
SELECT emp_id, mgr_id FROM Employee WHERE mgr_id IS NULL
UNION ALL
SELECT E.emp_id, EH.mgr_id FROM Employee E
JOIN EmployeeHierarchy EH ON E.mgr_id = EH.emp_id
)
SELECT * FROM EmployeeHierarchy;

Q3a) Importance of outer join operations. Describe all types with syntax
and examples. (10 marks)
 Outer Join: Retains unmatched tuples from one or both relations.
o Left Outer Join: Keeps unmatched tuples from the left relation.

sql
SELECT * FROM Employee LEFT JOIN Department ON Employee.dept_id =
Department.dept_id;
o Right Outer Join: Keeps unmatched tuples from the right relation.

sql
Copy code
SELECT * FROM Employee RIGHT JOIN Department ON Employee.dept_id =
Department.dept_id;
o Full Outer Join: Keeps unmatched tuples from both relations.

sql
Copy code
SELECT * FROM Employee FULL OUTER JOIN Department ON Employee.dept_id =
Department.dept_id;
Q4a) Write the following queries: (5+5 = 10 marks)
1. Retrieve the name and address of all employees who work for the
research department:
sql
Copy code
SELECT E.name, E.address
FROM Employee E
JOIN Department D ON E.dept_id = D.dept_id
WHERE D.name = 'Research';
2. Retrieve the names of employees who have no dependents:
sql
Copy code
SELECT name FROM Employee
WHERE emp_id NOT IN (SELECT emp_id FROM Dependents);

Q5a) Describe the seven steps of an algorithm for ER to relational


mapping. (10 marks)
1. Mapping strong entity types: Create a table for each strong entity with
primary keys.
2. Mapping weak entity types: Create a table for each weak entity with
foreign keys referencing strong entities.
3. Mapping binary relationships: For 1:1 and 1
relationships, add foreign keys to appropriate tables. For M
, create a new relation.
4. Mapping multi-valued attributes: Create a separate table for each
multi-valued attribute.
5. Mapping n-ary relationships: Create a table with foreign keys from
participating entities.
6. Mapping generalization/specialization: Use class-table or single-table
inheritance strategies.
7. Mapping aggregation: Represent as a relationship or a separate entity.

Q6a) Define SQL and its data types with syntax and examples. (6
marks)
 SQL: A language for managing data in relational databases.
 Data Types:
o INT: Integer numbers.

sql
Copy code
CREATE TABLE Employee (emp_id INT);
o VARCHAR: Variable-length strings.

sql
Copy code
CREATE TABLE Employee (name VARCHAR(100));
Q6b) Write a note on ambiguous attribute names, aliasing, and
renaming. (4 marks)
 Ambiguous Attribute Names: Occur in joins where columns with the
same name exist in multiple tables.
 Aliasing and Renaming: SQL allows renaming for better readability or
resolving ambiguities.
o Example:

sql
SELECT E.name AS EmployeeName, D.name AS DepartmentName
FROM Employee E, Department D WHERE E.dept_id = D.dept_id;

Q7a) Demonstrate the usage of DEFAULT and CHECK clause with syntax
and examples. (6 marks)
 DEFAULT: Provides a default value when no value is supplied.
o Example:

sql
Copy code
CREATE TABLE Employee (name VARCHAR(50), salary INT DEFAULT 50000);
 CHECK: Ensures a condition must hold for values in the column.
o Example:

sql
Copy code
CREATE TABLE Employee (name VARCHAR(50), salary INT CHECK (salary > 0));
Q7b) Write comparisons involving NULL and three-valued logic. (4
marks)
 NULL: Special marker for unknown or missing data. In SQL, comparisons
with NULL result in UNKNOWN (three-valued logic).
o Example:

sql
SELECT * FROM Employee WHERE salary IS NULL;

Q8a) Discuss Boolean functions of EXISTS and UNIQUE with syntax and
example. (6 marks)
 EXISTS: Returns true if a subquery returns any rows.
o Example:

sql
SELECT * FROM Employee WHERE EXISTS (SELECT * FROM Department WHERE
dept_id = Employee.dept_id);
 UNIQUE: Ensures all rows returned by a subquery are unique.
o Example:

sql
SELECT * FROM Employee WHERE UNIQUE (SELECT dept_id FROM Department);
Q8b) Describe usage of explicit sets and renaming in SQL. (4 marks)
 Explicit Sets: Use IN to specify a set of values.
o Example:

sql
SELECT * FROM Employee WHERE dept_id IN (1, 2, 3);

Q9a) GROUP BY and HAVING clause, joined tables, outer joins, and
aggregate functions in SQL. (10 marks)
 Example:
sql
Copy code
SELECT dept_id, AVG(salary) FROM Employee
GROUP BY dept_id
HAVING AVG(salary) > 50000;

Q10a) Describe CREATE ASSERTION statement and CREATE TRIGGER


statement. (6 marks)
 CREATE ASSERTION: Defines a constraint over multiple tables.
sql
CREATE ASSERTION salary_check CHECK (salary > 30000);
 CREATE TRIGGER: Automatically performs an action when an event
occurs.
sql
CREATE TRIGGER SalaryUpdate AFTER UPDATE ON Employee
FOR EACH ROW BEGIN
IF NEW.salary < OLD.salary THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary cannot decrease';
END IF;
END;
Q10b) Efficient implementation of a view, updating views, and inline
views. (4 marks)
 Efficient implementation: Use indexed views for performance.
 Updating views: Use INSTEAD OF triggers to allow updates.
 Inline views: Subqueries that can be used as a temporary table within a
query.

Expanded Answer for Q7a) Demonstrate the usage of DEFAULT and


CHECK clause with syntax and examples. (6 marks)
1. DEFAULT Clause
The DEFAULT clause is used to assign a default value to a column if no value is
provided during an insert operation. This ensures that a column is always
populated, even if a user doesn’t provide a specific value.
 Syntax:
sql
Copy code
CREATE TABLE table_name (
column_name datatype DEFAULT default_value
);
 Example:
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) DEFAULT 30000.00,
join_date DATE DEFAULT CURRENT_DATE
);
o Explanation:

 The salary column has a default value of 30000.00. If no


salary is provided during an INSERT statement, the value
30000.00 will be used automatically.
 The join_date column defaults to the current date using
CURRENT_DATE.
o Insert Example:

sql
Copy code
INSERT INTO Employee (emp_id, name) VALUES (1, 'John Doe');
 Since the salary and join_date were not specified, the
DEFAULT values will be used: salary = 30000.00 and join_date
= CURRENT_DATE.
2. CHECK Clause
The CHECK clause is used to impose constraints on values that can be inserted
into a column. It ensures that the data entered into a column meets specific
conditions.
 Syntax:
sql
Copy code
CREATE TABLE table_name (
column_name datatype CHECK (condition)
);
 Example 1 (Simple Check):
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) CHECK (salary > 0)
);
o Explanation:

 The CHECK constraint ensures that the salary column cannot


contain a value less than or equal to 0.
o Insert Example:

sql
Copy code
INSERT INTO Employee (emp_id, name, salary) VALUES (2, 'Jane Smith', -5000);
 This query would fail because the salary value violates the
CHECK constraint.
 Example 2 (Multiple Conditions):
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) CHECK (salary > 0 AND salary < 100000),
age INT CHECK (age >= 18 AND age <= 65)
);
o Explanation:

 The CHECK constraint on salary ensures that the value must


be greater than 0 but less than 100,000.
 The CHECK constraint on age ensures that employees must
be between 18 and 65 years old.
o Insert Example:

sql
Copy code
INSERT INTO Employee (emp_id, name, salary, age) VALUES (3, 'Mark Lee',
120000, 30);
 This query would fail because the salary value exceeds
100,000.
Combining DEFAULT and CHECK
You can combine both the DEFAULT and CHECK clauses in the same table
definition to provide default values while enforcing constraints.
 Example:
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) DEFAULT 25000.00 CHECK (salary > 0 AND salary <
100000),
age INT CHECK (age >= 18 AND age <= 65)
);
o Explanation:

 If a salary is not provided during the insert, the default salary


will be 25000.00, but the value must also meet the CHECK
constraint of being between 0 and 100,000.
 Similarly, the age must be between 18 and 65.

Final Remarks for 6 Marks:


 DEFAULT Clause: Ensures columns have values even if none are
provided.
 CHECK Clause: Ensures values meet specific conditions and constraints.
 This answer includes both basic and complex examples (e.g., multiple
conditions in the CHECK clause) and demonstrates how the two clauses
can be used together, making it suitable for 6 marks.
Let me know if you'd like more clarification on this or any other topic!
4o
You said:
can u expand on q 3a
ChatGPT said:
ChatGPT
Expanded Answer for Q3a) Importance of Outer Join Operations.
Describe all the types with syntax and examples. (10 marks)
1. Importance of Outer Join Operations
In SQL, joins are essential for retrieving data from multiple tables based on a
related column. While inner joins return only the rows that have matching values
in both tables, outer joins allow the retrieval of non-matching rows as well. This
feature is especially useful when analyzing data where you want to include
records that do not have corresponding matches in the other table.
Why Outer Joins are Important:
 Data Completeness: Outer joins allow you to include rows from one or
both tables even when there is no match, providing a more complete
dataset.
 Missing Data Handling: In scenarios where data might be missing in one
of the tables, outer joins help to display that absence rather than
completely excluding it.
 Reporting and Analysis: Outer joins are often used in reports where you
want to show all entities (e.g., departments, employees) regardless of
whether they have corresponding records (e.g., projects assigned to
departments).
2. Types of Outer Joins
SQL supports three types of outer joins: Left Outer Join, Right Outer Join, and
Full Outer Join. Let’s explore each with examples.

2.1 Left Outer Join


 A Left Outer Join returns all rows from the left table and the matching
rows from the right table. If there is no match, NULL values are returned
for columns from the right table.
 Syntax:
sql
Copy code
SELECT columns
FROM left_table
LEFT JOIN right_table ON left_table.column = right_table.column;
 Example: Suppose we have two tables: Employee and Department.
o Employee Table:

emp_i nam dept_i


d e d

1 John 10

2 Jane 20

3 Alice NULL
emp_i nam dept_i
d e d

4 Bob 30

o Department Table:

dept_i dept_na
d me

10 HR

20 Finance

 The following query retrieves all employees, including those not assigned
to a department:
 sql
 Copy code
 SELECT E.name, D.dept_name
 FROM Employee E
 LEFT JOIN Department D ON E.dept_id = D.dept_id;
o Result:

nam dept_na
e me

John HR

Jane Finance

Alice NULL

Bob NULL

o Explanation:

 The left join ensures that all rows from the Employee table
are included, even if they do not have a matching dept_id in
the Department table (Alice and Bob in this case).

2.2 Right Outer Join


 A Right Outer Join returns all rows from the right table and the matching
rows from the left table. If there is no match, NULL values are returned for
columns from the left table.
 Syntax:
sql
Copy code
SELECT columns
FROM left_table
RIGHT JOIN right_table ON left_table.column = right_table.column;
 Example: Continuing from the previous tables, the following query
retrieves all departments, including those without any employees:
sql
Copy code
SELECT E.name, D.dept_name
FROM Employee E
RIGHT JOIN Department D ON E.dept_id = D.dept_id;
o Result:

nam dept_na
e me

John HR

Jane Finance

NULL Sales

o Explanation:

 The right join ensures that all rows from the Department
table are included, even if there are no matching employees
in that department (e.g., the Sales department with no
employees).

2.3 Full Outer Join


 A Full Outer Join returns all rows when there is a match in either the left
or right table. If there is no match, NULL values are returned from the
missing side. This join combines both Left Outer Join and Right Outer
Join.
 Syntax:
sql
Copy code
SELECT columns
FROM left_table
FULL OUTER JOIN right_table ON left_table.column = right_table.column;
 Example: The following query retrieves all employees and all
departments, regardless of whether there is a match:
sql
Copy code
SELECT E.name, D.dept_name
FROM Employee E
FULL OUTER JOIN Department D ON E.dept_id = D.dept_id;
o Result:

nam dept_na
e me

John HR

Jane Finance

Alice NULL

Bob NULL

NULL Sales

o Explanation:

 The full outer join ensures that all rows from both the
Employee and Department tables are included, regardless of
whether they have a matching dept_id.

3. Practical Usage Scenarios of Outer Joins


 Left Outer Join:
o Used when you want to retrieve all records from the primary table
(left table), even if there is no related data in the secondary table.
o Example: A company wants to display all employees, even those
not assigned to any department.
 Right Outer Join:
o Used when the focus is on retrieving all records from the secondary
table (right table), even if there is no related data in the primary
table.
o Example: A company wants to show all departments, including
those that do not yet have any employees assigned.
 Full Outer Join:
o Used when you need to combine the results of both left and right
joins, i.e., showing all records from both tables and including rows
that do not have matches.
o Example: A company wants to generate a report of all employees
and all departments, even if some employees are not assigned to
any department and some departments do not have any
employees.

Conclusion:
Outer joins are crucial when you need to include unmatched records from one or
both tables in a SQL query. By using left, right, and full outer joins, you can
ensure that your data retrieval is more comprehensive, allowing you to handle
scenarios where certain relationships between tables might be missing. The
examples provided show how outer joins can be used to handle missing data and
how to write queries that include all rows from one or both tables, regardless of
whether they have a match.

This expanded answer now provides a detailed explanation of the importance


of outer joins and covers all three types of joins with syntax and multiple
examples, which makes it appropriate for 10 marks. Let me know if you'd like
further clarifications!
4o
You said:
expand q5a
ChatGPT said:
ChatGPT
Expanded Answer for Q5a) Describe the seven steps of an algorithm for
ER to relational mapping. Illustrate with the company database as an
example. (10 marks)
Introduction:
Entity-Relationship (ER) to Relational mapping is the process of converting an ER
model into a relational schema. The ER model is often used during the database
design phase, and relational schemas are the foundation for implementing
databases. The conversion ensures that all entities, relationships, and constraints
in the ER model are reflected accurately in the relational model.
Here are the seven steps of ER to relational mapping, explained with an
example using a company database.

1. Mapping Strong Entity Types


 Strong entities are entities that have a primary key and do not depend
on any other entity for their existence.
 Conversion: For each strong entity in the ER model, a separate relation
(table) is created. The attributes of the entity become the columns of the
table, and the primary key of the entity becomes the primary key of the
relation.
 Example: Consider the Employee entity:
o Employee: {emp_id (PK), name, age, salary}

The corresponding table will be:


sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
salary DECIMAL(10, 2)
);

2. Mapping Weak Entity Types


 Weak entities are entities that do not have a primary key of their own
and depend on another "owner" entity for their identification. Weak
entities usually have a partial key that uniquely identifies them together
with the primary key of the owner entity.
 Conversion: For each weak entity, a table is created that includes:
o All the attributes of the weak entity.

o A foreign key that references the primary key of the owner entity.

o The partial key of the weak entity becomes part of the primary key
of the table.
 Example: Suppose Dependent is a weak entity with the attributes
{dependent_name (partial key), age} that depends on Employee:
sql
Copy code
CREATE TABLE Dependent (
emp_id INT,
dependent_name VARCHAR(50),
age INT,
PRIMARY KEY (emp_id, dependent_name),
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id)
);

3. Mapping Binary Relationships


 Binary relationships connect two entities. Depending on the cardinality of
the relationship (1:1, 1
,M
), the mapping process varies.
3.1 One-to-One (1:1) Relationships
 Conversion: Add a foreign key to one of the two tables (either entity) and
enforce a unique constraint on the foreign key to ensure the one-to-one
relationship.
 Example: If each Employee has one ParkingSpot, and each parking spot is
assigned to only one employee:
sql
Copy code
CREATE TABLE ParkingSpot (
spot_id INT PRIMARY KEY,
emp_id INT UNIQUE,
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id)
);
3.2 One-to-Many (1
) Relationships
 Conversion: The primary key of the "one" entity is added as a foreign key
to the "many" entity.
 Example: If each Department can have multiple Employees but each
employee belongs to only one department:
o Department: {dept_id (PK), dept_name}

o Employee will include a dept_id foreign key.

sql
Copy code
CREATE TABLE Department (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES Department(dept_id)
);
3.3 Many-to-Many (M
) Relationships
 Conversion: Create a new relation (junction table) that includes foreign
keys from both entities involved in the relationship. These foreign keys
together form the primary key of the new relation.
 Example: If Employee can work on multiple Projects, and each project can
have multiple employees:
sql
Copy code
CREATE TABLE Project (
project_id INT PRIMARY KEY,
project_name VARCHAR(100)
);

CREATE TABLE Employee_Project (


emp_id INT,
project_id INT,
PRIMARY KEY (emp_id, project_id),
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id),
FOREIGN KEY (project_id) REFERENCES Project(project_id)
);

4. Mapping Multivalued Attributes


 Multivalued attributes are attributes that can have multiple values for a
single entity. These are mapped into a new relation, where each value of
the multivalued attribute is stored as a separate tuple.
 Conversion: Create a new relation for the multivalued attribute, with a
foreign key referencing the original entity.
 Example: Suppose an Employee can have multiple phone numbers:
sql
Copy code
CREATE TABLE EmployeePhone (
emp_id INT,
phone_number VARCHAR(20),
PRIMARY KEY (emp_id, phone_number),
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id)
);

5. Mapping N-ary Relationships


 An n-ary relationship involves more than two entities. For example, a
ternary relationship (3 entities) would involve three entities participating in
a relationship.
 Conversion: Create a new relation for the n-ary relationship. The primary
key of this new relation consists of the foreign keys from all participating
entities, along with any attributes of the relationship itself.
 Example: If there is a relationship between Employee, Project, and Role
(the role the employee plays in the project):
sql
Copy code
CREATE TABLE EmployeeProjectRole (
emp_id INT,
project_id INT,
role_id INT,
PRIMARY KEY (emp_id, project_id, role_id),
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id),
FOREIGN KEY (project_id) REFERENCES Project(project_id),
FOREIGN KEY (role_id) REFERENCES Role(role_id)
);

6. Mapping Generalization/Specialization (ISA Relationships)


 Generalization is when multiple entity types are combined into a single
higher-level entity. Specialization is when an entity is divided into sub-
entities based on some attributes.
 Conversion: There are three common approaches:
o Single Table Inheritance: Create one table with all attributes
(including attributes specific to sub-entities). This can lead to many
NULL values.
o Class Table Inheritance: Create a table for the general entity and
separate tables for each sub-entity. The sub-entity tables reference
the general entity’s primary key.
o Shared Primary Key Inheritance: Similar to class table
inheritance, but each sub-entity table uses the primary key of the
general entity directly as its primary key.
 Example (Class Table Inheritance): Suppose we have an Employee
entity, and some employees are Managers and others are Technicians:
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);

CREATE TABLE Manager (


emp_id INT PRIMARY KEY,
bonus DECIMAL(10, 2),
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id)
);

CREATE TABLE Technician (


emp_id INT PRIMARY KEY,
skill_level VARCHAR(50),
FOREIGN KEY (emp_id) REFERENCES Employee(emp_id)
);
7. Mapping Aggregation
 Aggregation is a special case of abstraction that is used when
relationships themselves have relationships. This happens when you treat
a relationship as a higher-level entity.
 Conversion: Model the aggregation as a new entity and map it using the
steps previously described.
 Example: Suppose we have an aggregation between an Employee
working on a Project that is supervised by a Manager. This aggregation can
be treated as a new entity and then mapped similarly to a binary or
ternary relationship.

Conclusion:
These seven steps ensure that all entities, relationships, multivalued attributes,
and special structures in the ER model are correctly translated into the relational
schema. This structured approach helps in designing a relational database that
adheres to the integrity and constraints present in the original ER model.
This detailed explanation of each step, along with relevant examples using a
company database, makes the answer complete for 10 marks.
Let me know if you need further clarification or another example!
4o
You said:
some questions have asked syt=natx and examples and u have given only
examples
ChatGPT said:
ChatGPT
Thank you for pointing that out! I’ll correct the responses where both syntax and
examples were requested but only examples were provided. Let’s go through
those questions and provide the necessary syntax and examples for
completeness.

Q1a) Natural Join and Equi Join Operations (6 marks)


Natural Join:
 Syntax:
sql
Copy code
SELECT *
FROM table1
NATURAL JOIN table2;
 Example: Suppose you have two tables: Employee and Department.
sql
Copy code
SELECT *
FROM Employee
NATURAL JOIN Department;
o This query joins the two tables on columns with the same name,
such as dept_id, and returns all rows where those columns have
matching values.
Equi Join:
 Syntax:
sql
Copy code
SELECT columns
FROM table1, table2
WHERE table1.column = table2.column;
 Example:
sql
Copy code
SELECT E.name, D.dept_name
FROM Employee E, Department D
WHERE E.dept_id = D.dept_id;
o This query explicitly joins the Employee and Department tables
based on the equality condition (E.dept_id = D.dept_id).

Q3a) Outer Join Operations (10 marks)


I had already provided examples for outer joins, but here's the syntax along
with the examples:
Left Outer Join:
 Syntax:
sql
Copy code
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
 Example:
sql
Copy code
SELECT E.name, D.dept_name
FROM Employee E
LEFT JOIN Department D ON E.dept_id = D.dept_id;
o This query returns all employees, including those who are not
assigned to any department.
Right Outer Join:
 Syntax:
sql
Copy code
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
 Example:
sql
Copy code
SELECT E.name, D.dept_name
FROM Employee E
RIGHT JOIN Department D ON E.dept_id = D.dept_id;
o This query returns all departments, even if they do not have any
employees assigned.
Full Outer Join:
 Syntax:
sql
Copy code
SELECT columns
FROM table1
FULL OUTER JOIN table2 ON table1.column = table2.column;
 Example:
sql
Copy code
SELECT E.name, D.dept_name
FROM Employee E
FULL OUTER JOIN Department D ON E.dept_id = D.dept_id;
o This query returns all employees and all departments, including
those that do not have corresponding matches.

Q6a) Define SQL and its Data Types (6 marks)


Here’s the required syntax for defining SQL data types, along with examples.
SQL Syntax for Data Types:
 Syntax:
sql
Copy code
CREATE TABLE table_name (
column_name data_type [constraint],
column_name data_type [constraint]
);
 Common SQL Data Types:
1. INT: Stores integer values.
2. VARCHAR(n): Stores variable-length character strings with a
maximum length of n.
3. DECIMAL(p, s): Stores fixed-point numbers with precision p and
scale s.
4. DATE: Stores date values.
5. BOOLEAN: Stores true or false values.
 Example:
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2),
join_date DATE
);
o This creates a table Employee with columns emp_id (integer), name
(string up to 50 characters), salary (decimal with 10 digits, 2 after
the decimal), and join_date (date type).

Q7a) DEFAULT and CHECK Clause (6 marks)


Here’s the required syntax for DEFAULT and CHECK clauses along with the
examples already provided.
DEFAULT Clause:
 Syntax:
sql
Copy code
CREATE TABLE table_name (
column_name data_type DEFAULT default_value
);
 Example:
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) DEFAULT 30000.00,
join_date DATE DEFAULT CURRENT_DATE
);
CHECK Clause:
 Syntax:
sql
Copy code
CREATE TABLE table_name (
column_name data_type CHECK (condition)
);
 Example:
sql
Copy code
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2) CHECK (salary > 0 AND salary < 100000),
age INT CHECK (age >= 18 AND age <= 65)
);
Q10a) CREATE ASSERTION and CREATE TRIGGER Statements (6 marks)
I provided examples for CREATE ASSERTION and CREATE TRIGGER, but here's
the explicit syntax for both along with the examples.
CREATE ASSERTION:
 Syntax:
sql
Copy code
CREATE ASSERTION assertion_name CHECK (condition);
 Example:
sql
Copy code
CREATE ASSERTION salary_check
CHECK (salary >= 30000);
o This assertion ensures that no employee has a salary below 30,000.

CREATE TRIGGER:
 Syntax:
sql
Copy code
CREATE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF} {INSERT | DELETE | UPDATE} ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic
END;
 Example:
sql
Copy code
CREATE TRIGGER SalaryUpdate
BEFORE UPDATE ON Employee
FOR EACH ROW
BEGIN
IF NEW.salary < OLD.salary THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary cannot decrease';
END IF;
END;
o This trigger prevents an employee's salary from being decreased.

Q10b) Efficient implementation of a view, updating views, and inline


views (4 marks)
This question is asking for a detailed explanation of three concepts: efficient
implementation of views, updating views, and inline views. I'll explain
each concept, provide the necessary syntax, and illustrate with examples.

1. Efficient Implementation of a View


What is a View?
A view is a virtual table in SQL that provides a way to present data from one or
more tables. Views don't store data themselves; instead, they store SQL queries
that generate the data on demand.
Efficient Implementation of Views:
The efficiency of views depends on how they are implemented. Since views are
not physically stored but rather computed on the fly, performance can be a
concern when dealing with large datasets or complex queries.
Methods to Improve View Performance:
1. Materialized Views:
o A materialized view stores the result of a query physically, unlike a
regular view, which just stores the query itself.
o This can significantly improve performance when dealing with
expensive queries that are executed frequently.
o Example:

sql
Copy code
CREATE MATERIALIZED VIEW EmployeeSummary AS
SELECT dept_id, COUNT(*) AS total_employees, AVG(salary) AS avg_salary
FROM Employee
GROUP BY dept_id;
2. Indexes on Views:
o For certain databases, creating an index on a view can improve
performance by allowing the system to retrieve data faster when
the view is queried.
o Example:

sql
Copy code
CREATE INDEX idx_employee_summary ON Employee(dept_id);
3. Simple Queries in Views:
o Views should be designed with simple, efficient queries. Complex
joins or subqueries can slow down performance, especially if the
view is used frequently.

2. Updating Views
Can Views Be Updated?
Views can be updated in some cases, but not always. Whether a view can be
updated depends on how it was defined. Generally, views that are based on a
single table or simple queries can be updated, while complex views involving
joins, groupings, or aggregate functions cannot.
Key Conditions for Updating Views:
1. Single Table Views:
o If the view is based on a single table and does not involve any
GROUP BY, DISTINCT, JOIN, or aggregate functions, it can be
updated directly.
o Example:

sql
Copy code
CREATE VIEW EmployeeNames AS
SELECT emp_id, name FROM Employee;
2. You can update the underlying table through the view:
3. sql
4. Copy code
5. UPDATE EmployeeNames
6. SET name = 'John Doe'
7. WHERE emp_id = 1;
8. Views Based on Joins or Multiple Tables:
o Views based on joins or multiple tables usually cannot be updated
directly because the changes would be ambiguous (i.e., which table
should be updated?).
o However, you can use INSTEAD OF triggers to allow updates on
such views.
INSTEAD OF Trigger Example:
sql
Copy code
CREATE VIEW EmployeeDept AS
SELECT E.name, D.dept_name
FROM Employee E
JOIN Department D ON E.dept_id = D.dept_id;
o This view is based on a join and cannot be updated directly.
However, you can create an INSTEAD OF trigger to handle updates:
sql
Copy code
CREATE TRIGGER UpdateEmployeeDept
INSTEAD OF UPDATE ON EmployeeDept
FOR EACH ROW
BEGIN
UPDATE Employee SET name = :NEW.name WHERE emp_id = :OLD.emp_id;
END;

3. Inline Views
What is an Inline View?
An inline view is a subquery that appears in the FROM clause of a SQL query.
Unlike regular views that are predefined and stored in the database, inline views
are temporary and only exist for the duration of the query.
 Use Case: Inline views are often used to simplify complex queries or to
perform calculations on aggregated data.
Syntax of an Inline View:
sql
Copy code
SELECT column_list
FROM (SELECT columns FROM table WHERE condition) AS inline_view_name
WHERE outer_condition;
Example:
Suppose you want to find the names of departments that have an average salary
greater than 50,000.
 Without an Inline View:
sql
Copy code
SELECT dept_name
FROM Department D
JOIN Employee E ON D.dept_id = E.dept_id
GROUP BY dept_name
HAVING AVG(salary) > 50000;
 With an Inline View (Improves readability and isolates aggregation):
sql
Copy code
SELECT dept_name
FROM (
SELECT dept_id, AVG(salary) AS avg_salary
FROM Employee
GROUP BY dept_id
) AS SalaryByDept
JOIN Department D ON SalaryByDept.dept_id = D.dept_id
WHERE SalaryByDept.avg_salary > 50000;
o Explanation:

 The subquery (SELECT dept_id, AVG(salary) ... ) is the inline


view, which calculates the average salary per department.
The outer query then selects departments that have an
average salary greater than 50,000.

Conclusion:
 Efficient Implementation of Views: Use materialized views for
performance and consider indexing views for faster access.
 Updating Views: Views can be updated under certain conditions, and
INSTEAD OF triggers can enable updates for more complex views.
 Inline Views: These are temporary views used in the FROM clause of a
query and can help simplify and organize complex queries.

You might also like