100% found this document useful (1 vote)
258 views

DBMS Answer Key

The document discusses three-tier architecture in database management systems. It explains that three-tier architecture organizes applications into presentation, application, and data tiers. The presentation tier handles the user interface. The application tier processes data using business logic. The data tier stores and manages the data. Communication only occurs between tiers, improving scalability, reliability, and security.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
258 views

DBMS Answer Key

The document discusses three-tier architecture in database management systems. It explains that three-tier architecture organizes applications into presentation, application, and data tiers. The presentation tier handles the user interface. The application tier processes data using business logic. The data tier stores and manages the data. Communication only occurs between tiers, improving scalability, reliability, and security.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

DBMS Question Bank

Q1. Explain the three-tier architecture of Data base Management System. (4)
Ans:

Three-tier architecture is a well-established software application architecture that organizes


applications into three logical and physical computing tiers: the presentation tier, or user
interface; the application tier, where data is processed; and the data tier, where the data
associated with the application is stored and managed.

The Three Tiers in detail


Presentation tier

 The presentation tier is the user interface and communication layer of the application,
where the end user interacts with the application.
 Its main purpose is to display information to and collect information from the user.
 This top-level tier can run on a web browser, as desktop application, or a graphical user
interface (GUI), for example. Web presentation tiers are usually developed using HTML,
CSS and JavaScript.
 Desktop applications can be written in a variety of languages depending on the platform.

Application tier

 The application tier, also known as the logic tier or middle tier, is the heart of the
application.
 In this tier, information collected in the presentation tier is processed - sometimes against
other information in the data tier - using business logic, a specific set of business rules.
 The application tier can also add, delete or modify data in the data tier.
 The application tier is typically developed using Python, Java, Perl, PHP or Ruby, and
communicates with the data tier using API calls.
Data tier

 The data tier, sometimes called database tier, data access tier or back-end, is where the
information processed by the application is stored and managed.
 This can be a relational database management system such as PostgreSQL, MySQL,
MariaDB, Oracle, DB2, Informix or Microsoft SQL Server, or in a NoSQL Database server
such as Cassandra, CouchDB or MongoDB.

In a three-tier application, all communication goes through the application tier. The presentation
tier and the data tier cannot communicate directly with one another.

Benefits (compared to single- or two-tier architecture) include:

 Faster development: Because each tier can be developed simultaneously by different


teams, an organization can bring the application to market faster, and programmers can
use the latest and best languages and tools for each tier.
 Improved scalability: Any tier can be scaled independently of the others as needed.
 Improved reliability: An outage in one tier is less likely to impact the availability or
performance of the other tiers.
 Improved security: Because the presentation tier and data tier can't communicate
directly, a well-designed application tier can function as a sort of internal firewall,
preventing SQL injections and other malicious exploits.

Q2.A company called M/s ABC Consultants Ltd. Has an entity EMPLOYEE with
a number of employees having attributes such as EMP-ID, EMP-NAME, EMP-
ADD and EMP-BDATE. The company has another entity PROJECT that has
several projects having attributes such as PROJ-ID, PROJ-NAME and START-
DATE. Each employee may be assigned to one or more projects or may not be
assigned to one or more projects. A project must have at least one employee
assigned and may have any number of employees assigned. An employee’s
billing rate may vary by project, and the company wishes to record the
applicable billing rate (BILL-RATE) for each employee when assigned to a
particular project.
By making additional assumptions, if so required, draw an E-R diagram for the
above situation. (6)
Ans:
1.

2. Cardinality of the relationship

 Since it is mentioned that an employee is associated with 0, 1 or more projects


and each project must have at least one employee associated with it
 So, from EMPLOYEE to PROJECT IS (M:M) many to many
 Now since an employee can be associated with many projects, so for every
project he is associated with it a BILL_DATE is generated.
 but for a particular project and an employee only one bill date is generated
 So, from EMPLOYEE to BILL_DATE is (1:M)

3.

EMPLOYEE(EMP_ID, EMP_NAME, EMP_ADD, EMP_BDATE)

PROJECT(PROJ_ID, PROJ_NAME, START_DATE)

BILL_DATE(EMP_ID,PROJ_ID,PROJ_COST)

The primary keys are underlined and bold.

Q3. Differentiate between Hierarchical, Network & Relational Database


Management Systems. (6)
Ans:
Hierarchical model vs Network model vs Relational
model:
Hierarchical Data Model Network Data Model Relational Data Model

1. Relationship between 1. Relationship between 1.Relationship between records is


records is of the parent records is expressed in represented by a relation that
child type. the form of pointers or contains a key for each record
links. involved in the relationship.

2. Many to many 2. Many to many 2. Many to many relationship can


relationship cannot be relationship can also be be easily implemented.
expressed in this model implemented in this
model

3. It is a simple, 3. Record relationship 3. Relationship implementation is


straightforward and implementation is quite very easy through the use of a key
natural method of complex due to the use or composite key field.
implementing record of pointers.
relationships.

4. This type of model is 4. Network model is 4. Relational model is useful for


useful only when there is useful for representing representing most of the real
some hierarchical such records which have world objects and relationships
character in the database. many to many among them.
relationships.

5. Searching for a record is 5. Searching for a record 5. A unique, indexed key field is
very difficult since one can is easy since there are used to search for a data element.
retrieve a child only after multiple access paths to
going through its parent a data element.
record.

6. In Hierarchical model 6.In Network model 6. Relational model does not


record relations are record relations are maintain physical connection
physical. physical. among records, data is organized
logically in the form of rows and
columns and stored in table.

7. During updation or 7. No problem of 7. Data integrity maintaining


deletion process, chances inconsistency exists in methods like Normalization
of data inconsistency is Network model. process are adopted for
involved. consistency.
Q4. Explain Categorization and Aggregation with the help of EER Diagram.

EER Model

EER is a high-level data model that incorporates the extensions to the original ER model.

It is a diagrammatic technique for displaying the following concepts

 Sub Class and Super Class


 Specialization and Generalization
 Union or Category
 Aggregation
These concepts are used when the comes in EER schema and the resulting schema
diagrams called as EER Diagrams.

Features of EER Model

 EER creates a design more accurate to database schemas.


 It reflects the data properties and constraints more precisely.
 It includes all modeling concepts of the ER model.
 Diagrammatic technique helps for displaying the EER schema.
 It includes the concept of specialization and generalization.
 It is used to represent a collection of objects that is union of objects of different of
different entity types.
A. Sub Class and Super Class

 Sub class and Super class relationship leads the concept of Inheritance.

 The relationship between sub class and super class is denoted with symbol.
1. Super Class

 Super class is an entity type that has a relationship with one or more subtypes.
 An entity cannot exist in database merely by being member of any super class.
For example: Shape super class is having sub groups as Square, Circle, Triangle.
2. Sub Class

 Sub class is a group of entities with unique attributes.


 Sub class inherits properties and attributes from its super class.
For example: Square, Circle, Triangle are the sub class of Shape super class.
B. Specialization and Generalization

1. Generalization

 Generalization is the process of generalizing the entities which contain the


properties of all the generalized entities.
 It is a bottom approach, in which two lower level entities combine to form a higher
level entity.
 Generalization is the reverse process of Specialization.
 It defines a general entity type from a set of specialized entity type.
 It minimizes the difference between the entities by identifying the common
features.
For example:

In the above example, Tiger, Lion, Elephant can all be generalized as Animals.
2. Specialization

 Specialization is a process that defines a group entities which is divided into sub
groups based on their characteristic.
 It is a top down approach, in which one higher entity can be broken down into two
lower level entity.
 It maximizes the difference between the members of an entity by identifying the
unique characteristic or attributes of each member.
 It defines one or more sub class for the super class and also forms the
superclass/subclass relationship.
For example

In the above example, Employee can be specialized as Developer or Tester, based on


what role they play in an organization.

3. Aggregation

 Aggregation is a process that represent a relationship between a whole object and


its component parts.
 It abstracts a relationship between objects and viewing the relationship as an
object.
 It is a process when two entity is treated as a single entity.

In the above example, the relation between College and Course is acting as an Entity in
Relation with Student.
Q5. Define the following terms:
(a) DBMS
(b) Data Independence
Ans:
a. Database management systems are software systems used to manage and
manipulate data in a database. As most application performance issues originate in
the database, knowing how to monitor and optimize your database is essential to
your operations.

Data Independence
o Data independence can be explained using the three-schema architecture.
o Data independence refers characteristic of being able to modify the schema at one level of the
database system without altering the schema at the next higher level.

There are two types of data independence:

1. Logical Data Independence


o Logical data independence refers characteristic of being able to change the conceptual schema
without having to change the external schema.
o Logical data independence is used to separate the external level from the conceptual view.
o If we do any changes in the conceptual view of the data, then the user view of the data would not be
affected.
o Logical data independence occurs at the user interface level.

2. Physical Data Independence


o Physical data independence can be defined as the capacity to change the internal schema without
having to change the conceptual schema.
o If we do any changes in the storage size of the database system server, then the Conceptual structure
of the database will not be affected.
o Physical data independence is used to separate conceptual levels from the internal levels.
o Physical data independence occurs at the logical interface level.
Q6. How is traditional file processing approach different than DBMS
approach? Explain.
Difference between File System and DBMS:
Basis File System DBMS

The file system is software that manages and


organizes the files in a storage medium within DBMS is software for managing
Structure a computer. the database.

Data Redundant data can be present in a file In DBMS there is no redundant


Redundancy system. data.

Backup and It doesn’t provide backup and recovery of It provides backup and recovery
Recovery data if it is lost. of data even if it is lost.

Query There is no efficient query processing in the Efficient query processing is there
processing file system. in DBMS.

There is more data consistency


There is less data consistency in the file because of the process of
Consistency system. normalization.

It has more complexity in


handling as compared to the file
Complexity It is less complex as compared to DBMS. system.

DBMS has more security


Security File systems provide less security in mechanisms as compared to file
Constraints comparison to DBMS. systems.
Basis File System DBMS

It has a comparatively higher cost


Cost It is less expensive than DBMS. than a file system.

Data In DBMS data independence


Independence There is no data independence. exists.

Multiple users can access data at a


User Access Only one user can access data at a time. time.

The user has to write procedures for The user not required to write
Meaning managing databases procedures.

Data is distributed in many files. So, not easy Due to centralized nature sharing
Sharing to share data is easy

Data It give details of storage and representation of It hides the internal details of
Abstraction data Database

Integrity Integrity Constraints are difficult to Integrity constraints are easy to


Constraints implement implement

Example Cobol, C++ Oracle, SQL Server

Q7. What do you mean by generalization and specialization? Explain (Diagram


also).
Q8. Define the referential integrity constraints in Relational Databases with
suitable example.
Ans:

Referential integrity
Referential integrity requires that a foreign key must have a matching primary key
or it must be null. This constraint is specified between two tables (parent and
child); it maintains the correspondence between rows in these tables. It means the
reference from a row in one table to another table must be valid.

Examples of referential integrity constraint in the Customer/Order database of the


Company:
 Customer(CustID, CustName)
 Order(OrderID, CustID, OrderDate)

To ensure that there are no orphan records, we need to enforce referential


integrity. An orphan record is one whose foreign key FK value is not found in the
corresponding entity – the entity where the PK is located. Recall that a typical join
is between a PK and FK.

The referential integrity constraint states that the customer ID (CustID) in the
Order table must match a valid CustID in the Customer table. Most relational
databases have declarative referential integrity. In other words, when the tables
are created the referential integrity constraints are set up.

Here is another example from a Course/Class database:

 Course(CrsCode, DeptCode, Description)


 Class(CrsCode, Section, ClassTime)

The referential integrity constraint states that CrsCode in the Class table must
match a valid CrsCode in the Course table. In this situation, it’s not enough that the
CrsCode and Section in the Class table make up the PK, we must also enforce
referential integrity.

Q9. Why we may choose to define a view?


Ans:
A view provides several benefits.
1. Views can hide complexity
If you have a query that requires joining several tables, or has complex logic or calculations, you
can code all that logic into a view, then select from the view just like you would a table.

2. Views can be used as a security mechanism


A view can select certain columns and/or rows from a table (or tables), and permissions set on
the view instead of the underlying tables. This allows surfacing only the data that a user needs to
see.

3. Views can simplify supporting legacy code


If you need to refactor a table that would break a lot of code, you can replace the table with a view
of the same name. The view provides the exact same schema as the original table, while the actual
schema has changed. This keeps the legacy code that references the table from breaking, allowing
you to change the legacy code at your leisure.

Q10. What is a relation? What are primary, candidate and foreign keys? (4)
Ans:
A relationship in a DBMS is primarily the way two or more data sets are linked. This is so true
for Relational Database Management Systems. One dataset may be then termed as the
foreign key and the ones linked to it may be termed the Primary Key. There may be multiple
Foreign and Primary keys linked to each other.

Relationships allow the datasets to share and store the data in separate tables. They also help
link disparate data with each other.

1. Primary key

o It is the first key used to identify one and only one instance of an entity uniquely. An entity can contain
multiple keys, as we saw in the PERSON table. The key which is most suitable from those lists becomes
a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each employee. In the
EMPLOYEE table, we can even select License_Number and Passport_Number as primary keys since
they are also unique.
o For each entity, the primary key selection is based on requirements and developers.

2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
o Except for the primary key, the remaining attributes are considered a candidate key. The candidate
keys are as strong as the primary key.

For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the attributes,
like SSN, Passport_Number, License_Number, etc., are considered a candidate key.

3.Foreign key

o Foreign keys are the column of the table used to point to the primary key of another table.
o Every employee works in a specific department in a company, and employee and department are two
different entities. So we can't store the department's information 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 In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.
Q11. Consider the following relational schema (6)
Account (account-number, branch-name, balance)
Loan (Loan-number, branch-name, balance)
Depositor (Customer-name, Account-number)
Borrower (Customer-name, Loan-number)
Formulate the relational algebra statements for the following (Assume keys
and additional information (as per requirement):
(a) Find all loan numbers for loan made at Bombay branch.
(b) Find all customers who have both a loan and an account at the bank.
(c) Find the average account balance at each branch.
(d) Find the number of depositors at each branch.
Q12. Describe the Join Operation. What does it accomplish? (3)
JOINS in SQL are commands which are used to combine rows from two or more tables, based
on a related column between those tables. There are predominantly used when a user is trying
to extract data from tables which have one-to-many or many-to-many relationships between
them.

Now, that you know what joins mean, let us next learn the different types of joins.

How many types of Joins are there in SQL?


There are mainly four types of joins that you need to understand. They are:

 INNER JOIN
 FULL JOIN
 LEFT JOIN
 RIGHT JOIN

You can refer to the below image.


How do I know which join to use in SQL?
Let us look into each one of them. For your better understanding of this concept, I will be
considering the following three tables to show you how to perform the Join operations on such
tables.

Employee Table:

EmpID EmpFname EmpLname Age EmailID PhoneNo Address

1 Vardhan Kumar 22 vardy@abc.com 9876543210 Delhi

2 Himani Sharma 32 himani@abc.com 9977554422 Mumbai

3 Aayushi Shreshth 24 aayushi@abc.com 9977555121 Kolkata

4 Hemanth Sharma 25 hemanth@abc.com 9876545666 Bengaluru

5 Swatee Kapoor 26 swatee@abc.com 9544567777 Hyderabad

Project Table:

ProjectID EmpID ClientID ProjectName ProjectStartDate

111 1 3 Project1 2019-04-21

222 2 1 Project2 2019-02-12

333 3 5 Project3 2019-01-10

444 3 2 Project4 2019-04-16

555 5 4 Project5 2019-05-23

666 9 1 Project6 2019-01-12

777 7 2 Project7 2019-07-25

888 8 3 Project8 2019-08-20

Client Table:

ClientID ClientFname ClientLname Age ClientEmailID PhoneNo Address EmpID

1 Susan Smith 30 susan@adn.com 9765411231 Kolkata 3

2 Mois Ali 27 mois@jsq.com 9876543561 Kolkata 3

3 Soma Paul 22 soma@wja.com 9966332211 Delhi 1

4 Zainab Daginawala 40 zainab@qkq.com 9955884422 Hyderabad 5

5 Bhaskar Reddy 32 bhaskar@xyz.com 9636963269 Mumbai 2

INNER JOIN
This type of join returns those records which have matching values in both tables. So, if you
perform an INNER join operation between the Employee table and the Projects table, all the
tuples which have matching values in both the tables will be given as output.

Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.Column1,....
FROM Table1
INNER JOIN Table2
ON Table1.MatchingColumnName = Table2.MatchingColumnName;
NOTE: You can either use the keyword INNER JOIN or JOIN to perform this operation.

Example:
1 SELECT Employee.EmpID, Employee.EmpFname, Employee.EmpLname, Projects.ProjectID,
Projects.ProjectName
2 FROM Employee
3 INNER JOIN Projects ON Employee.EmpID=Projects.EmpID;

Output:
EmpID EmpFname EmpLname ProjectID ProjectName

1 Vardhan Kumar 111 Project1

2 Himani Sharma 222 Project2

3 Aayushi Shreshth 333 Project3

3 Aayushi Shreshth 444 Project4

5 Swatee Kapoor 555 Project5

FULL JOIN

Full Join or the Full Outer Join returns all those records which either have a match in the
left(Table1) or the right(Table2) table.

Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.Column1,....
FROM Table1
FULL JOIN Table2
ON Table1.MatchingColumnName = Table2.MatchingColumnName;
Example:
1 SELECT Employee.EmpFname, Employee.EmpLname, Projects.ProjectID

2 FROM Employee

3 FULL JOIN Projects

4 ON Employee.EmpID = Projects.EmpID;

Output:
EmpFname EmpLname ProjectID

Vardhan Kumar 111

Himani Sharma 222


Aayushi Shreshth 333

Aayushi Shreshth 444

Hemanth Sharma NULL

Swatee Kapoor 555

NULL NULL 666

NULL NULL 777

NULL NULL 888

LEFT JOIN

The LEFT JOIN or the LEFT OUTER JOIN returns all the records from the left table and also those
records which satisfy a condition from the right table. Also, for the records having no matching
values in the right table, the output or the result-set will contain the NULL values.

Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.Column1,....
FROM Table1
LEFT JOIN Table2
ON Table1.MatchingColumnName = Table2.MatchingColumnName;
Example:
1 SELECT Employee.EmpFname, Employee.EmpLname, Projects.ProjectID,
Projects.ProjectName
2
FROM Employee
3 LEFT JOIN
4 ON Employee.EmpID = Projects.EmpID ;

Output:
EmpFname EmpLname ProjectID ProjectName

Vardhan Kumar 111 Project1

Himani Sharma 222 Project2

Aayushi Shreshth 333 Project3

Aayushi Shreshth 444 Project4

Swatee Kapoor 555 Project5

Hemanth Sharma NULL NULL

RIGHT JOIN

The RIGHT JOIN or the RIGHT OUTER JOIN returns all the records from the right table and also
those records which satisfy a condition from the left table. Also, for the records having no
matching values in the left table, the output or the result-set will contain the NULL values.
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.Column1,....
FROM Table1
RIGHT JOIN Table2
ON Table1.MatchingColumnName = Table2.MatchingColumnName;
Example:
1 SELECT Employee.EmpFname, Employee.EmpLname, Projects.ProjectID,
Projects.ProjectName
2
FROM Employee
3 RIGHT JOIN
4 ON Employee.EmpID = Projects.EmpID;

Output:
EmpFname EmpLname ProjectID ProjectName

Vardhan Kumar 111 Project1

Himani Sharma 222 Project2

Aayushi Shreshth 333 Project3

Aayushi Shreshth 444 Project4

Swatee Kapoor 555 Project5

NULL NULL 666 Project6

NULL NULL 777 Project7

NULL NULL 888 Project8

Now, let us move forward with our next section in this article i.e. the top questions asked
about SQL Joins in your interviews.

Most Common Questions asked about Joins


Question 1: What is a Natural Join and in which situations is a natural join
used?

Solution:

A Natural Join is also a Join operation that is used to give you an output based on the columns
in both the tables between which, this join operation must be implemented. To understand the
situations n which natural join is used, you need to understand the difference between Natural
Join and Inner Join.

The main difference the Natural Join and the Inner Join relies on the number of columns
returned. Refer below for example.
Now, if you apply INNER JOIN on these 2 tables, you will see an output as below:

If you apply NATURAL JOIN, on the above two tables, the output will be as below:

From the above example, you can clearly see that the number of columns returned from the
Inner Join is more than that of the number of columns returned from Natural Join. So, if you
wish to get an output, with less number of columns, then you can use Natural Join

Q13. Give relational schema for SUPPLIER-PART database where different


suppliers supplying various parts at different rates and each part is supplied by
a number of suppliers. Assuming that the following are meaningful, state the
integrity constraints; additional assumptions may be made for the job at hand.
(4)
(a) Retrieve names of the cities from which part P2 may be supplied.
(b) Retrieve supplier numbers of suppliers who are capable of supplying all
parts.
(c) Reformulate the above queries in SQL.
Q14.What do you mean by Data Model. Explain some features of hierarchal
data model.
In PDF.
Q16.What do you mean by nested queries. Give examples.
Ans:
A nested query in SQL contains a query inside another query. The result of the inner query will be used
by the outer query. For instance, a nested query can have two SELECT statements, one on the inner
query and the other on the outer query.

Examples of Nested Query in SQL


We will use the Employees and Awards table below to understand independent and co-related nested
queries. We will be using Oracle SQL syntax in our queries.

Let's create the Employees and Awards tables:

CREATE TABLE employee (


id NUMBER PRIMARY KEY,
name VARCHAR2(100) NOT NULL,
salary NUMBER NOT NULL,
role VARCHAR2(100) NOT NULL
);
CREATE TABLE awards(
id NUMBER PRIMARY KEY,
employee_id NUMBER NOT NULL,
award_date DATE NOT NULL
);

Let's add data to the tables created above:

INSERT INTO employees VALUES (1, 'Augustine Hammond', 10000, 'Developer');


INSERT INTO employees VALUES (2, 'Perice Mundford', 10000, 'Manager');
INSERT INTO employees VALUES (3, 'Cassy Delafoy', 30000, 'Developer');
INSERT INTO employees VALUES (4, 'Garwood Saffen', 40000, 'Manager');
INSERT INTO employees VALUES (5, 'Faydra Beaves', 50000, 'Developer');
INSERT INTO awards VALUES(1, 1, TO_DATE('2022-04-01', 'YYYY-MM-DD'));
INSERT INTO awards VALUES(2, 3, TO_DATE('2022-05-01', 'YYYY-MM-DD'));

Employees

id name salary role

1 Augustine Hammond 10000 Developer


id name salary role

2 Perice Mundford 10000 Manager

3 Cassy Delafoy 30000 Developer

4 Garwood Saffen 40000 Manager

5 Faydra Beaves 50000 Developer

Awards

id employee_id award_date

1 1 2022-04-01

2 3 2022-05-01

Independent Nested Queries

Example 1: IN

Select all employees who won an award.

SELECT id, name FROM employees


WHERE id IN (SELECT employee_id FROM awards);

Output

id name

2 Perice Mundford

4 Garwood Saffen

5 Faydra Beaves

Example 2: NOT IN

Select all employees who never won an award.

SELECT id, name FROM employees


WHERE id NOT IN (SELECT employee_id) FROM awards);

Output

id name

1 Augustine Hammond

3 Cassy Delafoy

Example 3: ALL

Select all Developers who earn more than all the Managers
SELECT * FROM employees
WHERE role = 'Developer'
AND salary > ALL (
SELECT salary FROM employees WHERE role = 'Manager'
);

Output

id name salary role

5 Faydra Beaves 50000 Developer

Explanation

The developer with id 5 earns (50000) more than all the managers: 2 (10000) and 4 (40000)

Example 4: ANY

Select all Developers who earn more than any Manager

SELECT * FROM employees


WHERE role = 'Developer'
AND salary > ANY (
SELECT salary FROM employees WHERE role = 'Manager'
);

Output

id name salary role

5 Faydra Beaves 50000 Developer

3 Cassy Delafoy 30000 Developer

Explanation

The developers with id 3 and 5 earn more than any manager:

 The developer with id 3 earns (30000) more than the manager with id 2 (10000)
 The developer with id 5 earns (50000) more than the managers with id 2 (10000) and 4 (40000)

Co-related Nested Queries

Select all employees whose salary is above the average salary of employees in their role.

SELECT * FROM employees emp1


WHERE salary > (
SELECT AVG(salary) FROM employees emp2
WHERE emp1.role = emp2.role
);

Output

id name salary role

4 Garwood Saffen 40000 Manager


id name salary role

5 Faydra Beaves 50000 Developer

Explanation

The manager with id 4 earns more than the average salary of all managers (25000), and the developer with
id 5 earns more than the average salary of all developers (30000). The inner query is executed for all rows
fetched by the outer query. The role value (emp1.role) of every outer query's row is used by the inner query
(emp1.role = emp2.role).

We can find the average salary of managers and developers using the below query:

SELECT role, AVG(salary) FROM employees GROUP BY role;


role avg(salary)

Developer 30000

Manager 25000

Q17. Define ACID property of a transaction.

ACID stands for Atomicity, Consisency, Isolation, and Durbility property. Multiple users can share
data in a safe and secure way using these properties.

Atomicity:

 Atomicity is based on the principle of “either all or nothing” which means that if any updates happens
inside the database then that updates should be available for others beyond user and application.
 If any updates happens inside the database then that updates should not be available for others
beyond user and application.

Consistency:

 Inside a database before or after any transaction takes place this ensures that consistency is
maintained.

Isolation:

 This property states that happens in isolation with other which means that any transactions that has
started but not yet completed should be in isolation with others so that the other transactions are not
affected by this transaction.

Durability:
 This property states that the data should always be in a durable state i.e. any data which is in the
committed state should be available in the same state even if any failure or restart occurs in the system

Q18. Define a view in SQL. Show with suitable example that insertion of tuple
through view may not be possible.
Q19. Explain with suitable example the creation and modification of a
relational schema in SQL.
Creating a basic table involves naming the table and defining its columns and each column's data
type.
The SQL CREATE TABLE statement is used to create a new table.

Syntax
The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this case, you
want to create a new table. The unique name or identifier for the table follows the CREATE TABLE
statement.
Then in brackets comes the list defining each column in the table and what sort of data type it is.
The syntax becomes clearer with the following example.
A copy of an existing table can be created using a combination of the CREATE TABLE statement
and the SELECT statement. You can check the complete details at Create Table Using another
Table.

Modification:
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used
to add and drop various constraints on the existing table.
ALTER TABLE – ADD
ADD is used to add columns into the existing table. Sometimes we may require to add additional
information, in that case we do not require to create the whole database again, ADD comes to our
rescue.
Syntax:
ALTER TABLE table_name
ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);

ALTER TABLE – DROP


DROP COLUMN is used to drop column in a table. Deleting the unwanted columns from the table.
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;

ALTER TABLE-MODIFY
It is used to modify the existing columns in a table. Multiple columns can also be modified at once.
*Syntax may vary slightly in different databases.
Syntax(Oracle,MySQL,MariaDB):
ALTER TABLE table_name
MODIFY column_name column_type;
Syntax(SQL Server):
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
Queries
Sample Table:
Student
ROLL_NONAME
1 Ram

2 Abhi

3 Rahul

4 Tanu

QUERY:
 To ADD 2 columns AGE and COURSE to table Student.
ALTER TABLE Student ADD (AGE number(3),COURSE varchar(40));
OUTPUT:
ROLL_NONAME AGECOURSE
1 Ram

2 Abhi

3 Rahul

4 Tanu

 MODIFY column COURSE in table Student


ALTER TABLE Student MODIFY COURSE varchar(20);
After running the above query maximum size of Course Column is reduced to 20 from 40.
 DROP column COURSE in table Student.
ALTER TABLE Student DROP COLUMN COURSE;
OUTPUT:
ROLL_NONAME AGE
1 Ram

2 Abhi

3 Rahul

4 Tanu

You might also like