topic 3 msbte questions and answers … table creation the foreign key is added as:alter table...
TRANSCRIPT
TOPIC 3 MSBTE QUESTIONS AND ANSWERS
SUMMER – 2017
Q. Define super key. 2 Marks
Definition: Super key of an entity set is a set of one or more attributes whose values uniquely
determine each entity.
Q. Define Group by clause. 2 Marks
The SQL GROUP BYclause is used along with the SQL aggregate functions and specifies the
groups where selected rows are placed.
When one or more aggregate functions are presented in the SQL SELECT column list, the SQL
GROUP BY clause calculates a summary value for each group.
Q. What is SQL? State its features. 2 Marks
SQL is an acronym for Structured Query Language an is a standard relational query language
used for creating and manipulating databases.
Features of SQL are:
SQL allows the user to create,update, delete, and retrieve data from a database.
SQL is very simple and easy to learn.
SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.
Q. What is OUTER JOIN? Explain in detail. 4 Marks
The SQL OUTER JOIN returns all rows from both the participating tables which satisfy the join
condition along with rows which do not satisfy the join condition.
The SQL OUTER JOIN operator (+) is used only on one side of the join condition only.
Outer join are of three types:
1.Left outer join (also known as left join): this join returns all the rows from left table combine
with the matching rows of the right table. If we get no matching in the right table it returns
NULL values.
Left Outer Join syntax :
SELECT column-name-list from table-name LEFT OUTER JOIN table-name2 on table-
name1.column-name = table-name2.column-name;
2.Right outer join(also known as right join): this join returns all the rows from right table are
combined with the matching rows of left table .If we get no columnmatching in the left table, it
returns null value.
Right Outer Join Syntax:
SELECT column-name-list from table-name1 RIGHT OUTER JOIN table-name2 on table-
name1.column-name = table-name2.column-name;
3.The full outer join keyword returns all records when there is a match in either left (table1) or
right (table2) table records.
FULL OUTER JOIN Syntax:
SELECT column_name(s)from table1full outer join table2 on table1.column_name
=table2.column_name;
Q. Explain referential integrity constraints with example. 4 Marks
(Note: Any other example can be considered)
Referential integrity constraint:
It is used to established a parent child relationship between two tables.
A value of foreign key is derived from the primary key.
Primary key is defined in a parent table and foreign key is defined in child table. The child table
contains the values for foreign key column which are present in parent tables primary key
column but not other than that.
Syntax:
Create table tablename (column datatype size references parenttablename (primary key
attribute)....)
Example:
Create table product (EmpId number (4) references Emp (EmpId), PName varchar2(10));
After table creation the foreign key is added as:Alter table product add constraint fk_prod foreign
key (EmpId) references Emp (EmpId);
Q. Explain string, data and time functions of SQL.
SQL string functions are used primarily for string manipulation.
Following are the string functions used in SQL.
Q. Explain having clause with example. 4 marks
(Note: Any other example considered)
Having clause is used to filter data based on the group functions. This is similar to WHERE
condition but is used with group functions.
Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
Syntax
SELECT column1, aggregate_function(column2)
FROM table1, table2
WHERE [ conditions ]
GROUP BY group_expression
HAVING [ conditions ]
ORDER BY column1, column2
Example:
SQL > SELECT ID, NAME, AGE, ADDRESS, MIN(SALARY) FROM CUSTOMERS
GROUP BY ID HAVING MIN(SALARY)>=2000;
Q. Describe commit and rollback with proper syntax. 4 Marks
Commit:
The COMMIT command is used to save changes invoked by a transaction to the database.
The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
The syntax:
SQL> COMMIT;
Or
COMMIT WORK;
Rollback:
The ROLLBACK command is used to undo transactions that have not already been saved to the
database.
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
We can either rollback the entire transaction or till a particular save point transaction can be
rolled back.
The syntax for ROLLBACK is:
ROLLBACK TO SAVEPOINT_NAME;
OR
ROLLBACK;
OR
ROLLBACK WORK;
Q. Consider the structure for book table as
Book-master = {bookid, bookname, subcode-author, no_of copies, price} Write SQL
queries for following:
(i) Display total no. of books for subject „DBM‟
(ii) Get authorwise list of all books.
(iii) Display all books whose prices are between Rs.200 and Rs.500
(iv) Display all books with details whose name start with „S‟ 4 Marks
(Note: Queries with any other correct logic shall be considered)
(i)select sum(no_of Copies) from Book_master where subcode=‗ DBM‘;
(ii) Select SUM(no_of Copies),author from Book_master group by (author);
(iii) Select bookname from book_master where price>=200 and price <=500;
(iv) select * from book_master where bookname like ‗S%‘;
Q. List out query processing components and state their function.
Components of query processing:
1)DDL interpreter
2) DML compiler
3) Embedded DML PreCompiler
4) Query Evaluation Engine 4 Marks
The query processor components include:
1. DDL Interpreter: It interprets DDL statements and records them in a set of tables containing
metadata or data dictionary.
2. DML Compiler: It translates DML statements of high level query language into low level
instructions that query evaluation engine understands.
3. Embedded DML PreCompiler: It converts DML statements embedded in application
program to normal procedural calls in host language. The precompiler must interact with the
DML compiler to generate the appropriate code.
4. Query Evaluation Engine: It executes low level instructions generated by DML compiler and
DDL
Q. Explain candidate key and primary key. 4 Marks
Candidate key:
In a relation, there may be a primary key or may not, but there may be a key or combination of
keys which uniquely identify the record. Such a key is called as Candidate key.
Primary key:
A key which is selected by the designer to uniquely identify the entity is called as Primary key.
A primary key cannot contain duplicate values and it can never contain null values inside it.
SUMMER 2016
Q. Define attribute and entity. 2 Marks
Entity: An entity is a thing or object in the real world with an independent existence. An entity
may be an object with a physical existence.
Attribute: Describing properties of an entity is called attributes. For example, a student entity
may have name, class, and age as attributes.
Q. Explain the steps used in query processing with suitable diagram. (Diagram - 2 marks;
Explanation - 2 marks) 4 Marks
Query processing: It is a three step process that transforms a high-level query (of relational
calculus/SQL) into an equivalent and more efficient lower-level query (of relational algebra).
1. Parsing and translation – Check syntax and verify relations. It translates the query into an
equivalent relational algebra expression.
2. Optimization – Generate an optimal evaluation plan (with lowest cost) for the query plan.
3. Evaluation – The query-execution engine takes an (optimal) evaluation plan, executes that
plan, and returns the answers to the query.
Q. List and explain the types of integrity constraints in detail. 4 Marks
(Listing - 1 mark; Any Two Constraints explanation - 1 ½ marks each) [** Note: Either syntax
or example can be considered**]
Integrity constraints: Not Null constraint, CHECK constraint, Primary Key constraint, Unique
Constraint, Referential Integrity Constraint
1. Not Null: By default all columns in tables allows null values. When a NOT NULL constraint
is enforced on column or set of columns it will not allow null values.
Syntax for NOT NULL CREATE TABLE TABLE_NAME (COLUMN_NAME
DATA_TYPE, COLUMN_NAME DATA_TYPE NOT NULL); Example: SQL>CREATE
TABLE STUDENT (ROLL_NO NUMBER(5), NAME VARCHAR2(20) NOT NULL);
2. CHECK: The constraint defines a condition that each row must satisfy. A single column can
have multiple check condition.
Syntax:- CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE,
COLUMN_NAME DATA_TYPE CONSTRAINT CONSTRAINT_NAME CHECK
<CONDITION>); Example: SQL> CREATE TABLE EMP (ID NUMBER(5), NAME
VARCHAR2(10), SAL NUMBER(10) CONSTRINT CHK_SAL CHECK (SAL>15000));
3. Primary Key constraint: It is use to avoid redundant/duplicate value entry within the row of
specified column in table. It restricts null values too.
Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE,
COLUMN_NAME DATA_TYPE CONSTRAINT CONSTRAINT_NAME PRIMARY KEY);
Example: SQL> CREATE TABLE EMP (ID NUMBER (5) CONSTRAINT ID_PK PRIMARY
KEY, NAME VARCHAR2 (10), SAL NUMBER (10));
4. Unique Constraint: The UNIQUE constraint uniquely identifies each record in a database
table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
for a column or set of columns. It allows null value.
Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE,
COLUMN_NAME DATA_TYPE CONSTRAINT CONSTRAINT_NAME UNIQUE);
Example: CREATE TABLE PERSONS (P_ID NUMBER CONSTRAINT P_UK UNIQUE,
FIRSTNAME VARCHAR (20), CITY VARCHAR (20));
5. Referential Integrity Constraint: It is a relational database concept in which multiple tables
share a relationship based on the data stored in the tables, and that relationship must remain
consistent. A value of foreign key is derived from primary key which is defined in parent table.
Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE,
COLUMN_NAME DATA_TYPE CONSTRAINT CONSTRAINT_NAME REFERENCES
PARENT_TABLE_NAME (PARENT_TABLE_COL_NAME ON DELETE CASCADE,
COLUMN_NAME DATA_TYPE);
Example: CREATE TABLE DEPARTMENT (EMP_ID NUMBER(5) REFERENCES
EMP(EMP_ID), DNO NUMBER(3));
Q. Explain ACID properties of transaction. 4 Marks
(Four ACID properties - 1 mark each)
ACID Properties:
1. Atomicity: When one transaction takes place, many operations occur under one transaction.
Atomicity means either all operations will take place property and reflect in the database or none
of them will be reflected.
2. Consistency: Consistency keeps the database consistent. Execution of a transaction needs to
take place in isolation. It helps in reducing complications of executing multiple transactions at a
time and preserves the consistency of the database.
3. Isolation: It is necessary to maintain isolation for the transactions. This means one transaction
should not be aware of another transaction getting executed. Also their intermediate result should
be kept hidden.
4. Durability: When a transaction gets completed successfully, it is important that the changes
made by the transaction should be preserved in database in spite of system failures.
Q. Describe Commit and Rollback with syntax. 4 Marks
(For each command explanation - 1 mark; syntax - 1 mark)
Ans:
Commit
The COMMIT command is used to save changes invoked by a transaction to the database.
The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
The syntax for COMMIT command is as follows:
SQL> COMMIT;
Rollback:
The ROLLBACK command is used to undo transactions that have not already been saved to the
database.
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
We can either rollback the entire transaction or till a particular save point transaction can be
rolled back.
The syntax for ROLLBACK is:
ROLLBACK TO SAVEPOINT_NAME; OR
ROLLBACK;
e.g. ROLLBACK TO sv1;
OR ROLLBACK
Q. Consider the following database: 4 Marks
Employee(emp_id, emp_name, emp_city, emp_addr, emp_dept, join_date) Solve the
following query:
i) Display the names of employees in capital letters.
ii) Display the emp_id of employee who live in city Pune and Mumbai.
iii) Display the details of employees whose joining date is after „01-Apr.-1997‟.
iv) Display the total number of employees whose dept.no.is „10‟.
(Each correct query - 1 mark)
Ans:
i) select upper(emp_name) from Employee;
ii) select emp_id from Employee where emp_city = ‗Pune‗ or emp_city = ‗Mumbai‗;
OR Select emp_id from Employee where emp_city in(‗Mumbai‗, ‗Pune‗);
iii) select * from Employee where join_date>‗01-Apr-1997‗;
iv) select count(emp_id) from Employee where emp_dept = 10;
Q. Describe Grant and Revoke commands. 4 Marks
(Description of Grant - 2 marks; Revoke - 2 marks)
Ans:
Grant: This command is used to give permission to user to do operations on the other user‗s
object.
Syntax: Grant<object privileges>on<object name>to<username>[with grant option] ;
Example: Grant select, update on emp to user1;
Revoke: This command is used to withdraw the privileges that has been granted to a user.
Syntax: Revoke <object privileges>on<object name>from <username> ;
Example: Revoke select, update on emp from user1;
Q. Describe string function, date and time function. (Any two String Function - 2 marks;
any two Date and Time Function - 2 marks) 4 marks
Sr.
No
Function Description
1.
Initcap(str) Converts first letter of string to capital letter. Example: Select
initcap(‗rdbms‗) from dual;
2.
Lower(char) Converts a string to all lowercase characters. Example: Select
lower(‗RDBMS‗) from dual;
3.
Upper(char) Converts a string to all uppercase characters. Example: Select upper(‗rdbms‗)
from dual;
4.
Length(char) Find outs the length of given string. Example: Select length(‗RDBMS‗) from
dual;
5. Ltrim(char,set) It trim from the left of character string. Example: Select Ltrim(‗manas khan‗,
‗manas‗) from dual;
6. Rtrim(char,set) It trim from the Right of character string. Example: Select Rtrim(‗manas
khan‗, ‗khan‗) from dual;
7. Lpad(char1,len
gth, char2)
It returns char1, left-padded to given length with the sequence of characters in
char2. Example: Select Lpad(‗SKY‗, 8, ‗*‗) from dual;
8. Rpad(char1,len
gth ,char2)
It returns char1, right-padded to given length with the sequence of characters
in char2. Example: Select Lpad(‗SKY‗, 8, ‗*‗) from dual;
9 Translate(char,
fromstring,to
string)
It returns expr with all occurrences of each character in from string replaced
by its corresponding character in to_string. Example: Select
translate(Hickory,‗H‗,‗D‗) from dual
10 Replace(char,s
earchstring,[re
pstring])
It returns character string with each occurrences of search string replaced with
[repstring] Example: Select replace(‗Tick and Tock‗,‗T‗,‗Cl‗) from dual;
11 Substr(char,m,
n)
It returns substring of character string that stack at m character and is of length
n Example: Select substr(Triangle‗4,5) from dual;
12 Concatenation(
)
It merges two or more strings or a string and a data value together Example:
Select (‗Branch is‗|| branch_name) from table_name;
Sr. No Function Description
1 months_between(d1,
d2) Where, d1 and d2
are dates
Used to find number of months between d1 and d2. If d1 later
date then d2 ans is positive If d1 earlier than d2 answer is
negative Example: Select months_between(‗05-MAY-
1996‗,‗05-JAN-1996‗) from dual;
2 add_months(d,n)
Where,d is date, n no
of months to be
added
Returns date after adding the number of months specified with
the function. Example: Select add_months(sysdate,2) from
dual;
3 Next_day(d,char)
Where d is date, char-
day of week
Returns the date of the first weekday named ‗char‗ that is after
the date named by date. Example: Select next_day(‗01-FEB-
2006‗,‗Wednesday‗) from dual;
4 Last_day(d) Where, d
is date
Returns the last day of the month that contains date ‗d‗.
Example: Select last_day(sysdate) from dual
5 Round(date,[fmt])
Where, fmt format
model Month Day
Year
Returns date rounded to the unit specified by the format model
‗fmt‗. Example: Select round(sysdate,‗day‗) from dual;
6 Trunc(date([fmt])
Where, fmt format
model Month Day
Year
Returns date with the time portion of the day truncated to the
unit specified by the format model fmt. Example: Select
trunc(sysdate,‗day‗) from dual;
Q. Explain with example group by and having clause. 4 Marks
(For each clause - Explanation - 1 mark, syntax/example - 1 mark) Ans: Group by clause
1. The group by clause can be used in a select statement to collect data across multiple records
and group by one or more columns.
2. The group by field contains the repetitive records or values like department number in
employee.
3. The syntax is:
Select col1,col2,….,coln aggregate_function (expression) From table_name Where predicates
Group by column_name;
4. Example: Display average salary of each department
Select avg(sal) from emp group by deptno; Having clause
1. This like a where clause, except that it involves a summary value, rather than a column value.
2. A where clause specifies the rows in the table to be included in the summation.
3. The having clause operates after the summation has been done.
4. Having clause is used in combination with the group by clause.
5. It can be used in a select statement to filter the records that a group by returns.
6. The syntax is :
Select col1,col2,….,col n aggregate_function (expression) From table_name Where predicates
Group by column_name; Having condition 1,condition2;
7. Example: Display the department number whose total salary is greater than 15000.
Select deptno, sum(sal) from emp group by deptno having sum(sal)>15000;
Q. List and explain any 4 arithmetic operators in SQL with example. 4 Marks
(For each - 1 mark) Ans: Arithmetic operators are used to perform mathematical functions in
SQL—the same as in most other languages. There are four conventional operators for
mathematical functions:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
Addition
Addition is performed through the use of the
plus (+) symbol. Example
Meaning
SELECT SALARY + BONUS FROM
EMPLOYEE_PAY_TBL;
The SALARY column is added with the
BONUS column for a total for each row of
data
Subtraction
Subtraction is performed using the minus (-)
symbol. Example
Meaning
SELECT SALARY - BONUS FROM
EMPLOYEE_PAY_TBL;
The BONUS column is subtracted from the
SALARY column for the difference
Multiplication
Multiplication is performed by using the
asterisk (*) symbol. Example
Meaning
SELECT SALARY * 10 FROM
EMPLOYEE_PAY_TBL;
The SALARY column is multiplied by 10
Division
Division is performed through the use of
the ―/‖ symbol. Example
Meaning
SELECT SALARY / 10 FROM
EMPLOYEE_PAY_TBL;
The SALARY column is divided by 10
Q. Consider the structure for book table as Book_master {book_id, book_name, subcode,
author, no_of_copies, price}.
Write SQL queries for the following:
i) Display total no. of book for subject „DBM‟.
ii) Get authorwise list of all books.
iii) Display all books whose prices are between Rs. 200 and Rs.500 4 Marks
Ans:
i. Select sum(no_of_copies) from Book_master where subcode=‗DBM‗; (1 mark)
OR Select sum(no_of_copies) from Book_master where book_name=‗DBM‗;
ii. Select author, book_name From Book_master Order by author;
OR (1 mark) Select author, sum(no_of_copies) from Book_master group by author;
iii. Select book_id From Book_master Where price between 200 and 500; (2 marks)
OR Select book_id From Book_master Where price >= 200 and price <= 500;
WINTER 2016
Q. List four DDL commands. 2 Marks
DDL commands:
1. Create 2. Alter 3. Rename 4. Drop 5. Truncate
Q. List DCL commands any four. 2 Marks
DCL commands:
1. Grant 2. Revoke 3. Commit 4. Rollback 5. Savepoint
Q. Explain DELETE and DROP Command with syntax and example 4 Marks
DELETE Command: The SQL DELETE Query is used to delete the existing records
from a table. You can use WHERE clause with DELETE query to delete selected rows,
otherwise all the records would be deleted.
Syntax:
DELETE FROM table_name WHERE [condition];
Example:
1) To Delete record from customer table with Name as JACK
DELETE FROM CUSTOMER WHERE NAME = 'JACK';
DROP Command: The SQL DROP Command is use to delete all records and schema of
the table.
Syntax:
DROP Table <table name>;
Example:
Drop table emp;
Q. Consider the following database Employee (emp-id, emp-name, emp-city, empaddr,
emp-dept, join-date)
i) Display the emp-id of employee who live in city Pune or Nagpur.
ii) Display the details of employee whose joining date is after 02-July-2007.
iii) Change employee name „Ajit‟ toAarav‟.
iv) Display the total number of employees whose dept is „50‟. 4 Marks
i) Select emp-id from Employee where emp-city=‘Pune‘ or emp-city=‘Nagpur‘;
OR
i) Select emp-id from Employee where emp-city IN(‗Pune‘,‘Nagpur‘);
ii) Select * from Employee where join-date>‘02-Jul-2007‘;
iii) Update Employee set emp-name=‘Aarav‘ where emp-name=‘Ajit‘;
iv) Select count(emp-dept) from Employee where emp-dept=50;
OR
iv) Select count(*) from Employee group by emp-dept having emp-dept=50;
Q. Explain entity integrity constraints with syntax and example. 4 Marks
There are two Entity constraints: 1. Primary Key constraint
2. Unique Constraint
1. Primary Key constraint: It is use to avoid redundant/duplicate value entry within the
row of specified column in table. It restricts null values too.
Syntax:
CREATE TABLE TABLE_NAME
(COLUMN_NAME DATA_TYPE,
COLUMN_NAME DATA_TYPE CONSTRAINT CONSTRAINT_NAME PRIMARY
KEY);
Example:
SQL> CREATE TABLE EMP
(ID NUMBER (5)CONSTRAINT ID_PK PRIMARY KEY,
NAME VARCHAR2 (10),
SAL NUMBER (10));
Unique Constraint: The UNIQUE constraint uniquely identifies each record in a
database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee
for uniqueness for a column or set of columns.
Syntax:
CREATE TABLE TABLE_NAME
(COLUMN_NAME DATA_TYPE,
COLUMN_NAME DATA_TYPE CONSTRAINT CONSTRAINT_NAME UNIQUE);
Example:
CREATE TABLE PERSONS
(P_ID NUM CONSTRAINT P_UK UNIQUE ,
FIRSTNAME VARCHAR(20),
CITY VARCHAR(20) );
Q. Give the syntax and example of CREATE and RENAME Commands. 4 Marks
The Syntax for the CREATE TABLE command is:
CREATE TABLE <table_name>
(<column_name1>< datatype>(size),
<column_name2>< datatype> (size),
<column_nameN>< datatype> (size));
For Example: To create the employee table, the statement would be like,
CREATE TABLE employee
(emp_id number(5),
name char(20),
deptno number(2),
dob date,
salary number(10,2),
address varcharchar2(30) );
The Syntax for the RENAME TABLE command is:
RENAME <old_table_name> To < new_table_name>;
For Example: To change the name of the table employee to my_employee, the query
would be like,
RENAME employee TO my_employee;
Q. Explain ALTER command with any two options. 4 Marks
The SQL ALTER TABLE command is used to modify the definition (structure) of a
table by modifying the definition of its columns
It can be used for
1. To add any new column to a table
2. To change data type or size of already existing data column of a table.
3. To delete a column from a table
4. To add / drop constrains from column of a table.
The three options with ALTER command are:
1. Add column:-We can add any number of columns in a table using ALTER table
command with add clause. Added column becomes last column by default.
Syntax to add a column:-
ALTER TABLE <table_name>
ADD (<column_name1>< datatype>(size),
..<column_nameN>< datatype>(size) );
2. Drop Column: - We can delete the existing column with help of drop clause in the
ALTER table command. We can drop one column at a time. After dropping any
column from the table, there must be at least one column left in the table.
Syntax to drop a column:-
ALTER TABLE <table_name >
DROP column <column_name>;
3. Modify column:-We can change the data type and/or size of a column in a table by
using modify clause in ALTER table. The size of the column can be increased or
decreased if the column contains only null values or if the table has no rows.
Syntax to modify a column
ALTER TABLE <table_name >
MODIFY( <column_name1>< datatype>(size),
<column_name2>< datatype>(size),
..
<column_name N>< datatype>(size)) ;
Q. Describe ACID properties of transaction. 4 Marks
ACID Properties:
1. Atomicity: When one transaction takes place, many operations occur under one
transaction. Atomicity means either all operations will take place property and
reflect in the database or none of them will be reflected.
2. Consistency: Consistency keeps the database consistent. Execution of a transaction
needs to take place in isolation. It helps in reducing complications of executing
multiple transactions at a time and preserves the consistency of the database.
3. Isolation: It is necessary to maintain isolation for the transactions. This means one
transaction should not be aware of another transaction getting executed. Also their
intermediate result should be kept hidden.
4. Durability: When a transaction gets completed successfully, it is important that the
changes made by the transaction should be preserved in database in spite of system
failures.
Q. Explain any four string functions with example. 4 Marks
Q. Consider the following database schema:
Emp(Empno,Ename,job,mgr,joindate,salary,comm.,deptno).
Write the SQL queries for the following:
i) Write a query to find list of employees whose salary is not less 5000.
ii) Write a query to find list of employees whose job title is either “Manager” or
“Analyst”.
iii) Change the location of deptno 40 to Pune from Chandrapur.
iv) Display the Ename and salary of employees who earn more than Rs. 50,000
and are in deptno 10 or 30. 4 Marks
Ans
i) select * from Emp where salary >= 5000;
ii) select * from Emp where job=‘Manager‘ or job=‘Analyst‘;
OR
ii) select * from Emp where job in(‘Manager‘ , ‘Analyst‘);
iii) update Emp set location=‘Pune‘ where deptno=40; {consider location
attribute in Emp table}
iv) select Ename,Salary from Emp where salary >50000 and(deptno = 10 or
deptno=30);
Q. Explain Domain integrity constraint with syntax and example. 4 Marks
1. Not Null constraint: This constraint ensures all rows in the table contain a definite
value for the column which is specified as not null. Which means a null value is not
allowed.
syntax: create table <table name>( Column_name Datatype (Size) [CONSTRAINT
constraint name] NOT NULL );
Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee
( id number(5),
name char(20) CONSTRAINT nm_nn NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
OR
For Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee
( id number(5),
name char(20) NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
1) Check constraint: it defines a condition that each row must satisfy. A single
column can have multiple check constraints that reference the column in its
definition.
Syntax at table creation:
Create table <table_name>
(column_name1 datatype(size) constraint <constraint_name> check <condition or
logical expression>,
---
column_name n datatype(size)
);
Example:
create table emp( empno number(5), ename varchar2(25), salary number(7,2)
constraint emp_sal_ck check(salary > 5000), job varchar2(15) );
After table creation
Syntax:
Alter table <table_name> add constraint<constraint_name> check <condition>;
Example:
alter table emp add constraint emp_deptno_ck check(deptno>5);
Q. Give the use of grant and revoke command with syntax and example.
1. GRANT command is used to provide access or privileges on the database objects to
the users.
The Syntax for the GRANT command is:
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
The Example for the GRANT command is:
GRANT insert,update
ON emp
TO staff ;
2. REVOKE command removes user access rights or privileges to the database objects.
The Syntax for the REVOKE command is:
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name};
The Example for the REVOKE command is:
REVOKE insert,update
ON emp
FROM staff ;
Q. Explain Inner join and Outer join with example. 4 Marks
(Any one outer join should be considered)
INNER Join: This is a simple JOIN in which the result is based on matched data as per
the condition specified in the query.
Inner Join Syntax :
SELECT column_name_list
from table_name1
INNER JOIN
table_name2
on table_name1.column_name = table_name2.column_name;
Inner Join Example :
SELECT * from emp inner join dept on emp.id = dept.id;
Outer Join is based on both matched and unmatched data. Outer Joins subdivide
further into,
• Left Outer Join
• Right Outer Join
• Full Outer Join
Left Outer Join
The left outer join returns a result table with the matched data of two tables then
remaining rows of the left table and null for the right table's column.
Left Outer Join syntax :
SELECT column-name-list from table-name LEFT OUTER JOIN table-name2
on table-name1.column-name = table-name2.column-name;
Left Outer Join Example:
SELECT * FROM emp LEFT OUTER JOIN dept ON (emp.id=dept.id);
Right Outer Join
The right outer join returns a result table with the matched data of two tables then
remaining rows of the right table and null for the left table's columns.
Right Outer Join Syntax:
select column-name-list from table-name1 RIGHT OUTER JOIN table-name2
on table-name1.column-name = table-name2.column-name;
Right Outer Join Example:
SELECT * FROM emp RIGHT OUTER JOIN dept on (emp.id=dept.id)
Full Outer Join
The full outer join returns a result table with the matched data of two table then
remaining rows of both left table and then the right table.
Full Outer Join Syntax :
select column-name-list from table-name1 FULL OUTER JOIN table-name2
on table-name1.column-name = table-name2.column-name;
Full Outer Join Example:
select empname,sal from emp FULL OUTER JOIN dept on emp.id = dept.id;
SUMMER 2015
Q. What is Primary Key? Give example 2 Marks
Ans:
Primary key: Within a relation there is always one attribute which has values that are
unique in a relation and thus can be used to identify tuple of that relation. Such a unique
identifier is called the primary key.
E.g. In the Student(Rollno,name,class,address) relation Rollno is the primary key.
Q. List any four DML commands. 2 Marks
(For each command – ½ Mark)
Ans: List of DML commands:
1. Select
2. Insert
3. Update
4. Delete
Q. What are the atomic values? 2 Marks
(Correct Definition-2 Marks)
Ans:
A piece of data in a database table that cannot be broken down any further called atomic
value.
OR
The value of each attribute containing only a single value from that attribute domain is
called atomic value.
Q. What is the use of GRANT and REVOKE? 4 Marks
(GRANT-2 Marks, REVOKE -2Marks)
Ans:
Grant: This command is used to give permission to user to do operations on the other
user‟s object.
Syntax: Grant<object privileges>on<object name>to<username>[with grant option] ;
Example: Grant select,update on emp to user1;
Revoke: This command is used to withdraw the privileges that has been granted to a user.
Syntax: Revoke <object privileges>on<object name>from <username> ;
Example: Revoke select, update on empfrom user1;
Q. What are the four ways to insert a record in a table? 4 Marks
(Each Syntax or example- 1 Mark)
Insert is a DML statement used to insert or add data into table.
1. Syntax1: syntax for insert command without defining attributes
Insert into <Table_name> values (value1,value2,…..);
2. Syntax2: syntax for insert command with defining attributes
Insert into <Table_name>(col1,col2,.…) values (value1,value2,…..);
3. Syntax3: To insert values for selected attributes in a table.
Insert into <Table_name>(col1,col2) values (value1,value2);
4. Syntax4: To insert more than one row.
Insert into <Table_name>values(&attribute1, „&attribute2‟,..&attributen);
Example:
Consider table ―persons‖
Example for both syntax and its output
Example1:
Insert into persons values („Bhosale‟,‟Ajit‟,‟Bapat Road‟,‟pune‟);
Example2:
Insert into persons (Last_Name, First_name, Address, City) values
(„Suryawanshi‟,‟Savita‟,‟Meera road‟,‟Raigad‟);
Example3:
Insert into persons (Last_Name, First_name) values („Suryawanshi‟,‟Savita‟);
Example4:
Insert into persons values („&Last_Name‟, „&First_name‟, „&Address‟, „&City‟)
Output:
Q. Given-
Employee (EMP_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE,
DEPARTMENT) 4 Marks
Write SQL queries fori)
Get FIRST_NAME, LAST_NAME from employee table.
ii) Get unique DEPARTMENT from employee table.
iii) Get FIRST_NAME form employee table using alias name “Employee Name”
iv) Get FIRST_NAME from employee table after removing white spaces from left
side.
( Each query – 1 Mark)
Ans :
i) select FIRST_NAME,LAST,NAME from employee;
ii) select distinct DEPARTMENT from employee;
iii) select FIRST_NAME ―Employee Name‖ from employee;
iv) select ltrim(FIRST_NAME) from employee;
Q. Explain Foreign Key and ON DELETE CASCADE with suitable example.
(Foreign key explanation with example – 3Marks, On delete cascade – 1 Mark) 4 Marks
Ans:
Foreign key represents relationship between two tables.
A foreign is a column ( or group of columns) whose values are derived from the „primary
key‟ of same or some other table.
For eg : consider two tables :
Emp={empid, empname, deptno, salary}
Dept= { deptno, deptname}
In table Emp, empid is a primary key which contains unique values to identify each
record.
In table Dept, deptno is a primary key containing unique values for deptnos.
To set the relationship between these two tables, we can define Emp.deptno as a foreign
key as:
1. At creation time (Assuming Dept is already created with deptno as primary key)
Create table Emp ( empid number(4), empname varchar(20), deptno number(3)
constraint fk1 references Dept(deptno) , salary number(10,2));
2. After creation :
Alter table Emp add constraint fk1 foreign key (deptno) references dept(deptno);
On delete cascade :
When a relation is created between two tables, it is permissible to delete records in child
table , but a vice–versa operation is not allowed. i.e. deleting records from parent table
when it is referenced from some other table is not allowed.
On delete cascade clause allows automatic deletion of child records when parent record is
deleted.
Eg :
Alter table Emp add constraint foreign key emp(deptno) references dept(deptno) on delete
cascade;
Q. What are the various datatypes of PL/SQL? 4 Marks
(Any 4 data types -1Mark each)
Ans:
The default data types that can be declared in Pl/SQL are :
1) number (size)– for storing numeric data
eg. a number(2);
2) char/ varchar(size) – for character data
eg: mynamevarchar(20);
3) date – for date and time data
eg : dob date;
4) Boolean – for storing true, false or null
eg: status Boolean;
5) %Type - to declare a variable or constant to have a same data type as that of a
previously defined variable or a column in a table.
e.g. enoemp.empno%type
Q. Explain the difference between DROP and TRUNCATE with example.
(Any 4 valid differences – 1 Mark each OR Explanation of DROP and TRUNCATE – 2
Marks each)
Q. Explain types of JOINs. 4 Marks
(Any four JOINs –1 Mark each)
SQL Join types are as follows:
1) INNER JOIN or EQUI JOIN:
A join which is based on equalities is called equi join. In equi join comparison operator
―=‖ is used to perform a Join.
Syntax:
SELECT tablename.column1_name,tablename.column1_name
FROM table_name1,table_name2
where table_name1.column_name=table_name2.column_name;
Example:
Select stud_info.stud_name,stud_info.branch_code,branch_details.location
From stud_info,branch_details
Where
Stud_info.branch_code=branch_details.branch_code;
2) SELF JOIN:
The SQL SELF JOIN is used to join a table to itself, as if the table were two tables,
temporarily renaming at least one table in the SQL statement.
Syntax:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Example:
Select x.stud_name, y.stud_name from stud_infox,stud_info y
Where x.leader= y.stud_id;
3) LEFT OUTER JOIN:
A left outer join retains all of the rows of the ―left‖ table, regardless of whether
there is a row that matches on the ―right‖ table.
Syntax:
Select column1name,column2name
from
table1name any_alias1 ,table2name any_alias2
on
any_alias1.columnname(+) = any_alias2.columnname;
OR
Select column1name,column2name
from
table1name left outer join table2name on
table1name.columnname= table2name.columnname;
Example:
select
last_name,department_name
from
employeese,departments d
on
e.department_id(+) = d.department_id;
OR
select
last_name,department_name
from
employees left outer join departments
on
employees.department_id = departments.department_id;
4) RIGHT OUTER JOIN
A right outer join retains all of the rows of the ―right‖ table, regardless of whether
there is a row that matches on the ―left‖ table.
Syntax:
Select column1name,column2name
from table1name any_alias1 ,table2name any_alias2
on
any_alias1.columnname =any_alias2.columnname (+);
OR
Select column1name,column2name
from table1name any_alias1 right outer join table2name any_alias2
on
any_alias1.columnname =any_alias2.columnname;
Example:
Select last_name,department_name
from
employeese,departments d
on
e.department_id = d.department_id(+);
OR
Select last_name,department_name
from
employees e right outer join departments d
on
e.department_id = d.department_id;
5) NON EQUI JOIN:
Non equi joins is used to return result from two or more tables where exact join is not
possible.
Syntax:
Select aliasname.column1name, aliasname.column2name from tablename
alias where <condition using range>;
For example:
we have emp table and salgrade table. The salgrade table contains grade and
their low salary and high salary. Suppose you want to find the grade of
employees based on their salaries then you can use NON EQUI join.
Select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s where e.sal
between s.lowsal and s.hisal;
Q. How to use COMMIT, SAVE POINT, ROLLBACK commands. 4 Marks
( Explanation – 3Marks, Example – 1Mark)
Commit:
database.
or ROLLBACK command.
d is as follows:
SQL> COMMIT;
Savepoint:
certain point without rolling back the entire transaction.
SAVEPOINT SAVEPOINT_NAME;
e.g. SAVEPOINT SV1;
Rollback:
saved to the database.
COMMIT or ROLLBACK command was issued.
ROLLBACK TO SAVEPOINT_NAME;
e.g. ROLLBACK TO sv1;
Q. Explain ACID properties. 4 Marks
(Four properties –1 Mark each)
To ensure integrity of the data, we require that the database system maintain the
following properties of the transactions (ACID properties):
Atomicity: Either all operations of the transaction are reflected properly in the
database, or none are.
Consistency: Execution of a transaction in isolation (that is, with no other transaction
executing concurrently) preserves the consistency of the database.
Isolation: Even though multiple transactions may execute concurrently, the system
guarantees that, for every pair of transactions Ti and Tj, it appears to Ti that either
Tjfinished execution before Ti started, or Tjstarted execution after Ti finished. Thus,
each transaction is unaware of other transactions executing concurrently in the system.
Durability: After a transaction completes successfully, the changes it has made to the
database persist, even if there are system failures.
Q. Explain GROUP BY, ORDER BY clause of SQL with example. 4 Marks
(Explanation with syntax / example – 2Marks each)
Group by clause
group by clause can be used in a select statement to collect data across
multiple records and group by one or more columns.
in employee.
Select col1,col2,….,col n aggregate_function (expression)
From table_name
Where predicates
Group by column_name;
Select avg(sal)
From emp
group by deptno;
Order by clause:
result-set by one or more columns.
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
1. SELECT * FROM Customers
ORDER BY Country;
2. SELECT * FROM Customers
ORDER BY Country DESC;
Q. Draw transaction state diagram.
(Correct diagram- 2 Marks)
A transaction must be in one of the following states:
1. Active: the initial state, the transaction stays in this state while it is
executing.
2. Partially committed: after the final statement has been executed.
3. Failed: when the normal execution can no longer proceed.
4. Aborted: after the transaction has been rolled back and the
database has been restored to its state prior to the start of the
transaction.
5. Committed: after successful completion.
Q. Explain concurrent execution of multiple transaction in detail.
A transaction is a collection of operations that perform modifications in database application.
A set of transactions can be executed by some sequence which is called as a schedule.
There are two types of schedules as serial executions and concurrent execution.
When two transactions are executed one after the other, it is called as serial execution and when
they are interleaved, it is called as concurrent execution of transaction.
Concurrent execution should always preserve consistency. This means that even if the
transactions are interleaved, there should not be any damage to data.
Example :
Transaction T1 :Rs. 50 of A‘s account are transferred to B‘s Account.
Transaction T2 : 10% of A‘s balance is transferred to B‘s Account Consider initial amount as
A=100, B=150 so initially A+B=150 Concurrent schedule will appear as :
Initially A=100, B=150 therefore A+B=250.
At the end of both the transactions in above concurrent schedule. The consistency is preserved.
i.e., A=45, B=205 and therefore A+B=250
Q. Describe serializability.
In concurrent execution of transaction, if the consistency level of the concurrent schedule is same
as the consistency level after serial schedule of the same schedule, then that concurrent schedule
is called as serializable concurrent schedule and this property of schedule is called as
serializability.
Serializability ensures consistency of database.
Example :
Transaction T1: Rs. 50 of A‘s account are transferred to B‘s Account.
Transaction T2 : 10% of A‘s balance is transferred to B‘s Account Consider initial amount as
A=100, B=150 so initially A+B=250 Serial Schedule appears as
At the end of serial schedule, A+B=250
Concurrent schedule will appear as:
Here also A+B=250 at the end of schedule, so this concurrent schedule preserves consistency
and hence it is a serializable schedule and shows serializability property.