You are on page 1of 90

1 [Database Management System - 3330703]

Lab Manual
of
Database Management System (3330703)
Semester – 3

Government Polytechnic, Ahmedabad


Programme :Diploma in Computer Engineering

Name of Student :_________________________________________________________________

Enrollment No :_________________________________________________________________________

Shift : Morning / Evening Division : ______________

GTU Term Date :_____ / _____ / _________ To _____ / ______ / __________


2 [Database Management System - 3330703]

PRACTICAL – 1
Queries to
create a table
3 [Database Management System - 3330703]

PRACTICAL – 1

Queries to create a table.

CREATE TABLE COMMAND: -

Create table command is used to create a table. Create table defines column of a table
uniquely.
Each column has minimum three attributes: -
1. Name
2. Data type
3. Size
Each table column is separated from other by a comma (,).

SYNTAX: -

CREATE TABLE <TABLE NAME>


(<COLUMN NAME1> <DATATYPE> (<SIZE>),
<COLUMN NAME2> <DATATYPE> (<SIZE>),
<COLUMN NAME3> <DATATYPE> (<SIZE>));

EXAMPLE : -

CREATE TABLE CUSTOMER


( CUSTID NUMBER(5),
NAME VARCHAR2(10),
ADDRESS VARCHAR2(10),
CNO NUMBER(12) );
4 [Database Management System - 3330703]

Write SQL Syntax to create the given table below.

Table Name Customer Table Name Sale_Detail


Column Name Data Type Column Name Data Type
cid Varchar2(6) cid Varchar2(6)
cname Varchar2(15) Pid Varchar2(6)
city Varchar2(15) Sale Number(3)
state Varchar2(15) saledate date

Table Name Emp_Detail


Table Name Proj_Detail
Column Name Data Type
Column Name Data Type
empno Varchar2(6)
empno Varchar2(6)
empname Varchar2(15)
projno Varchar2(6)
desg Varchar2(15)
hr_worked Number(5)

Table Name Project Table Name Desg_rate


Column Name Data Type Column Name Data Type
projno Varchar2(6) Desg Varchar2(15)
projname Varchar2(15) hr_rate Number(4,2)
Table Name State_Detail
Table Name Product
Column Name Data Type
Column Name Data Type
City Varchar2(10)
pid Varchar2(6)
State Varchar2(10)
pname Varchar2(10)
pcost Number(4,2)
profit Number(3)
5 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
6 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
7 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
8 [Database Management System - 3330703]

PRACTICAL – 2
SQL DDL COMMANDS
– ALTER, RENAME,
TRUNCATE, DROP &
DESC
9 [Database Management System - 3330703]

PRACTICAL – 2

SQL DDL – ALTER, RENAME, TRUNCATE,


DROP & DESC COMMAND.
The structure of a table can be modified by using ALTER table command.
ALTER table allows changing the structure of an existing table.
With ALTER TABLE it is possible to……….
 Add or delete column
 Create or destroy indexes
 Change data type of existing columns.
 Rename columns or table itself.

Alter table works by making a temporary copy of original table.


The alteration is performed on the copy then original table is deleted and the new one is
renamed.
While ALTER TABLE is executing, the original table is still readable by oracle users.

(1). ALTER COMMAND TO ADD NEW COLUMNS: -

SYNTAX: -

ALTER TABLE <TABLE NAME> ADD (<NEW COLUMNNAME> <DATATYPE>


(<SIZE>), (<NEW COLUMNNAME> <DATATYPE>(<SIZE>));

EXAMPLE: -

ALTER TABLE STUDENT ADD CITY VARCAHR2(10);

(2). ALTER COMMAND TO DROP COLUMNS: -

SYNTAX: -

ALTER TABLE <TABLE NAME> DROP COLUMN <COLUMN NAME>;


10 [Database Management System - 3330703]

EXAMPLE: -

ALTER TABLE STUDENT DROP COLUMN CITY;

(3). ALTER COMMAND TO MODIFY EEXISTING COLUMNS: -

SYNTAX: -

ALTER TABLE <TABLE NAME> MODIFY (<COLUMN NAME> <NEW


DATATYPE> (<NEW SIZE>));

EXAMPLE: -

ALTER TABLE STUDENT MODIFY (STUDID VARCHAR2(10));

(2). RENAME COMMAND: -

SYNTAX: -

RENAME <TABLE NAME> TO <NEW TABLENAME>;

EXAMPLE: -

RENAME STUDENT TO STUDENTINFO;

(3).DROP COMMAND: -

Drop table statement with table name can destroy specific table

SYNTAX: -

DROP TABLE <TABLE NAME>;

EXAMPLE: -

DROP TABLE STUDENT;

(4). TRUNCATE TABLE COMMAND: -

Truncate table empties a table completely. Logically it is equivalent to delete stmt that
deletes all rows , but there are practical differences under some circumstances.
Truncate operations drop & re-create table which is much faster than deleting rows one
by one.
Write SQL Statement to perform the given task: -
11 [Database Management System - 3330703]

1. WAQ to add column contact no. data_type number(10) to customer


table.
2. WAQ to modify size of contact no to number(15) instead of
number(10).
3. WAQ to drop column contact no. added to customer table.
4. WAQ to rename customer table to customer information.
5. WAQ to truncate customer information table.
6. WAQ to drop customer information table.
12 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
13 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
14 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
15 [Database Management System - 3330703]

PRACTICAL – 3

SQL QUERIES TO
INSERT, SELECT,
UPDATE & DELETE
DATA
16 [Database Management System - 3330703]

PRACTICAL – 3

SQL QUERIES TO INSERT, SELECT, UPDATE


& DELETE DATA
 INSERT STATEMENT: -
Once a table created, data is loaded in it using Insert command.
It is used to enter either single row or multiple row.

SYNTAX: -
INSERT INTO <TABLE NAME> (<COLUMN NAME1>, <COLUMN NAME2>,
<COLUMN NAME3>) VALUES (<EXPRESSION1>, <EXPRESSION2>,
<EXPRESSION3>);

EXAMPLE: -

(1). QUERY TO INSERT SINGLE ROW

INSERT INTO STUDENT (STUDID, NAME, ADDRESS, CNO) VALUES


(101, „ABC‟, „S.NAGAR‟, „9425784123‟);

(2). QUERY TO INSERT MULTIPLE ROW

INSERT INTO STUDENT VAKUES (&STUDID, ‘&NAME’, ‘&ADDRESS’, &CNO);

Write SQL Queries to Insert following data given into table: -


17 [Database Management System - 3330703]

Table Name Customer1


cid Cname City State
C1 Pradip Mysore Karnatak
C3 Aastik Kolkata West Bengal
C2 Tushar Pune Maharashtra
C4 Arpan Chennai Tamilnadu
C5 Anumita Indore Madhya Pradesh

Table Name State_Detail


City State
Mysore Karnatak
Kolkata West Bengal
Pune Maharashtra
Chennai Tamilnadu
Indore Madhya Pradesh

Table Name Product


pid pname Pcost profit
P3 Pen 20.5 20
P2 Floppy 30 12
P1 Pencil 5.25 10
P4 Rubber 2 10
P5 Paper 20.5 10

Table Name Sale_Detail


cid pid Sale saledt
C1 P3 2 14-jul-04
C3 P2 10 15-jul-04
C2 P3 1 14-jul-04
C1 P4 5 14-jul-04
C1 P1 3 20-aug-04
C4 P5 3 14-nov-04
C5 P4 2 18-sep-04

Table Name Emp_Detail


Empno Empname Desg
E1 Anup Analyst
E2 Arup DBA
18 [Database Management System - 3330703]

E3 Kaushik Analyst
E4 Amit Programmer
E5 Chandra Programmer

Table Name Project1 Table Name Desg_rate


Projno projname desg hr_rate
P2 Coding DBA 1000
P3 Data Recovery Analyst 800
P1 Data base Programmer 500
P4 Website
P5 Desktop proj

Table Name Proj_Detail


empno Projno hr_worked
E1 P2 15
E2 P3 10
E3 P1 40
E4 P4 10
E5 P5 20
E2 P1 30
E5 P4 25

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
19 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
20 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
21 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
22 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
23 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
24 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
25 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
26 [Database Management System - 3330703]

 SELECT STATEMENT: -
Once data is inserted and user need to view the data then use select command.

(1). Select Command to select particular column: -

SYNTAX: -

SELECT COLUNMNAME1, COLUNMNAME2,.., COLUNMNAMEn


FROM TABLE_NAME;
EXAMPLE: -

SELECT STUDID, NAME FROM STUDENT;


(2). Select Command to display all records of table: -

SYNTAX: -

SELECT * FROM TABLENAME;

EXAMPLE: -

SELECT * FROM STUDENT;

(3). Filtering Data using SELECT statement: -

If information of a particular table is to be retrieved on particular condition then use where


clause in query.

SYNTAX: -

SELECT * FROM <TABLENAME> WHERE <CONDITION>;

EXAMPLE: -

SELECT * FROM STUDENT WHERE STUDID = ‘S101’;

(4). Select Command for selected Columns & Rows: -

SYNTAX: -

SELECT <COLUMNNAME1>, <COLUNMNAME2> FROM <TABLENAME>


WHERE <CONDITION>;
27 [Database Management System - 3330703]

EXMAPLE: -

SELECT STUDID, NAME FROM STUDENT WHERE STUDID = ‘S101’;

(5). Select Command for displaying DISTINCT Value: -

A table could hold duplicate rows. In such case, if user wants to view only unique
rows distinct clause is used.

SYNTAX: -

SELECT DISTINCT <COLUMNNAME1>, <COLUMNNAME2> FROM


<TABLENAME>;

EXAMPLE: -

SELECT DISTINCT CITY FROM STUDENT;

SELECT DISTINCT * FROM STUDENT;

(6). Select Command with ORDERBY CLAUSE: -

Oracle allows data from a table to be viewed in a sorted order. The rows retrieved will be
either in ascending order or descending order depending on condition specified.

SYNTAX: -

SELECT * FROM <TABLE NAME> ORDERBY <COLUMNNAME1>,


<COLUNMNAME2> <SORT ORDER>;

EXAMPLE: -

SELECT * FROM STUDENT ORDERBY STUDID; // default ascending order

SELECT * FROM STUDENT ORDERBY STUDID DESC; // descending order


28 [Database Management System - 3330703]

Write SQL Statement to SELECT data as specified below: -

1. WAQ to display customer name & city from customer table.


2. WAQ to display city & statename from state table.
3. WAQ to display all records of employee.
4. WAQ to display all records of project.
5. WAQ to display customer name & city who lives in Mysore.
6. WAQ to display all details of product where product name = “floppy”.
7. WAQ to display all details of Sale_detail where saledt > 15-Jul-04.
8. WAQ to display state where city = “Pune”.
9. WAQ to display all details of Sale_detail for cid = “C1” & pid = “P2”.
10. WAQ to display project name for project no “P3”.
11. WAQ to display employee no, employee name for designation = “Programmer”.
12. WAQ to display all details from proj_detail for empno = “E2” and projno = “P3”.
13. WAQ to display all details of proj_detail for hr_worked > 20.
14. WAQ to display distinct empno & projno from empdetail.
15. WAQ to display distinct city from customer.
16. WAQ to display data from Product sorted on column Profit.
17. WAQ to display data from Empdetail sorted by descending order on column
hr_worked.
18. WAQ to display content of Product sorted by descending order on pcost &
ascending order on profit.

__________________________________________________________________
29 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
30 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
31 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________

 UPDATE STATEMENT: -

Update command is used to change or modify data values in a table. It is used to update
all rows or selected rows.
Set clause here indicates which column data should be modified and new values that they
should hold.

(1). UPDATING ALL ROWS OF A TABLE

SYNTAX: -
32 [Database Management System - 3330703]

UPDATE <TABLE NAME> SET <COLUMNNAME> = <EXPRESSION>;


EXAMPLE: -
UPDATE STUDENT SET CITY = „RAJKOT‟;

(2). UPDATING RECORDS CONDITIONALLY: -

SYNTAX: -

UPDATE <TABLE NAME> SET <COLUMNNAME1> = <EXPRESSION1>,


<COLUMNNAME2> = <EXPERSSION2> WHERE <CONDITION>;

EXAMPLE: -

UPDATE STUDENT SET CITY = „RAJKOT‟ WHERE STUDID = „S101‟ AND NAME
= „ABC‟;

Write SQL Statement to UPDATE data as specified below: -


1. Update Product table by setting profit to15 for product name pencil.
2. Update Sale_detail modify saledt to 15-Nov-04 for cid C4 and pid P5.
3. Change customer city to Rajkot and state to Gujarat for cid = C5.
4. Update projectname to Website for projectno P3.
5. Update project table change designation to “Project head” for empno E3 and
empname “Kaushik”.
33 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
34 [Database Management System - 3330703]

 DELETE STATEMENT: -

Delete Command deletes rows from table that specifies the condition provided by where
clause and returns number of records deleted.

(1). DELETING ALL ROWS OF A TABLE

SYNTAX: -

DELETE FROM <TABLE NAME>;


EXAMPLE: -
DELETE FROM STUDENT;

(2). DELETING SPECIFIC ROWS OF A TABLE

SYNTAX: -

DELETE FROM <TABLE NAME> WHERE <CONDITION>;


EXAMPLE: -
DELETE FROM STUDENT WHERE STUDID = „S101‟;

Write SQL Statement to DELETE data as specified below: -

1. WAQ to delete all data from state_detail.


2. WAQ to delete data from customer for city = “mysore”.
3. WAQ to delete data from product having product name “rubber”.
4. WAQ to delete data from empdetail having hr_worked greater than 20.
5. WAQ to delete data from product having pcost 30 and profit 12.

________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
35 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
36 [Database Management System - 3330703]

PRACTICAL – 4
SQL COMMANDS
to demonstrate
various
functions.

27
37 [Database Management System - 3330703]

PRACTICAL – 4

SQL COMMANDS to demonstrate various


functions.
SQL provides specialized functions to perform operations using data manipulation
commands.
A function is a module that takes one or more arguments and returns a single value.
Functions are very powerful feature of SQL.
It can be used to perform calculation on data, manipulate output for groups of rows,
convert column data types and format dates & numbers.

SINGLE ROW FUNCTION: -

A single row function or scalar function returns only one value for every row queried in
the table. Single row functions can be broadly classified as……………..

 Date function
 Numeric function
 Character function
 Conversion function
 Miscellaneous function
38 [Database Management System - 3330703]

DATE FUNCTION: -
Date functions operate on the date values producing output which also belongs to date
data type.

Sr No. Function Purpose


1 ADD_MONTHS(d,n) where d is Add calendar months to date
date and n is integer
2 LAST_DAY(d) where d is date Last day of the month
3 NEXT_DAY(d , day) where d is Next day of the date specified
date
4 MONTHS_BETWEEN(d1 , d2) Number of months between two dates
where d1 and d2 are dates
5 ROUND(d , [format]) where d is Rounded to the unit specified by the
date format which may be MONTH or YEAR
6 TRUNC(d , [format]) where d is Truncated to the unit specified by the
date Format
7 GREATEST(d1, d2, d3….) where Returns greatest date present in the
d1, d2, d3 are dates argument.
8 LEAST(d1, d2, d3……) where d1, Returns the least date present in the
d2, d3 are dates argument.

Write SQL Statement to perform the given task: -

(1) WAQ to display the system date by rounding it to next month.


(2) WAQ to display the system date by rounding it to the next year.
(3) WAQ to display the last date of the system date.
(4). WAQ to display the next date of system date which is FRIDAY
(5). WAQ to display the system date along with truncated value of sale date to the next
month.
(6). WAQ to display the sale date along with truncated value of sale date to the next
month.
39 [Database Management System - 3330703]

(7). WAQ to display sale date and date after 2 months from sale date.
(8). WAQ to display system date, sale date and months between two dates.
(9). WAQ to display the greatest date between sale date and system date. Name it as BIG
also display sale date and SYSDATE.
(10). WAQ to display the least date between sale date and system date. Name it as
SMALL also display sale date and SYSDATE.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
40 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
41 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
42 [Database Management System - 3330703]

NUMERIC FUNCTION: -

Sr No. Function Purpose


1 ABS(N) Returns absolute value of N
2 POWER(M,N) Returns M raise to Nth power. N must be
an integer else error is returned.
3 SQRT(N) Returns square root of N
4 EXP(N) Returns e raised to nth power.
5 EXTRACT ({YEAR | MONTH | Returns a value extract from a date or an
DAY | HOUR | MINUTE | internal value
SECOND} FROM
{DATEVALUE | INTERNAL
VALUE})
6 GREATEST(EXP1, Returns the greatest value from given
EXP2…EXPN) expression.
7 LEAST(EXP1, EXP2 ….. EXPN) Returns the least value from given
expression.
8 ROUND (column / expression , n) Rounds the columns or value to n
9 TRUNC (column / expression , n) Truncates the column, expression or
value to n decimal places
10 MOD (m , n) Returns the remainder of m/n
11 FLOOR(N) Returns the largest integer value that is
equal to or less than a number
12 CEIL(N) Returns the smallest integer value that is
equal to or less than a number
43 [Database Management System - 3330703]

Write SQL Statement to perform the given task: -


(1). WAQ to display the product name along with the rounded value of product cost for
product name is “PENCIL”.
ANS: select pname, round(pcost) from Product where
pname='Pencil';
(2). WAQ to display the product name along with the rounded value of product cost to 1
decimal places where product name is “PENCIL”.
Ans: select pname, round(pcost,1) from Product where pname='Pencil';
(3). WAQ to display the product name along with the rounded value of product cost to -1
decimal places where product name id “PENCIL”.

(4). WAQ to display product name along with truncated value of product cost to 0, 1, -1
decimal places for PEN.
(5). WAQ to display product cost along with MOD value if divided by 5.
(6). WAQ to find absolute value of -12.
(7). WAQ to find power of (4,2).
(8). WAQ to find square root of 49.
(9). WAQ to find exponent of 7.
(10). WAQ to extract month and year from SYSDATE.
(11). WAQ to find greatest value from 35, 40, 42.
(12). WAQ to find least value from 35, 40, 42.
(13). WAQ to find FLOOR value of 20.15
(14). WAQ to find CEIL value of 20.15
44 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
45 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
46 [Database Management System - 3330703]

CHARACTER FUNCTION: -
Character functions accept data as input and can return both character and number values.

Sr No. Function Purpose


1 LOWER Converts alpha character values to lowercase
2 UPPER Converts alpha character values to uppercase
3 INITCAP Converts first character of alpha character values
to uppercase
4 CONCAT (COL1, COL2, Concatenates the characters.
…., COL N)
5 SUBSTR(COL, M, [N]) Returns specified character from character value
starting at character position m , n characters
long. If m is negative, the cont starts from end of
the character value. If n is omitted, all character
to the end of string are returned.
6 LENGTH(COL) Returns number of characters in value
7 INSTR(COL, M) Returns numeric position of a named character
8 LPAD(COL, N, Pads the character value right-justified to a total
„STRING‟) width of n character positions.
9 RPAD(COL,N) Pads the character value left-justified to a total
width of n character positions.
10 TRIM Trims leading/trailing character from string.
11 ASCII(SINGLE Returns the number code that represent the
CHARACTER) specified character.
12 TRANSLATE (<STRING Replaces a sequence of character in a string with
1>, <STRING TO another set of character. It replaces a single
REPLACE>, character at a time.
<REPLACEMENT
STRING>)

Write SQL Statement to perform the given task: -


47 [Database Management System - 3330703]

(1). WAQ to display all concatenated value of CNAME, CITY by converting CNAME
into title case and CITY into uppercase.
(2). WAQ to display the first three characters of CNAME.
(3). WAQ to display the position of character „M‟ in the CNAME of the customer whose
name id “ANUMITA”.
(4). WAQ to display the length of all customer names.
(5). PAD# character in left of product cost to a total width of 5 character positions.
(6). PAD# character in right of product cost to a total width of 5 character positions.
WAQ to display along with PNAME.
(7). WAQ to display PNAME by trimming „P‟ if it is first character in PNAME.
(8). WAQ to display the customer name, product name and sale details from
CUSTOMER, PRODUCT and SALE_DETAIL table using „||‟ operator.
(9). WAQ to find ASCII value of C.
(10). WAQ for string ABC123XYZ to replace 123 with PQR.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
48 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
49 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________

CONVERSION FUNCTION: -

Sr No. Function Purpose


1 TO_CHAR(number / date , Converts a number or date value to a
[fmt]) VARCHAR2 character string with format
specified in fmt.
2 TO_DATE(char, [fmt]) Converts a character string representing date to a
date value to the format specified. It format is
omitted, the format is DD-MM-YY.
3 TO_NUMBER(char, [fmt]) Converts a character string containing a number
in the format specified by the optional format
specified in fmt.

Write SQL Statement to perform the given task: -


(1). WAQ to display sale date in character format DD-MM-YY from SALE_DETAIL.
(2). WAQ to display sale date in character format DD-MONTH-YYYY HH:MI from
SALE_DETAIL.
(3). WAQ to display sale detail in character format MONTH YEAR from
SALE_DETAIL.
(4). WAQ to display PNAME with difference between 31-Dec-2004 & Sale Date.
50 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
51 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
52 [Database Management System - 3330703]

AGGEGRATE FUNCTION: -

Sr No. Function Purpose


1 AVG([<DISTINCT> | <ALL>] Returns an AVERAGE value of n and
<N>) ignoring NULL values in a column.
2 MIN ([<DISTINCT> | <ALL>] Returns a MINIMUM value of
<EXPR>) expression.
3 MAX ([<DISTINCT> | <ALL>] Returns a MAXIMUM value of
<EXPR>) expression.
4 COUNT ([<DISTINCT> | <ALL>] Returns the number of rows where
<EXPR>) expression is not NULL
5 COUNT (*) Returns the number of rows in the table
including duplicates and those with
NULLS.
6 SUM ([<DISTINCT> | <ALL>] Returns a SUM value of n.
<N>)

Write SQL Statement to perform the given task: -


(1). WAQ to display total count of customer.
(2) WAQ to display minimum cost of product.
(3). WAQ to display maximum cost of product.
(4). WAQ to display average cost of product.
(5). WAQ to display total sale detail.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
53 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
54 [Database Management System - 3330703]

PRACTICAL – 5
Queries to use
SET Operators.
55 [Database Management System - 3330703]

PRACTICAL – 5

Write queries to use SET Operator.

☼ UNION CLAUSE:-
Multiple queries can be put together and their output can be combined using the UNION
clause.
The UNION clause merges the output of two or more queries into a single set of two or
more queries into a single set of rows and columns.

Records only Common Records Records only


In query one From both query In query two

Following points should be considered while working with union clause:

 The number of column and data type of column being selected must be identical in all
the SELECT statement used in the query. The name of column need not be identical.
 NULL values are ignored during duplicate checking.
 By default, output is stored in ascending order of first column of the SELECT clause.

EXAMPLE:-

To find all customer having a loan and an account, or both in bank is written as…

► SELECT CUSTOMER_NAME FROM DEPOSITOR


UNION
SELECT CUSTOMER_NAME FROM BORROWER

UNION automatically eliminates duplicates. If user want to retain


duplicate values write UNION ALL in place of UNION.

► SELECT CUSTOMER_NAME FROM DEPOSITOR


UNION ALL
SELECT CUSTOMER_NAME FROM BORROWER
56 [Database Management System - 3330703]

Restrication on using union clause are as follows:-


 Number of column in all queries should be same.
 The data type of the column in each query must be same.
 Union cannot be used in sub query.
 Aggreate function cannot be used with union clause.

☼ INTERSECT CLAUSE:-
Multiple queries can be put together and their output can be combined using the
INTERSECT clause.

The INTESECT clause outputs the rows produced by both the queries intersected i.e. the
Output in an intersect clause will include only those rows that are retrieved common to
both the Queries.

Common Records In
Both Tables

EXAMPLE :-
To find all customer who have both a loan and an account in the bank is written as..
►SELECT DISTINCT CUSTOMER_NAME FROM DEPOSITOR
INTERSECT
SELECT CUSTOMER_NAME FROM BORROWER

INTERSECTION automatically eliminates duplicates.If user want to retain duplicate


values write INTERSECT ALL in place of UNION.

►SELECT DISTINCT CUSTOMER_NAME FROM DEPOSITOR


INTERSECT ALL
SELECT CUSTOMER_NAME FROM BORROWER

Following points should be considered while working with INTERSECT Clause :-


 The number of column and data type of column being selected must be identical
 In all the SELECT statement used in the query. The name of column need not be
Identiacal.
 INTERESECT does not ignore NULL Value.
57 [Database Management System - 3330703]

MINUS CLAUSE:-
Multiple queries can be put together and their output can be combined using the MINUS
clause.
The MINUS clause outputs the rows produced by first query,after filtering the rows
retrived by the second query.

EXAMPLE:-
To find all customer who have an account but no loan in the bank is written as…
► SELECT DISTINCT CUSTOMER_NAME FROM DEPOSITOR
MINUS
SELECT CUSTOMER_NAME FROM BORROWER

MINUS automatically eliminates duplicates.IF user want to retain duplicate values write
MINUS ALL in place of UNION.

► SELECT DISTINCT CUSTOMER_NAME FROM DEPOSITOR


MINUS ALL
SELECT CUSTOMER_NAME FROM BORROWER
58 [Database Management System - 3330703]

Create the table specified below and insert data into it.

1) Table Name: Client_detail 3) Table Name: Salesman_detail

Column Name Data Type Column Name Data Type


Client_no Varchar2(5) Salesman_no Varchar2(5)
Name Varchar2(15) Name Varchar2(15)
City Varachar2(15) City Varachar2(15)

2) Table Name: Sales_Order 4) Table Name: Sales_Order_Detail

Column_Name Data Type Column_Name Data Type


Order_no Varchar2(5) Order_no Varchar2(5)
Order_date Date Product_no Varchar2(5)
Salesman_no Varchar2(5)

5) Table Name: Product_detail

Column_Name Data Type


Product_no Varchar2(5)
Description Varchar2(15)
59 [Database Management System - 3330703]

Solve Following Queries using SET OPERATORS:-


1) Select Salesman_no,name from salesman_detail and Client_no name from
Client_master having city=Rajkot using UNION
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________

2) Retrive common salesman_no from salesman_detail and sales_order. Use


INTERSECT Clause to find detail from salesman_detail where city=Rajkot.
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
60 [Database Management System - 3330703]

PRACTICAL – 6
To apply all
constraints
using at least
two tables.
61 [Database Management System - 3330703]

PRACTICAL – 6
To apply all constraints using at least two
tables.
Oracle permits data constraint to be attached to table columns via SQL syntax that checks
for integrity prior storage.
Once data constraint are part of a table column, the oracle database engine checks data
being entered into table column against the data constraint.
If data passes this check, it is stored in table column, else data is rejected.
Even if single column of record being entered into table fails a constraint, the entire
record is rejected and not stored in table.
There are two types of data constraint that can be applied to data inserted into table.
(1). I/O constraint
(2). Business Constraint

(1). I/O CONSTRAINT: -


It is mainly used to check data that is input into database.
It consists of Primary Key, foreign Key & Unique Key.
(1). PRIMARY KEY: -
It is used to uniquely identify each row in the table.
It cannot take null value.
It allows only unique data to be entered
Only one Primary key is allowed per table.

SYNTAX: -
<column name> <data type> (<size>) PRIMARY KEY
62 [Database Management System - 3330703]

EXAMPLE: -

CREATE TABLE CUSTOMER_DETAIL(


CUSTID VARCHAR2(10) PRIMARY KEY,
NAME VARCHAR2(15),
ADDRESS VARCHAR2(20),
CITY VARCHAR2(15),
PINCODE NUMBER(8));
(2). FOREIGN KEY: -

Foreign Key represents relationship between tables.


Table that defines primary key or unique key is called primary table or master table.
Table that defines foreign key is called foreign table or detail table.

SYNTAX: -
<column name> <datatype> (<size>) REFERENCES <table name> <column name>

EXAMPLE: -

CREATE TABLE ACT_DETAIL(


ACCNO VARCHAR2(10),
CUSTID VARCHAR2(10) REFERENCES CUSTOMER_DETAIL,
ACCTYPE VARCHAR2(15),
BALANCE NUMBER(10));

(3). UNIQUE KEY: -


It will not allow duplicate values i.e. only unique values.
It allows null values to be entered.
SYNTAX: -
<column name> <datatype>(size) UNIQUE;
63 [Database Management System - 3330703]

EXAMPLE: -
CREATE TABLE CUST_DETAILS
CUSTID VARCHAR2(10) UNIQUE,
NAME VARCHAR2(10),
ADDRESS VARCHAR2(20),
CITY VARCHAR2(15),
PINCODE NUMBER(8));

(2). BUSINESS RULE CONSTRAINT: -


Oracle allows programmer to define constraints at: -
Column level
Table level

(1). NOT NULL Constraint at Column Level: -


In addition to Primary key and Foreign key, Oracle has NOT NULL as column
constraint.
The NOT NULL column constraint ensures that a table column can not be left empty.

SYNTAX: -

<COLUMN NAME> <DATA TYPE> (<SIZE>) NOT NULL;

EXAMPLE: -

CREATE TABLE ACCT_DETAIL(


ACCNO VARCHAR2(10),
CUSTID VARCHAR2(10) REFERENCES CUSTOMER_DETAIL,
ACCTYPE VARCHAR2(15),
BALANCE NUMBER(10) NOTNULL);
64 [Database Management System - 3330703]

(2). CHECK Constraint: -

At column level: -

SYNTAX: -

<COLUMN NAME> <DATATYPE> (<SIZE>) CHECK (<LOGICAL EXPRESSION>)

EXAMPLE: -

CREATE TABLE CUSTOMER (


CUSTNO VARCHAR2(10) CHECK (CUSTNO LIKE „C%‟),
FNAME VARCHAR2(10) CHECK (FNAME = UPPER(FNAME)),
LNAME VARCHAR2(10) CHECK (LNAME = UPPER(LNAME)),
DOB DATE );

At table level: -

SYNTAX: -

CHECK (<LOGICAL EXPRESSION>)

EXAMPLE: -

CREATE TABLE CUSTOMER (


CUSTNO VARCHAR2(10),
FNAME VARCHAR2(10),
CNAME VACRHAR2(10),
DOB DATE,
CHECK(CUSTNO LIKE „C%‟),
CHECK(FNAME = UPPER(FNAME)),
CHECK(LNAME = UPPER(LNAME));

(3). DEFAULT VALUE Constraint: -

It is used to assign default value to a column. When a record is loaded into table and
column is empty, Oracle engine will automatically load this column with default value
specified. The data type of default value should match data type of column.
65 [Database Management System - 3330703]

SYNTAX: -

<COLUMN NAME> <DATATYPE> (<SIZE>) DEFAULT (VALUE);

EXAMPLE: -

CREATE TABLE COMP_STUD_DETAIL(


SID VARCHAR2(10),
SNAME VARCHAR2(20),
BRANCH VARCHAR2(10) DEFAULT „COMPUTER‟);

Now Query…………………

INSERT INTO COMP_STUD_DETAILS (SID, SNAME) VALUES („S001‟, „ABC‟)

Will automatically insert COMPUTER into column branch.

Write SQL Statement to create table with all necessary constraint: -

Table Name: - Employee Detail


Field name Datatype Description
Fname Varchar2(12) First name NOT NULL
Mname Char(1) Middle name
Lname Varchar2(12) Last name NOT NULL
Ssn Varchar2(6) Social Security Number PRIMARY KEY
Bdate Date Birth date
Address Varchar2(20) Address
Gender Char(1) F: female M: Male
Salary Number(10,2) Salary
Suprssn Number(10,2) Supervisor‟s SSN, FOREIGN KEY references
EMP(SSN)
Deptno Varchar2(5) Department no FOREIGN KEY references
DEPT(DEPTNO)
66 [Database Management System - 3330703]

Table Name: - Department

Field name Datatype Description


Dname Varchar2(10) Department name NOT NULL, UNIQUE
Deptno Varchar2(5) Department no PRIMARY KEY
Mgrssn Varchar2(6) Manager‟s SSN no. NOT NULL, FOREIGN
KEY REFERENCES EMP(SSN)

Mgrstrdate Date

Table Name: Dept_loaction

Field Name Datatype Description


Deptno Varchar2(5) FOREIGN KEY REFEENCES
DEPARTMENT(DEPTNO)
Deptloc Varchar2(15) PRIMARY KEY

Table Name: - Project

Field Name Datatype Description


Projname Varchar2(15) NOT NULL, UNIQUE
Projno Varchar2(4) PRIMARY KEY
Projloc Varchar2(15)
Deptno Varchar2(5) FOREIGN KEY REFEENCES
DEPARTMENT(DEPTNO)

Table Name: - Works_on


67 [Database Management System - 3330703]

Field Name Datatype Description


Essn Varchar2(6) FOREING KEY REFERNCES EMP(SSN)
Projno Varchar2(4) FOREING KEY REFERNCES PROJECT(PROJNO)
Hours Number(3,1) NOT NULL

Table Name: - Dependent

Field Name Datatype Description


Essn Varchar2(6) FOREING KEY REFERNCES EMP(SSN)
Dname Varchar2(12) PRIMARY KEY
Gender Char(1) F: female M: Male
Bdate Date Birth date
Rship Varchar2(10) Relationship

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
68 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
69 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
70 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
71 [Database Management System - 3330703]

PRACTICAL – 7
SQL COMMANDS
to perform all
join operations
using at least
two tables.
72 [Database Management System - 3330703]

PRACTICAL – 7

SQL COMMAND to perform all join operation


using at least two tables.
A join condition in a where clause is required to combine all rows from all tables.
If a join condition is omitted, the result is a Cartesian product in which all combinations
of rows will be displayed, which is undesirable in most conditions.
There are four types of joins in SQL. Each is with a different purpose.
EQUI JOIN: -

Equi Join as it name suggests is based on equalities. The equi-join combines rows that
have equivalent values for the specified columns.
This is also called simple join or inner join.
This is the most used join among all.
Consider the EMP, DEPT & SALGRADE table given below: -

TABLE NAME: - EMP

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7499 ALLEN MANAGER 7698 20-FEB-92 1600 300 10
7698 BLAKE ANALYST 7839 01-MAY-90 2850 30
7782 CLARK MANAGER 7566 03-DEC-89 2975 10
7566 FORD CLERK 7839 02-APR-85 2450 1400 10
73 [Database Management System - 3330703]

TABLE NAME: - DEPT

DEPTNO DNAME LOCATION GRADE LOSAL HISAL


10 ACCOUNT NEW YORK 1 700 1200
2 1201 1400
20 RESEARCH DALLAS
3 1401 2000
30 SALES BOSTON

(1). WAQ to display the name and department name of those employee who works in
department no. 10

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
74 [Database Management System - 3330703]

NON EQUI JOIN: -

In case of Non Equi Join column from one table does not directly corresponds to column
of second table.
Non Equi Join is best used with BETWEEN clauses.
This join specifies the relationship between columns belonging to different tables.
In this type of join >, >=, <, <= and != operators can also be used.

(2). WAQ to display the name, salary and grade of those employees whose salary
is greater than 1300 and less than 3000.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
75 [Database Management System - 3330703]

OUTER JOIN: -

An outer join returns all rows returned by simple join. Equi Join as well as those from
one table that do not match any row from the other table.
This type of join is rarely used in practical implementations.

(3). WAQ to display the name of the subordinate who reports to the boss along with the
name of the boss. Included name of employee who does not report to any one.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
76 [Database Management System - 3330703]

SELF JOIN: -

Joining a table t itself is known as Self Join. In this type of join different alias is used for
the same table.
This join is used only in very specific cases.

(4). WAQ to display the name of the subordinate who reports to the boss along with
name of the boss.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________

(5). WAQ to display ENAME, SAL and DEPTNO of those employees who are getting
SAL more than the average salary of the DEPTNO in which they are posted.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
77 [Database Management System - 3330703]

PRACTICAL – 8
Write Queries
using relational
algebra .
78 [Database Management System - 3330703]

PRACTICAL – 8

Write Queries using relational algebra.

 The SELECT operation


 The select operation selects tuples that specify a given predicate.
 We used lower case greek letter sigma(σ) to denote selection.
 the predicate appears as a subscript to σ.
 The argument relation is in parenthesis after the σ.

To solve the query like to select those tuples of the table loan where branch name is
“perryridge”.
Select * from loan where branch_name=”perryridge”;
In relational algebra query is written as
σ branch_name= ”perryridge”(loan)
For example to find data that has amount more than 1200 is written as……
σ amont > 1200 (loan)
We can combine several predicates into larger predicate by using the connectives and (^),
or (\/) and not (¬).
Thus to find those tuples(rows) pertaining to loans of more than $1200 made by
Perryidge branch is written as……………..
σ branch_name = “perryridge” ^ amount > 1200

 The Project operation

Consider loan table as shown below: -

Loan_number Branch_name Amount


L-15 Perriydge 1500
L-16 Perriydge 1300
L-17 Perriydge 1000
79 [Database Management System - 3330703]

Now user wants to find loan_number and amount and don‟t require details of branch-
name. Projection is used to produce this relation
Projection is denoted by uppercase Greek letter pi (‫ )ח‬and is written as…….
‫ח‬loan-number, amount (loan)

 Composition of Relational Operation

Now to find customer who live in Harrison is written as…………………

‫ ח‬customer-name(σcustomer-city = “Harrison”(customer))

 Union Operation

Consider a query to find names of all bank customer who have either an account or loan
or both. To find this information we need depositor relation (table) and borrower relation
(table).
‫ ח‬Customer-name(borrower)
‫ ח‬Customer-name(depositor)
‫ ח‬Customer-name(borrower) Ụ Customer-name(depositor)

 Set-Difference Operation

The set – difference operation denoted by - , allows us to find tuples (rows) that are in
one relation but not in another.
The expression r – s produces a relation contining those tuples in r but not in s.
User can find all customer of bank who have an account but not a loan by writing: -
‫ ח‬Customer-name(depositor) – ‫ ח‬customer-name(borrower)
80 [Database Management System - 3330703]

Cartesian - Product Operation

The Cartesian-Product operation denoted by cross (X), allows us to combine information


from any two relation. We write Cartesian Product of relation r1 and r2 as r1 x r2.
For example relation schema for r = borrower x loan is
(borrower.customer_name, borrower.loanno, loan.loanno, loan.branch_name,
loan.amount)
Thus user can distinguish borrower‟s & loan‟s loan number by borrower.loanno &
loan.loanno.
For example we want to find names of all customers who have loan at Perryridge branch.
Then we need information from both loan relation(table) and borrower relation(table)
Thus we write…………………………….
σ branch-name = “Perridge” (borrower x loan)

If borrower table has 3 rows and loan table has 3 rows then total rows returned by
Cartesian product is 9.

If user wants only that loan number that are in both borrower and loan table & have
branch name = “Perridyge”then it is specified as……………….

σ borrower.loan_number = loan.loan_number
(σbranch_name = “Perridyge” (borrower x loan))

Now to find customer name for condition above stated is written as……..

Customer_name (σborrower.loan_number = loan.loan_number


(σbranch_name = “Perriydge”(borrower x loan)))

Set - Intersection Operation: -

For example if user want to find all customer who have both a loan and an account then
intersection is written as……………

‫ ח‬Customer-name(borrower) ∩ customer-name(depositor)

The intersection operation r ∩ s is performed by following operation: -


r ∩ s = r – (r - s)
81 [Database Management System - 3330703]

Write Relational Algebra for following Queries: -


1. WAQ to display customer name & city from customer table.
2. WAQ to display customer name & city who lives in Mysore.
3. WAQ to display all details of Sale_detail where saledt > 15-Jul-04.
4. WAQ to display project name for project no “P3”.
5. WAQ to display all details of Sale_detail for cid = “C1” & pid = “P2”.

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
82 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
83 [Database Management System - 3330703]

PRACTICAL – 9

SQL Statements to
perform sub queries
and correlate queries.
84 [Database Management System - 3330703]

PRACTICAL – 9

SQL Statement to perform sub queries and


correlate queries.

A subquery is a SQL query nested inside a larger query.

 A subquery may occur in :

o A SELECT clause

o A FROM clause

o A WHERE clause

 The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement
or inside another subquery.

 A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.

 You can use the comparison operators, such as >, <, or =. The comparison operator can also
be a multiple-row operator, such as IN, ANY, or ALL.

 A subquery is also called an inner query or inner select, while the statement containing a
subquery is also called an outer query or outer select.

 The inner query executes first before its parent query so that the results of an inner query
can be passed to the outer query.

You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the
following tasks:

 Compare an expression to the result of the query.

 Determine if an expression is included in the results of the query.

 Check whether the query selects any rows.


Employees
(EMPLOYEE_ID,FIRST_NAME,LAST_NAME ,EMAIL,PHONE_NUMBER,HIRE_DATE,
JOB_ID,SALARY , COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID)
85 [Database Management System - 3330703]

Departments
( DEPARTMENT_ID , DEPARTMENT_NAME , MANAGER_ID , LOCATION_ID )

Locations
(LOCATION_ID,STREET_ADDRESS ,POSTAL_CODE ,CITY, STATE_PROVINCE,
COUNTRY_ID)

1. Write a query to display the name ( first name and last name ) for those employees who gets
more salary than the employee whose ID is 163.

2. Write a query to display the name ( first name and last name ), salary, department id, job id
for those employees who works in the same designation as the employee works whose id is
169.

3. Write a query to display the name ( first name and last name ), salary, department id for
those employees who earn such amount of salary which is the smallest salary of any of the
departments.

4. Write a query to display the department number, name ( first name and last name ), job and
department name for all employees in the Finance department.

5. Write a query to display all the information of an employee whose salary and reporting
person id is 3000 and 121 respectively.

6. Write a query to display all the information of the employees who does not work in those
departments where some employees works whose manager id within the range 100 and 200.

7. Display the employee name( first name and last name ), employee id, and job title for all
employees whose department location is Toronto.

8. Write a query to display the employee number, name( first name and last name ) and job
title for all employees whose salary is smaller than any salary of those employees whose job
title is MK_MAN

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
86 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
87 [Database Management System - 3330703]

__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
__________________________________________________________________
88 [Database Management System - 3330703]

PRACTICAL – 10
Create simple
report using
Break on, btitle,
Title etc.
89 [Database Management System - 3330703]

PRACTICAL – 10

Create simple report using Break on, btitle,


Title etc.
 Reports provide the way to display different operations (query, cursor, trigger
etc).
 Reports formatting command gives output in the form of text or table format (row
and column).
 It takes print on the printer as desired output.
 Oracle provides the different way to develop reports and templates for report
creating.
 SQL Code to generate the report: -

SET PAGESIZE 22
SET LINESIZE 60
SET FEEDBACK OFF
TITLE „BOMBAY SALES CORPORATION | SALES REPORT‟
BTITLE „CONFIDENTIAL‟
COLUMN MEONTH HEADING „MONTH‟ FORMAT A10
COLUMN SALESMAN HEADING „NAME OF SALESMAN‟
FORMAT A20
COLUMN PRODUCT HEADING „PRODUCT‟ FORMAT A10
COLUMN QUANTITY HEADING „QUANTITY‟ FORMAT 99
SELECT MONTH, SALESMAN, PRODUCT, QUANTITY FROM
SALES WHERE PRODUCT = „PENDRIVE‟;
90 [Database Management System - 3330703]

OUTPUT

BOMABY SALES CORPORATION


SALES REPORT

MONTH NAME OF PRODUCT QUANTITY


SALESMAN
JAN KUMARAN PENDRIVE 12
JAN SWAMY PENDRIVE 5
FEB DEEP PENDRIVE 5
FEB KUMARAN PENDRIVE 5
FEB SWAMY PENDRIVE 6
CONFIDENTIAL

You might also like