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

UNIT-1 Solved

The document outlines the course details for Database Management Systems, including various SQL queries, database design principles, and integrity constraints. It covers topics such as creating tables, using SQL functions, and performing different types of joins. Additionally, it provides examples of SQL commands and their syntax for data retrieval and manipulation.

Uploaded by

Aruna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

UNIT-1 Solved

The document outlines the course details for Database Management Systems, including various SQL queries, database design principles, and integrity constraints. It covers topics such as creating tables, using SQL functions, and performing different types of joins. Additionally, it provides examples of SQL commands and their syntax for data retrieval and manipulation.

Uploaded by

Aruna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Regulation: 2019 Academic Year 2022-2023

COURSE DETAILS –DATABASE MANAGEMENT SYSTEMS

UNIT I – RELATIONAL DATABASES

Course Code : 19UCSPC301


Course Name : DATABASE MANAGEMENT SYSTEMS
Semester/Year : B.E (CSE) III SEMESTER/ /II YEAR
Offered By : CSE & IT
Prepared By :Mrs.K.KAVITHA AP/CSE
Part-A
5. Analyse the integrity constraints satisfied for the data values to be stored in the
database?
When designing a database application, developers have various options for guaranteeing the
integrity of data stored in the database. These options include:
 Enforcing business rules with triggered stored database procedures,
 Using stored procedures to completely control access to data,
 Enforcing business rules in the code of a database application
 Using Database integrity constraints, which are rules defined at the column or object
level that restrict values in the database.

13. Assume that a procedure has to be called in JDBC, which statement is used for that
purpose?
The Informix JDBC driver provides the Statement, PreparedStatement, and CallableStatement
methods, which can be used to execute stored procedures. The method we use depends on the
characteristic of the stored procedure. For example, if the stored procedure returns a single
value, you should use a JDBC Statement object. The following table provides some guidelines
for what method to use for which stored procedure type.
Stored procedure type JDBC method
Stored procedure requires no IN or OUT
parameters Use a Statement object
Stored procedure with IN parameters Use a PreparedStatement object
Stored procedure with IN and OUT
parameters Use a CallableStatement object
18. Create Tables as follows by choosing appropriate data type and set the necessary
primary and foreign key constraints: Product (Prodid, Prodesc, Price, Stock)
Purchase (Purid, Proid, qty), Add a column customer name in Purchase table.
Create table product( prodid number(10), prodesc varchar(10), price number(10), stock
number(10), primary key (prodid));
Create table purchase(purid number(10), proid number(10) references product, qty
number(10),primary key (purid));
Alter table purchase add (cust_name varchar(10));

19. Consider the following


relation Jedi-Teams (master,
apprentice)
Jedi(name, side, home-planet)
Government(leader planet, postition)
Inhabitants(specie, planet)
Given a query to find all planetary leaders who are apprentices and use the dark side of the
force and give the query in relational algebra expression
Regulation: 2019 Academic Year 2022-2023

SQL Query select leader from Jedi-Teams, Jedi, Government where apprentice = name and name
= leader and side = 'dark'
Relational algebra

25. Find out a way to fetch alternate records from a table?


Let us consider rownum and MOD function for retrieving the alternate records from a
table.
To get Even number records:

SELECT *
FROM ( SELECT rownum rn, empno, ename
FROM emp
) temp
WHERE MOD(temp.rn,3) = 0

To get Odd number records:

SELECT *
FROM ( SELECT rownum rn, empno, ename
FROM emp
) temp
WHERE MOD(temp.rn,2) = 1

26. Consider there are certain strings available in a database. Mention the command
used to fetch first 5 characters of the string?

To obtain partial characters from a string SUBSTRING function can be used. The syntax
and parameters are mentioned below.
The SQL Server SUBSTRING function syntax is as follows:
SUBSTRING (expression, position, length)
Parameters:
 expression: Input source string
 position: Is an integer value that specifies the initial position from which the characters
can be extracted from the given expression. The first position of an expression is always
starting with 1. The initial position can be a negative integer.
 length: Is a positive integer value. It specifies the ending limit and determines how many
characters are going to be extracted from the given expression.

27. Give an example for “where” clause predicates.


SQL includes a between comparison operator to simplify where clauses that specify that a value
be less than or equal to some value and greater than or equal to some other value. We can use the
between comparison to write,

Select name From


instructor
Where salary between 90000 and 100000;

Instead of: Select name


From instructor
Where salary<=100000 and salary >=90000;
Regulation: 2019 Academic Year 2022-2023

29. Write a SQL query to fetch employee names having salary greater than or equal to
5000 and less than or equal 10000.
User will use BETWEEN in the 'where' clause to return the empId of the employees with salary
satifying the required criteria and then use it as subquery to find the fullName of the employee
form EmployeeDetails table.
SELECT FullName
FROM EmployeeDetails
WHERE EmpId IN
(SELECT EmpId FROM EmpolyeeSalary
WHERE Salary BETWEEN 5000 AND
10000);

31. Examine the structure of the EMPLOYEES table. You issue the following command:
INSERT INTO EMPLOYEES (employee_id , first_name , job_id) VALUES (5100,
'BRUCE', 'CLERK');Assuming that there is a duplicate value check constraint on the
EMPLOYEE_ID column, what will be the outcome of the above statement?
The ORA error message is triggered when a unique constraint has been violated.
Essentially the user causes the error when trying to execute an INSERT or UPDATE statement
that has generated a duplicate value in a restricted field. The error can commonly be found when
a program attempts to insert a duplicate row in a table.
This statement will throw an error namely a 'Constraint violated' ORA error , since the
row with values "5100, BRUCE, CLERK" already exists in the table, the insert statement with
same data set is not possible.
33. Write an SQL query to Select all employees from department numbers 7369, 7499
and Display all the details of the records whose employee name starts with „S‟
Select * from emp where deptno in(7369,7499);
 Use SELECT FROM WHERE syntax.
 Select should include all in the given format.
 From should include employee

where empname like ‗s%
„; Table:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
Query:
SELECT DNAME FROM DEPT WHERE DEPTNO IN ( SELECT DEPTNO FROM
EMP WHERE ENAME LIKE 'S%'
Answer: 7369 SMITH
34. Write an SQL query to determine the max and min salary and rename the column
as max_salary and min_salary.
Steps:
1. Use the MIN & MAX aggregate function in select clause for finding the maximum and
minimum salary from the database.
2. Rename the column as min_sal & max_sal.
Ans: select min(sal) ―min_salary, max(sal) ―max_salary from emp;
Regulation: 2019 Academic Year 2022-2023

35. Write an SQL query to list out the employee names who will celebrate their birthdays
during current month and to display the names and dob of all employees who were born
in February.
Steps to obtain the name of employees who are born in february
 Use “select” from clause.
 Use to_char functions on name in select clause to obtain the result.
Ans: select empname from emp where to_char (dob,„MON„) like to_char (sysdate,
‗MON„); Ans: select empname , dob from emp where to_char (dob,„MON„)=„FEB„;

36. Write a query using having clause for Listing the number of customers in
each country. Only include countries with more than 10 customers.
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
HAVING COUNT(Id) > 10
54. Why SELECT * is not preferred in embedded SQL programs?
SELECT* is not used in embedded SQL due to following reasons:
 If the table structure is changed (a field is added ), the program will have to be
modified.
 Program might retrieve the columns which it might not use, leading on I/O overhead.
 The chance of an index only scan is lost.

37. Consider the following query and represent in relational expression.


Select count(*), home-planet from Jedi, Inhabitants where specie = 'wookies' and
planet = home-planet and side = 'light' group by home-planet
Relational Algebra:

Logical Query plan is :

38. Write the SQL query to Display total salary spent for employees and Display total
salary spent for each job category.
The usage of SQL GROUP BY clause is, to divide the rows in a table into smaller
groups. The GROUP BY clause is used with the SQL SELECT statement.The grouping can
happen after retrieves the rows from a table.When some rows are retrieved from a grouped result
Regulation: 2019 Academic Year 2022-2023

against some condition, that is possible with HAVING clause.

The query for obtaining total salary spent for employees , GROUP BY clause is used with the
SELECT statement to make a group of rows based on the values of a specific column or
expression. The SQL AGGREGATE function can be used to get summary information for every
group and these are applied to an individual group.

 Select sum (sal) from employees;


 Select job, sum (sal) from employees group by job;

40. You need to find the salaries for all the employees who have a higher salary than the
Vice President of a company 'ABC'. What is the query used to obtain the result?
(Consider the table structure as given)
SQL> DESC employees
Name Null? Type
EMPLOYEE_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)
The Query below obtains the inner sub-query gives the VP's salary as a result to the outer query.

SELECT first_name, last_name, salary


FROM employees
Regulation: 2019 Academic Year 2022-2023

WHERE salary > (SELECT salary


FROM employees
WHERE job_id = 'VICE-PRESIDENT');

Part-B

5. Let relations r1(A,B,C) and r2(C,D,E) have the following properties: r1 has 20,000
tuples, r2 has 45,000 tuples, 25 tuples of r1 fit on one block and 30 tuples of r2 fit on one
block Estimate the number of block transfers and seeks required, using each of the
following join strategies for r1∞r2:
i. Nested loop join
ii. Block nested loop join
iii. Merge join
iv. Hash join
Solutions:
r1 needs 800 blocks, and r2 needs 1500 blocks. Let us assume M pages of memory. If
M > 800, the join can easily be done in 1500 + 800 disk accesses, using even plain nested-

i. Nested-loop join: Using r1 as the outer relation we need 20000 ∗ 1500 + 800 = 30, 000,
loop join. So we consider only the case where M ≤ 800 pages.

800 disk accesses, if r2 is the outer relation we need 45000 ∗ 800 + 1500 = 36, 001, 500
disk accesses.
ii. Block nested-loop join: A block-nested loop (BNL) is an algorithm used to join two
relations in a relational database. This algorithm is a variation on the simple nested loop
join used to join two relations and (the "outer" and "inner" join operands, respectively).
Block nested loop join requires no indices and can be used with any kind of join

Solution: If r1 is the outer relation, we need ⌈ 800 M−1 ⌉ ∗ 1500 + 800 disk accesses, if r2 is
condition.

the outer relation we need ⌈ 1500 M−1 ⌉ ∗ 800 + 1500 disk accesses.
iii. Merge-join: The Merge Join operator is one of four operators that join data from two
input streams into a single combined output stream. However, it requires all input data to
be sorted by the join columns. Often this means that a Merge Join can‟t be used without
adding extra Sort operators. The Merge Join operator supports all ten logical join
operations: inner join; left, right, and full outer join; left and right semi and anti semi join;
as well as concatenation and union. The algorithm requires at least one equality-based
join predicate.
Solution: Assuming thatr1 and r2 are not initially sorted on the join key, the total sorting cost
inclusive of the output is Bs = 1500(2⌈logM−1(1500/M)⌉+2) + 800(2⌈logM−1(800/M)⌉ + 2)
disk accesses. Assuming all tuples with the same value for the join attributes fit in memory, the
total cost is Bs + 1500 + 800 disk accesses.
iv. Hash-join: The Hash Join algorithm is a good choice, if the tables are large and there is
no usable index. Like the Sort Merge Join algorithm, it is a two-step process. The first
step is to create an in-memory hash index on the left side input. This step is called the
build phase. The second step is to go through the right side input one row at a time and
find the matches using the index created in step one. This step is called the probe phase.
Solution: We assume no overflow occurs. Since r1 is smaller, we use it as the build relation and
r2 as the probe relation. If M > 800/M, i.e. no need for recursive partitioning, then the cost is
Regulation: 2019 Academic Year 2022-2023

3(1500+800) = 6900 disk accesses, else the cost is 2(1500 + 800)⌈logM−1(800) − 1⌉ + 1500
+ 800 disk accesses.

7. Create the following tables with the mapping given below.


a. stu_details (reg_no, stu_name, DOB, address, city)
b. mark_details (reg_no, mark1, mark2, mark3, total)
i. Alter the table mark_details to add a column average with data type as long.
ii. Display the months between the DOB and till date.
iii. Using alter command drop the column address from the table
stu_details. SQL SELECT Statement
The most commonly used SQL command is SELECT statement. SQL SELECT statement
is used to query or retrieve data from a table in the database. A query may retrieve information
from specified columns or from all of the columns in the table. To create a simple SQL SELECT
Statement, you must specify the column(s) name and the table name. The whole query is called
SQL SELECT Statement.

Syntax of SQL SELECT Statement:


SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];

table-name is the name of the table from which the information is retrieved.
column_list includes one or more columns from which data is retrieved.
The code within the brackets is optional.
SQL Alter DataBase
The ALTER DATABASE Statement is used to change characteristics of a
database.After creating a database, we can change its properties by executing ALTER
DATABASE statement. The user should have admin privileges for modifying a database.
SQL ALTER DATABASE Statement:
The Syntax for the ALTER DATABASE Statement is:
ALTER DATABASE database_name
[COLLATE collation_name ]
In the above query,
database_name - is the name of the database to be created
- collation_name - - is the default collation for the database
collation_name - This is an optional field and if not provided thanDefault Collation is
assigned to database.
Solutions:
a. CREATE TABLE
stu_details(
reg_no int, stu_name varchar(25),
DOB date,
address nvarchar(50),
city varchar(35));
Regulation: 2019 Academic Year 2022-2023

b. CREATE
TABLEMark
_details( reg_n
o int, mark1
int, mark2 int,
mark3 int, total
int));
i. ALTER TABLE mark_details ADD (average long);
ii. SELECT DATEDIFF(MM,DOB,GetDate()) as Months FROM stu_details
iii. ALTER TABLE stu_details DROP(address);

8. Consider the following schema and write the following SQL


queries Suppliers(sid:integer, sname:string, address:string)
Parts(pid:integer, pname:string, color:string)
Catalog(sid:integer, pid:integer, cost:real)
i. Find the sids of suppliers who supply some red and some green parts.
ii. Find the paris of sids such that the supplier with first sid charges more for
some part than the supplier with second sid.
Find the pids of parts supplied by at least two different suppliers
The SQL SELECT statement is used to fetch the data from a database table which returns
this data in the form of a result table. These result tables are called result-sets. Select is the most
commonly used statement in SQL. The SELECT Statement in SQL is used to retrieve or fetch
data from a database. We can fetch either the entire table or according to some specified rules.
The data returned is stored in a result table. This result table is also called result-set.
With the SELECT clause of a SELECT command statement, we specify the columns that
we want to be displayed in the query result and, optionally, which column headings we prefer to
see above the result table.
SQL WHERE Clause
WHERE keyword is used for fetching filtered data in a result set.It is used to fetch data
according to a particular criteria.WHERE keyword can also be used to filter data by matching
patterns.
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name operator
value; column1 , column2: fields int the table
table_name: name of table
column_name: name of field used for filtering the
data operator: operation to be considered for filtering
value: exact value or pattern to get related data in
result Operators used by WHERE clause are:
Operator Description
> Greater Than
>= Greater than or Equal to
< Less Than
<= Less than or Equal to
= Equal to
<> Not Equal to
BETWEEN In an inclusive Range
LIKE Search for a pattern
Regulation: 2019 Academic Year 2022-2023

IN To specify multiple possible values for a column


The select clause is the first clause and is one of the last clauses of the select statement that the
database server evaluates.The basic syntax of the SELECT statement is as follows −
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax.
SELECT * FROM
table_name; Solutions:
i. SELECT S.sid FROM Suppliers S, Parts P, Catalog C WHERE C.sid=S.sid
and C.pid=P.pid and p.pname=„red„ OR ‗green„;
ii. SELECT P.pid FROM Suppliers S, Parts P, Catalog C WHERE C.sid=S.sid
and C.pid=P.pid
and SELECT sid as S_ID FROM Suppliers and C.sid= S_ID and C.cost>(SELECT
C.cost FROM Catalog C and sid=S_ID);
iii. SELECT P.pid FROM Suppliers S, Parts P, Catalog C WHERE C.sid=S.sid
and C.pid=P.pid and S.sname=like(%);

You might also like