Mid-1 Question Bank With Answers
Mid-1 Question Bank With Answers
5. How to represent the strong Entity set and Weak entity set in ER-Model?
Strong entity
Strong Entity is independent of any other entity in the schema
Example – A student entity can exist without needing any other entity in the schema or a course
entity can exist without needing any other entity in the schema.
Weak entity
A weak entity is an entity set that does not have sufficient attributes for Unique
Identification of its records.
Example 1 – A loan entity can not be created for a customer if the customer doesn’t exist
• Physical level (or Internal View / Schema): The lowest level of abstraction describes how the
data are actually stored.
• Logical level (or Conceptual View / Schema): The next-higher level of abstraction describes
what data are stored in the database, and what relationships exist among those data.
• View level (or External View / Schema): The highest level of abstraction describes only part
of the database which are requested by the user, but not the entire database.
Integrity constraints are a set of rules that are used to maintain the quality of information.
There are many types of integrity constraints.
1. Entity Integrity Constraint/Key constraints
2. Referential Integrity constraints/ Foreign key
3. Domain constraints
4. General constraints
8. Give examples of selection and projection operations in relational algebra.
Selection (σ): Selection operator is used to select tuples from a relation based on some condition.
A new relation is created by selecting only those rows requested by the user satisfying a
specified condition.
Syntax: σ (Cond)(Relation Name)
E.g: σ (AGE>18)(STUDENT)
Projection (π): The projection eliminates all attributes of the input relation but those mentioned
in the projection list. That means all other unnecessary fields are projected out.
Syntax:
Π(Column 1,Column 2….Column n)(Relation Name)
E.g: Extract ROLL_NO and NAME from STUDENT relation
Π(ROLL_NO,NAME)(STUDENT)
This process is essential in various applications like business analytics, reporting, and data
management.
10.Illustrate division Operation in relational algebra.
In relational algebra, the division operation is used when we need to find records from one
relation that are related to all records in another relation. It is typically used in queries where we
want to find entities that satisfy certain conditions with every element of another set.
Syntax of Division:
The division operation is denoted by the symbol ÷ and is typically used in situations involving
two relations, say R and S.
Relation R / Relation S
The result will be the set of tuples from R that are related to all tuples in S.
In a relational database, altering a table means modifying its structure after it has been created.
This can involve several operations such as adding, deleting, or modifying columns, or even
changing constraints. These operations are typically done using the ALTER TABLE statement
in SQL.
Altering Views
A view is a virtual table that is based on the result of a SELECT query. Altering a view involves
modifying the definition of the view without changing the actual underlying tables. The most
common operation is to redefine or update the view's SELECT statement.
INTERSECT :
Example: Using the same Employees and Contractors tables, suppose we want to find the
Names that appear in both tables (i.e., people who are both employees and contractors).
Sql: SELECT Name FROM Employees INTERSECT SELECT Name FROM Contractors;
EXCEPT
Example: Again, using the Employees and Contractors tables, suppose we want to find the
Names of people who are only employees and not contractors.
Sql:SELECT Name FROM Employees EXCEPT SELECT Name FROM Contractors;
To add a NOT NULL column to an existing table in SQL, we use the ALTER TABLE
statement. When adding a new column to a table, if the column is defined as NOT NULL, it
means that every row in the table must have a value for that column. If the column is to be added
to a table that already contains data, we need to make sure that either:
PART-B
1.Compare and Contrast File Systems with Database Systems.(4)
Network model:
The Network Model is a data model where data is organized using a graph-like structure
with many-to-many relationships.
A child can have multiple parents, allowing for more flexible connections between data.
Data is connected using pointers (links), making traversal efficient for complex
relationships.
It is invented by Charles Bachmann.
ii. RelationalModel:
It is invented by Edgarr F .codd in 1969.
The Relational Model organizes data into tables (relations) consisting of rows (tuples) and
columns (attributes).
Each table has a unique key to identify
records, and relationships between tables are
established using foreign keys.
This model ensures data integrity, flexibility,
and easy retrieval using Structured Query
Language (SQL).
Entities are represented as rectangles and can be things like Customers, Orders, or Products.
Attributes are the properties of entities (e.g., Customer Name, Order Date).
Relationships are shown as diamonds, indicating how entities are connected (e.g., a Customer
places an Order).
3.Write about various database system applications in detail.(4)
APPLICATIONS:
Sales: For customer, product, and purchase information.
◦ Accounting: For payments, receipts, account balances, assets and other accounting information.
◦ Human resources: For information about employees, salaries, payroll taxes, and benefits, and for
generation of paychecks.
◦ Manufacturing: For management of the supply chain and for tracking production of items in
factories, inventories of items inware houses and stores, and orders for items.
Online retailers: For sales data noted above plus online order tracking, generation of
recommendation lists, and maintenance of online product evaluations.
◦ Banking: For customer information, accounts, loans, and banking transactions.
◦ Credit card transactions: For purchases on credit cards and generation of monthly statements.
◦ Finance: For storing information about holdings, sales, and purchases of financial instruments such
as stocks and bonds; also for storing real-time market data to enable online trading by customers and
automated trading by the firm.
• Universities: For student information, course registrations, and grades (in addition to standard
enterprise information such as human resources and accounting).
• Airlines: For reservations and schedule information. Airlines were among the first to use databases
in a geographically distributed manner.
• Telecommunication: For keeping records of calls made, generating monthly bills, maintaining
balances on prepaid calling cards, and storing information about the communication networks.
Data abstraction is the process of hiding unwanted and irrelevant details from the end user.
It helps to store information in such a way that the end user can access data which is
necessary, the user will not be able to
see what data is stored or how it is
stored in a database.
Data abstraction helps to keep data
secure from unauthorized access
and it hides all the implementation
details.
Levels of Abstraction:
There are three levels of data abstraction in DBMS that are mentioned
below:
a) Physical or Internal Level:
It is the lowest level of data abstraction which defines how data is stored in database.
It defines data structures used to store data and methods to access data in database.
It is very complex to understand and hence kept hidden from user.
The internal view is described by internal schema.
Data Independence is the ability to change the schema at one level of a database system without
affecting the schema at the next higher level.
It is important because it allows changes in the data structure without disrupting application
programs or the way users interact with the data.
ANS:
A Database Management System (DBMS) is software that allows users to define, store, maintain,
and manage data in a structured and efficient manner.
A database system is partitioned into modules that deal with each of theresponsibilities of the
overall system.
The functional components of a database system can bebroadly divided into the storage manager,
the query processor components and disk storage.
Application Programmers
Develop application programs for interacting with databases.
Use tools like Rapid Application Development (RAD) to create forms and reports without
coding.
Sophisticated Users
Directly interact with the database using query languages like SQL.
Submit queries to the query processor, which converts them into instructions for the storage
manager.
Specialized Users
Create advanced database applications that go beyond traditional data processing.
Work on CAD systems, expert systems, multimedia databases, and environment modelling
systems.
Naïve Users
Use predefined application programs to interact with the database.
Example: A bank teller using a transfer program to move money between accounts.
Database Administrator (DBA)
Manages the entire database system and its resources.
I. Schema Definition & Modification: The DBA designs the database schema and updates
it as per evolving business needs.
II. Storage Structure & Access Control: Manages data storage methods and controls
access to ensure efficient and secure data retrieval
III. User Authorization & Security: Assigns user permissions to regulate database access
and protect sensitive information.
IV. Performance Monitoring & Optimization: Continuously analyses and improves
database performance by tuning queries and optimizing storage.
V. Ensuring Data Integrity: Implements constraints and rules to maintain accuracy,
consistency, and reliability of the database.
Query Processor:-
The query processor will accept query from user and solves it by accessing the database.
The Query Processor simplifies and facilitates data access in a database system.
It ensures quick processing of updates and queries by translating high-level commands into
efficient low-level operations.
This improves database performance and efficiency.
DDL interpreter: It interprets DDL statements and records the definitions in the data
dictionary.
DML compiler: It translates DML statements in a query language into an evaluation
planconsisting of low-level instructions that the query evaluation engine understands.
Query evaluation engine: It executes low-level instructions generated by the DML
compiler.
Storage manager:
A storage manager is a program module which acts like interface between the data stored in a
database and the application programs and queries submitted to the system.
Thus, the storage manager is responsible for storing, retrieving and updating data in the database.
Authorization and integrity manager: Checks for integrity constraints and authority of
users to access data.
Transaction manager: Ensures that the database remains in a consistent state although
there are system failures.
File manager: Manages the allocation of space on disk storage and the data structures
used to represent information stored on disk.
Buffer manager: It is responsible for retrieving data from disk storage into main
memory. It enables the database to handle data sizes that are much larger than the size of
main memory.
Disk Storage:
Disk storage in DBMS is the permanent storage used to store large volumes of data efficiently.
It ensures data persistence even after system shutdown.
6.What is ER model? Explain the basic symbols used for entities, attributes and relationships.(4)
ANS:
An entity relationship model describes relationship of entities that need to be stored in a database
It is mainly a structured design for database
It is a framework using specialized symbols to define the relationship betweenentities
It is created based on three main components entities attributes and relationships
ER diagrams require no technical knowledge of the underlying DBMS used.
It gives a standard solution for visualizing the data logically.
ENTITIES:
An entity can be either living or non-living component
It is represented as rectangle in a ER diagram
i) Strong entity:It has a primary key that helps in identifying it uniquely, and it is represented
by a rectangle.and exists independently.
ii) Weak entity:A weak entity is an entity that cannot exist independently in a database and
relies on a strong entity for its identification.A weak entity type is represented by a Double
Rectangle.
ATTRIBUTES:
Relationships:
o Many -
to-One relationship(N-1): An entity in A associated with only one entity in B and an
entity in B is associated with more than one entities in then it is known as many to one
relationship.
o
Super key:
A super key is a set of one or more attributes that uniquely identify a row (tuple) in a
table.
A super key may contain extra attributes that are not necessary for uniqueness.
Candidate Key:
A candidate key is a minimal super key that uniquely identifies each row (tuple) in a
table.
A candidate key contains only necessary attributes for uniqueness (removing extra ones
from a super key).
Primary Key:
A primary key is a chosen candidate key that uniquely identifies each row (tuple) in a
table.
A primary key must be unique for every row and cannot contain NULL values.
Foreign Key:
A foreign key is an attribute in one table that refers to the primary key of another table,
establishing a relationship.
It helps connect two or more tables, enabling you to create relationships between them.
Example:
9.How to represent generalization, specialization and aggregation using ER Diagrams. Explain with
suitable example.(4)
ANS:
Generalization:
Generalization is a bottom-up approach in which two lower level entities combine to form a
higher level entity.
In generalization, the higher level entity can also combine with other lower level entities to
make further higher level entity.
For example, Saving and Current account types entities can be generalised and an entity
with name Account can be created, which covers both.
Specialization:
Specialization is opposite to
Generalization.
It is a top- down approach in
which one higher level entity can
be broken down into two lower
level entity.
In specialization, a
higher level entity may not have
any lower-level entity sets, it's possible.
For example, a Student can be specialized into Current Student and Ex-Student, where a
Current Student is actively studying, while an Ex-Student has graduated or left the institution.
Aggregation:
Aggregration is a process when relation between two entities is treated as a single entity.
It is used when a relationship itself acts as an entity in another relationship.
For Example, the relationship between Center and Course together, is acting as an Entity, which
is in relationship with another entity Visitor.
Bank
o Each bank has a unique ID, name, address, and contact information.
Bank Account
o Each bank account has an ID, account number, type (savings, checking, etc.), and a
holder.
o Relationship:
Customer
o Each customer has a unique ID, CNIC (National Identification Number), address, and
name.
o Relationship:
o Represents each transaction made within the bank, with an ID, timestamp, amount, and
linked account.
o Relationship:
Employee
o Each employee has a unique ID, name, address, contact, and gender.
o Relationship:
o Integrity constraints ensure that changes (update deletion, insertion) made to the database by
authorized users do not result in a loss of data consistency.
The UNIQUE keyword ensures that all values in a column are different.
Specifying Primary Key Constraints in SQL
CREATE TABLE Students ( sid INT, name VARCHAR (30) ,Login VARCHAR(20) ,
Age INT, gpa REAL, UNIQUE (name, age),
CONSTRAINT StudentsKey PRIMARY KEY (sid) );
This definition says that sid is the primary key and the combination of name and age is also a
key. The definition of the primary key also illustrates that a constraint should precede with
CONSTRAINT constraint-name
CANDIDATE KEY
o The minimal set of attribute which can uniquely identify a tuple is known as candidate key .
o They can contain null values. These are the subset of super key.
o The remaining attributes except for primary key are considered as a candidate key.
o For example: In the EMPLOYEE table, id is best suited for the primary key. Rest of the attributes
like SSN, Passport_Number, and License_Number, etc. are considered as a candidate key.
SUPER KEY
Super key is a (maximum) set of an attribute which can uniquely identify a tuple. Super key is a
superset of a candidate key.
E.g: Let R be a relation with columns(A,B,C,D,E,F) such that by making AB as key we are able to
identify all other columns i.e CDEF
Keys Is super key or not AB---- CDEF yes
CD----ABEF yes
CB----DF no
ABD---CEF yes
DF---ABCE yes
D---BC no
DEF---ABC yes
By making AB as key we are able to identify all other columns i.e CDEF. Similarly using
CD,ABD,DF and DEF we are able to identify all. So all these are super key.
But by using CB we can only identify D and F. Hence CB is not a super key.
AB is a proper subset of super key ABD, when AB alone is able to identify all attributes, then we
need not need ABD. Hence ABD is only super key and AB is candidate key.
NOTE: Each candidate key is super key but not vice versa.
2. Referential Integrity Constraint-
Foreign keys are the columns of a table that points to the primary key of another table. They act as a
cross-reference between tables.
It states that if a foreign key exists in a relation then either the foreign key value must match a
primary key value of some tuple in its home relation or the foreign key value must be null.
The rules are:
1. You can't delete a record from a primary table if matching records exist in a related table.
2. You can't change a primary key value in the primary table if that record has related records in
foreign table.
3. You can't enter a value in the foreign key field of the related table that doesn't exist in the primary
key of the primary table.
4. However, you can enter a Null value in the foreign key, specifying that the records are unrelated.
o E.g: In a company, every employee works in a specific department, and employee and department
are two different entities. So we can't store the information of the department in the employee table.
That's why we link these two tables through the primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id as a new attribute in the
EMPLOYEE table.
o Now in the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.
Specifying Foreign Key Constraints in SQL
CREATE TABLE Enrolled ( studid INT , cid INT,
grade CHAR(10),
PRIMARY KEY (studid, cid),
FOREIGN KEY (studid) REFERENCES Students)
The foreign key constraint states that every studid value in Enrolled must also appear in Students,
that is, studid in Enrolled is a foreign key referencing Students. Specifically, every studid value
in Enrolled must appear as the value in the primary key field, sid, of Students.
4. General Constraints
Sometimes specifying general constraints (like age should be greater than 18,etc) are necessary.
Current relational database systems support such general constraints in the form of table
constraints and assertions. Table constraints are associated with a single table and checked
whenever that table is modified. In contrast, assertions involve several tables and are checked
whenever any of these tables is modified.
Rename a column
Drop a column
EXAMPLES:
Example:
SELECT id, name, salary FROM employees WHERE salary > 50000;
🔹Modifies the employee_view to show only employees with a salary above 50,000.
Example:
ANS:
A view is virtual tables whose rows are not explicitly stored in the database.
They are used to restrict access to the database or to hide data complexity.
Creating a view does not take any storage space as only the view query is stored in the data
dictionary and the actual data is not stored.
Merits of Views:
Simplified Queries: Views simplify complex queries into a single, user-friendly entity.
ANS:
1. Each entity in the ER model will become a table and all attributes of that entity will become columns
of the table. Key attribute of the entity will become primary key in the table.
2. Each relationship in the ER model will become a table. Key attributes of participating entities in the
relationship will become columns of the table. If the relationship has any attributes, then they also will
become columns of the table.
3. Any multi-valued attribute is converted into new table. The primary key of the entity will be added as
column in the new table.
4. Each weak entity is converted into a table with all its attributes as columns and primary key of the
strong entity acts as a foreign key in this table.
15.Explain the fundamental operations in relational algebra with
examples.(8M).
RELATIONAL ALGEBRA
Relational Algebra is procedural query language, which takes Relation as input and generates relation as
output. Relational algebra mainly provides theoretical foundation for relational databases and SQL.
1.Select Operation (σ):It selects tuples that satisfy the given predicate from a relation.
Notation :σp(r)
where σ stands for selecting tuples (rows) and r stands for relation (table) name.
pis prepositional logic formula which may use connectors like and, or, and not.
SQL Query:
where A1, A2 , An are column (attribute) names of relation r. Duplicate rows are automatically
eliminated in the output.
3.Union Operation (∪):It performs union operation between two given relations. It combines
rows from two given relations.
Notation: r U s
Notation: R ∩ S
Notation: r − s
Notation: ρ(temp, E)
It combines every row in first table with every row in the second table.
Notation: r Χ s
r Χ s = { q t | q ∈ r and t ∈ s}
8.Division (/):
Consider two relation A and B in which A has (exactly) two fields x and y and B has just one field
y, with the same domain as in A.
We define the division operation A / B as the set of all x values (in the form of unary tuples) such
A⊆B
that for every y value in (a tuple of) B, there is a tuple (x,y) in A.
9.
ANS:RELATIONAL CALCULUS
Relational calculus is an alternative to relational algebra.
In contrast to the algebra, which is procedural, the calculus is nonprocedural, or declarative.
It allows us to describe the set of answers without being explicit about how they should be
computed.
Where,
t = resulting tuples,
P(t) = known as Predicate and these are the conditions that are used to fetch t.
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.
∀t∈ r (Q(t))
Example 1:
ANS:
Domain Relational Calculus (DRC) is a non-procedural query language used in relational
databases.
Unlike SQL, which specifies how to retrieve data, DRC focuses on what data to retrieve using
domain variables.
In DRC, queries are written using logical expressions to specify conditions on the attributes
(columns) of a relation (table).
Syntax of DRC
A DRC query is expressed as:
Explanation:
ICs are specified when a relation is created and enforced or imposed when a relation
is modified. The impact of domain, PRIMARY KEY, and UNIQUE constraints is
The following insertion violates the constraint that the primary key cannot contain null.
INSERT
INTO Students (sid, name, login, age, gpa)
VALUES (null, `Mike', `mike@ee', 17, 3.4)
A similar problem arises whenever we try to insert a tuple with a value in a field that
is not in the domain associated with that field, i.e., whenever we violate a domain constraint.
Deletion does not cause a violation of domain, primary key or unique constraints. However,
an update can cause violations, similar to an insertion.
UPDATE Students S
SET S.sid = 50000
WHERE S.sid = 53688
This update violates the primary key constraint because there is already a tuple with
sid 50000.
The impact of foreign key constraints is more complex because SQL sometimes tries
to rectify a foreign key constraint violation instead of simply rejecting the change.
SQL provides several alternative ways to handle foreign key violations. We must
consider three basic questions:
1. What should we do if an Enrolled row is inserted, with a sid column value that does
not appear in any row of the Students table?
In this case the INSERT command is simply rejected.
2. What should we do if a Students row is deleted?
3. What should we do if the primary key value of a Students row is updated?
The options are:
Delete all Enrolled rows that refer to the deleted Students row.
Disallow the deletion of the Students row if an Enrolled row refers to it.
Set the sid column to the sid of some (existing) `default' student, for every Enrolled
row that refers to the deleted Students row.
For every Enrolled row that refers to it, set the sid column to null. In our example, this
option conflicts with the fact that sid is part of the primary key of Enrolled and
therefore cannot be set to null. Thus, we are limited to the first three options in our
example, although this fourth option is setting the foreign key to null is available in
the general case.
The options here are similar to the previous case.
SQL allows us to choose any of the four options on DELETE and UPDATE. For
example, we can specify that when a Students row is deleted, all Enrolled rows that refer to it
are to be deleted as well, but that when the sid column of a Students row is modified, this
update is to be rejected if an Enrolled row refers to the modified Students row.
CREATE TABLE Enrolled (sid CHAR(20),
cid CHAR(20),
grade CHAR(10),
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES Students
ON DELETE CASCADE
ON UPDATE NO ACTION)
The options are specified as part of the foreign key declaration. The default option is
NO ACTION, which means that the action DELETE or UPDATE is to be rejected. Thus, the
ON UPDATE clause in our example could be omitted, with the same effect. The CASCADE
keyword says that if a Students row is deleted, all Enrolled rows that refer to it are to be
deleted as well. If the UPDATE clause specified CASCADE, and the sid column of a
Students row is updated, this update is also carried out in each Enrolled row that refers to the
updated Students row.
If a Students row is deleted, we can switch the enrollment to a `default' student by
using ON DELETE SET DEFAULT. The default student is specified as part of the definition
of the sid field in Enrolled; for example, sid CHAR(20) DEFAULT `53666'. Although the
specification of a default value is appropriate in some situations (e.g., a default parts supplier
if a particular supplier goes out of business), it is really not appropriate to switch enrollments
to a default student. The correct solution in this example is to also delete all enrollment tuples
for the deleted student (that is, CASCADE), or to reject the update.
SQL also allows the use of null as the default value by specifying ON DELETE SET NULL.
ON DELETE CASCADE: Means when a row is deleted from the base relation, then all the
rows which referred to this deleted row in the dependent relation must also be deleted.
ON UPDATE CASCADE: Means when updations are carried in base relation for the
primary key attribute, then all this updations must also be carried out in the dependent
relation or foreign key table.
ON DELETE SET DEFAULT: It means when a row is deleted in employee, then that row
in dependent relation can be set to same default value.
ON DELETE SET NULL: It means on deleting the row in base relation the same row can
be assigned a NULL value in dependent relation.
SQL even provides the facility to delay the applications of constraints on relation and
also immediate application of constraints. This is possible with these two additional
Constraints.
1. DEFERRED Mode
2. IMMEDIATE Mode
The syntax for this constraint is
SET CONSTRAINT constraint name DEFFERED.
SET CONSTRAINT constraint name IMMEDIATE.
Usually, constraints are checked at the end of SQL statements and if the constraints are
violated then the statements are rejected. But with DEFFERED constraints, the Constraints
checks are postponed and are checked at the time of commit.
19.Let R =(ABC) and S=(DEF) let r(R) and s(S) be relations on schema R and
S. Give an expression in the Domain relational calculus that is equivalent to
each of the following. i) σB=25(r) ii) ∏A,F,( σC=D(rXs)). (4M)
Let's break down your request into Domain Relational Calculus expressions:
i) σB=25(r)
This expression in relational algebra represents a selection where the value of attribute B is equal
to 25 in the relation r (with schema R = (ABC)).
This expression represents a projection of attributes A and F after performing a selection on the
Cartesian product of relations r and s, where C = D.
Here:
(a,f)(a, f)(a,f) are the projected attributes, representing the values of A and F.
b,c,d,eb, c, d, eb,c,d,e represent the domain variables for attributes B, C (in relation r), and D, E
(in relation s), respectively.
The condition c = d filters the Cartesian product such that the values of C and D match.
So, for the second part, you first select the tuples where C = D in the Cartesian product, then
project only the A and F values.
20.Consider the following relations Sailors (sid, sname, rating, age) Boats (bid, bname,
color) Reserves (sid, bid, day) Write the statements in Relational Algebra, Relational
Calculus, Domain Relational Calculus and SQL for the following questions. a) Find the
names of sailors who have reserved a Red boat. b) Find the names of sailors who have
reserved at least one boat. c) Find the names of sailors who have reserved a Red and a
Green boat. d) Find the names of sailors who have reserved a Red or a White boat. e) Find
the names of sailors who have reserved all boats(8M)
Given Relations
SQL Query
FROM Sailors S
(b) Find the names of sailors who have reserved at least one boat.
Relational Algebra
SQL Query
FROM Sailors S
(c) Find the names of sailors who have reserved a Red and a Green boat.
Relational Algebra
{ <N> | ∃I ∃R1 ∃R2 ∃J1 ∃J2 ∃B1 ∃B2 ∃C1 ∃C2 (Sailors(I, N, R1, A) ∧ Reserves(I, J1, D1) ∧
Reserves(I, J2, D2) ∧ Boats(J1, B1, C1) ∧ Boats(J2, B2, C2) ∧ C1 = 'Red' ∧ C2 = 'Green') }
SQL Query
FROM Sailors S
(d) Find the names of sailors who have reserved a Red or a White boat.
Relational Algebra
SQL Query
FROM Sailors S
(e) Find the names of sailors who have reserved all boats.
Relational Algebra
SQL Query
FROM Sailors S
);
21.Consider the following relational schema. Student (id,name, age, city)Retrieve the names of all students.
Display the id’s of all students who are having age above 20.Display the names and id’s of all students who are
having age between 20 and 25 and lives in Hyderabad city.
1.Consider the following relational schema. Student (id,name, age, city)
A user can define a new domain using the CREATE DOMAIN statement, which uses CHECK
constraints.
Syntax :
CREATE DOMAIN domain_name AS data_type
CHECK (value specification)
Example
CREATE DOMAIN RATINGVAL AS INT CHECK
(value >= 0 AND value <= 10);
INTEGER is the underlying, or source, type for the domain ratingval, and every ratingval value must
be of this type. Values in ratingval are further restricted by using a CHECK constraint. In defining
this constraint, we use the keyword VALUE to refer to a value in the domain.
Now RATINGVAL domain is created so, we can use this domain anywhere in any table of database
as shown below:
CREATE TABLE student( Sid INT PRIMARY KEY,
name varchar(30), rating RATINGVAL
);
The optional DEFAULT keyword can also be used to associate a default value with a domain. If the
domain ratingval is used for a column in some relation and no value is entered for this column, then
default value associated with ratingval will be used.
DEFAULT CONSTRAINT
The DEFAULT constraint is used to provide a default value for a column. The default value will be
added to all new records if no other value is specified.
Example:
CREATE TABLE Persons(
ID int NOT NULL, LastName varchar(25) NOT NULL , FirstName varchar(25), Age int; City
varchar(25) DEFAULT 'Sandnes'
); Assertions: ICs over Several Tables
Assertions are constraints over several tables. It is a condition that we wish the database should
always satisfy.
Syntax
CREATE ASSERTION <Constraint name> CHECK (search condition)
[ <constraint attributes> ]
Example:
Suppose the constraint is that the number of boats plus the number of sailors should be less than
100. Here the constraint is on both- boat table as well as on sailor table. In such cases we create
assertions.
23.Define trigger and explain its three parts? Differentiate row level and statement level triggers.
A trigger is a procedure that is automatically invoked by the DBMS in response to specified changes
to the database, and is typically specified by the DBA. For example, a trigger can be invoked when a
row is inserted into a specified table or when certain table columns are being updated.
A trigger description contains three parts:
Event: A change to the database that activates the trigger.
Condition: A query or test that is run when the trigger is activated.
Action: A procedure that is executed when the trigger is activated and its condition is true.
There are two types of triggers
Row Level Trigger
Row Level Trigger is fired each time row is affected by Insert, Update or Delete command. To create
a new row-level trigger, you use the CREATE TRIGGER statement with the FOR EACH ROW
clause.
Statement-level Trigger
A statement-level trigger is fired whenever a trigger event occurs on a table regardless of how many
rows are affected. In other words, a statement-level trigger executes once for each transaction. By
default, the statement CREATE TRIGGER creates a statement-level trigger when you omit the FOR
EACH ROW clause.
Syntax:
create trigger [trigger_name] [before | after]
{insert | update | delete} on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. The table_name is the table to which the trigger applies.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row
being affected. In case of statement level trigger this line is simply omitted.
6. [trigger_body]: This provides the operation to be performed as trigger is fired
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the triggering statement is run. AFTER triggers run
the trigger action after the triggering statement is run.
Example program UPDATE TRIGGER
CREATE TRIGGER TT BEFORE UPDATE ON STD FOR EACH ROW
BEGIN
IF NEW.marks < 0 THEN
SET NEW.marks = 0;
ELSEIF NEW.marks > 100 THEN SET NEW.marks = 100;
END IF; END;
$$
Triggers are mostly used for maintaining the integrity of the information on the database and to avoid
redundancy.
24.Elaborate on Nested Queries and Correlated nested queries in SQL.
NESTED QUERIES
A nested query is a query that has another query embedded within it. The outer query is known as
the main query, and the inner query is known as a subquery.
The result of inner query is used in execution of outer query.
A subquery typically appears within the WHERE clause of a query.
1. Independent Nested Queries: The execution of inner query is independent of outer query, but the
result of inner query is used in execution of outer query. Various operators like IN, NOT IN, ANY,
ALL etc are used in writing independent nested queries.
IN: The IN operator is used when you want to compare a column with more than one value. It
allows us to test whether a value is in a given set of elements or not.
Example:
The nested subquery computes the set of sids for sailors who have reserved boat 103 (the set contains
22, 31, and 74),and the top-level query retrieves the names of sailors whose sid is in this set.
Result:
NOT IN: The NOT IN operator is used when you want to retrieve a column that has no entries in
the table or referencing table.
Example:
To find the names of sailors who have not reserved boat 103, we replace the outermost occurrence of
IN by NOT IN
Result:
Multiply Nested Query: A subquery can contain another query, making it a multiply nested
query.
Example:
Find the names of sailors who have reserved a red boat.
The innermost subquery finds the set of bids of red boats (102 and 104 from Boats). The subquery
one level above finds the set of sids of sailors who have reserved one of these boats. (22, 31, and 64
from Sailor). The top-level query finds the names of sailors whose sid is in this set of sids; we get
Dustin, Lubber, and Horatio.
2. Co-related Nested Queries: In co-related nested queries, the output of inner query depends on the
row which is being currently executed in outer query. Operators Exists and Not Exists are used in
writing correlated nested queries.
EXISTS: The EXISTS operator is another set comparison operator, such as IN. It allows us to test
whether a set is nonempty (an implicit comparison with the empty set )
Example:
Find the names of sailors who have reserved boat number 103.
For each Sailor row S, we test whether the set of Reserves rows R such that R.bid = 103 AND S.sid =
R.sid is nonempty. If so, sailor S has reserved boat 103, and we retrieve the name. The subquery
clearly depends on the current row S and must be re-evaluated for each row in Sailors. The
occurrence of S in the subquery (in the form of the literal S.sid) is called a correlation and such
queries are called correlated queries.
Result:
(Note that we are omitting S.sid here. That’s because we are not testing whether a value (S.sid)
is in a given set of elements or not, instead we are testing whether a set is nonempty. The above
query also illustrates the use of the special symbol * in situations where all we want to do is to
check that a qualifying row exists, and do not really want to retrieve any columns from the
row.)
NOT EXISTS : The EXISTS condition can also be combined with the NOT operator. The NOT
operator negates the EXISTS operator.
As a example, by using NOT EXISTS instead of EXISTS, we can compute the names of sailors who
have not reserved a red boat.
Example:
Result: