You are on page 1of 70

CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY (Autonomous)

Department of Computer Science and Engineering

Year-II Semester-IV

DATABASE MANAGEMENT SYSTEMS LAB RECORD

(Code- 18CSC15)

Submitted to :

Mrs.D.Naga Jyothi

Assistant Professor,Dept of CSE.

Submitted by :

Student Name: Aishwarya Jaini

Roll no: 160118733121

B.E-2/4, CSE-3

1
LIST OF EXPERIMENTS

S.No NAME OF THE EXPERIMENT PAGE


NO
1 Write the sample queries on single row numeric functions 5

2 Write the sample queries on single row character functions 9

3 Write the sample queries on date functions 18

4 Write the sample queries on conversion functions- to_date and to_char 25

5 Write the sample queries using DML commands – insert, update, delete and select 26

6 Write the sample queries on aggregate functions(min, max, count, sum, avg) 28

7 Write the sample queries on set operations(union, intersect and minus) 30

8 Write the sample queries using group by and order by functions 31

9 Write the sample queries using some, any and all operators 34

10 Create the following tables 35

EMP(eno,ename,job,… ........................................ )
DEPT(deptno,dname,……)
SALGRADE(… .... )
Use the various integrity constraints like primary key, foreign key, not null,
check constraints while creating and altering the tables.

11 Write the sample queries using other DDL commands- alter, truncate, drop 36

12 Write the sample queries using DCL commands – grant and revoke 37

13 Write the sample queries using TCL commands – commit, rollback and savepoint 39

14 Write the sample queries to exercise all the joins – inner join, left outer join, right 42
outer join and full outer joins

15 Write the sample queries to create the view and show an updation on the view 44

16 Write the sample queries on sequences, indexes and synonyms 46

17 Display the last 3 characters of the employee name in uppercase directly followed by 52
the job.
2
18 Display all the employees who earning salary not in the range of 2500 and5000 in 52
department 10 & 20.

19 List the emps whose jobs are same as SMITH or ALLEN. 53

20 How many clerks are there in the company? Which department exactly employs one 53
clerk?

21 How many employees are there in each department? 54

22 Display the number of employee for each job goup deptno wise. 55

23 Display the employees who do not manage any one. 55

24 List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order. 56

25 Which department has highest number of salesman, show the department number and 56
the count?
26 Find the lowest paid employee of sales department. 56

27 Display the unique jobs in the company 56

28 List the details of the emps working at Chicago. 57

29 Find all the employees whose salary can be <2000 or >4000 57

30 Find all the employees whose name starts with ‘S’ and has 6 characters in the name. 58

31 Find out all those managers and jr.managers who are drawing salary more than 10,000 58

32 Write the query to display the employee as well as department details department wise. 58

33 List the details of most recently hired emp of dept 30. 59

34 List the emps who joined in the company on the same date. 59

35 Get employee details from employee table who joined before January 1st 2013 60

36 Select all the employees who are earning same as SMITH 61

37 Write a query to display the ith maximum salary. 61

38 For each department show its deptno and average salary. Sort the result in descending 61
order of the average salary.

39 Display the Empno, Ename, job, Hiredate, Experience of all Managers. 62

3
40 Form the employee table by generating the following output: 62
Who , what , and when
………………………………………………………………………………
…………..
Eg: ford is held the position of analyst in dept no 20

41 Find the minimum, maximum and average salary for each job title . 62

42 Show the details of the staff who are not working in the research department. 63

43 Calculate the number of months between today and hired date of the employee. Order 63
the results by the number of months.
44 List the details of the department where maximum number of emps are working. 64

45 Get the first day of the given month. 64

46 Write a pl/sql block to find out if a number is odd or even. 65

47 Write a pl/sql block to input a number with substitution variable and then print its 65
multiplication table using for and while loop

48 Write a pl/sql block to avail 20% bonus to all employees who are receiving the 67
commission.

49 Write a pl/sql block using implicit cursors to get the number of employees. 67

50 Write a pl/sql block using explicit cursors to get the employee data. Print the 68
employee’s annual salary if the amount is less than 50000.

51 Write a pl/sqlblock to find the maximum of two numbers using functions. 69

4
1. AIM: Write the sample queries on single row numeric functions

single row functions: Single-row functions return a single result row for every row of a

queried table or view. These functions can appear in select lists, WHERE clauses, START

WITH and CONNECT BY clauses, and HAVING clauses.

Numeric Functions

Numeric functions accept numeric input and return numeric values. Most numeric

functions that return NUMBER values that are accurate to 38 decimal digits. The

transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and

TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN,

ATAN, and ATAN2 are accurate to 30 decimal digits. The numeric functions are:

ABS

CEIL

FLOOR

LOG

MOD

NANVL

POWER

ROUND (number)
SIGN
TRUNC (number)

ABS

Syntax: - abs(n)

ABS return the absolute value of n.

Example: -select abs (-5) from dual;

ABS (-5)

5
5

CEIL

Syntax: - ceil(n)

CEIL returns smallest integer greater than or equal to n.

Example: - select ceil (23.587) from dual;

CEIL (23.587)

24

FLOOR

Syntax: - floor(n)

FLOOR returns largest integer equal to or less than n.

Example: - select floor (23.587) from dual;

FLOOR (23.587)

23
LOG

Syntax: - log(n)

LOG returns the logarithm, base n2, of n1. The base n1 can be any positive value other

than 0 or 1 and n2 can be any positive value.

Example: - select log (2) from dual;

LOG (2)

0.3010299957

MOD

Syntax: - mod (n2, n1)

6
MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.

Example: - select mod (15,4) from dual;

MOD (15,4)

POWER

Syntax: - power (n2, n1)

POWER returns n2 raised to the n1 power. The base n2 and the exponent n1 can

be any numbers, but if n2 is negative, then n1 must be an integer.

Example: - select power (2,4) from dual;

POWER (2,4)

16

ROUND (number)

Syntax: - round (n, integer)


ROUND returns n rounded to integer places to the right of the decimal point. If you omit

integer, then n is rounded to 0 places. The argument integer can be negative to round off

digits left of the decimal point. For NUMBER values, the value n is rounded away from 0

(for example, to x+1 when x.5 is positive and to x-1 when x.5 is negative).

Example: -

• select round (23.587) from dual;


ROUND (23.587)

24

• select round (23.587,1) from dual;

ROUND (23.587,1)

7
23.6

• select round (23.587, -1) from dual;

ROUND (23.587, -1)

20

• select round (63.587, -1) from dual;

ROUND (63.587, -1)

60

SIGN

Syntax: - sign (n)

SIGN returns the sign of n. This function takes as an argument any numeric

datatype, or any nonnumeric datatype that can be implicitly converted to NUMBER,

and returns NUMBER. For value of NUMBER type, the sign is:

• -1 if n<0

• 0 if n=0

• 1 if n>0

Example: - select sign (23.587) from dual;

SIGN (23.587)

TRUNC (number)

Syntax: - trunc (n2, n1)

The TRUNC (number) function returns n1 truncated to n2 decimal places. If n2 is omitted,

then n1 is truncated to 0 places. n2 can be negative to truncate (make zero) n2 digits left

of the decimal point.

Example: -

8
• select trunc (23.587) from dual;

TRUNC (23.587)

23

• select trunc (23.587, -1) from dual;


TRUNC (23.587, -1)

20

• select trunc (23.587,1) from dual;

TRUNC (23.587,1)

23.5

• select trunc (23.587, -2) from dual;

TRUNC (23.587, -2)

2. AIM: Write the sample queries on single row character functions

single row character functions: Character functions that return character values return values

of the following datatypes unless otherwise documented:

• If the input argument is CHAR or VARCHAR2, then the value returned is

VARCHAR2. • If the input argument is NCHAR or NVARCHAR2, then the value

returned is NVARCHAR2. The character functions that return character values are:

CHR

CONCAT

INITCAP

9
LOWER

LPAD

LTRIM

REPLACE

RPAD
RTRIM

SUBSTR

TRANSLATE

TRIM
UPPER
CHR

Syntax: - chr (n)

CHR returns the character having the binary equivalent to n as a VARCHAR2 value in

either the database character set or, if you specify USING NCHAR_CS, the national

character set. This function takes as an argument a NUMBER value, or any value that

can be implicitly converted to NUMBER, and returns a character.

Example: - select chr (65) from dual;

CONCAT

Syntax: - concat (char1, char2)

CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the

datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string

returned is in the same character set as char1. Its datatype depends on the datatypes of the

arguments. In concatenations of two different datatypes, Oracle Database returns the

10
datatype that results in a lossless conversion.

Example: - select concat('h','ello') from dual;

CONCA

Hello

INITCAP

Syntax: - initcap (char)

INITCAP returns char, with the first letter of each word in uppercase, all other letters in

lowercase. Words are delimited by white space or characters that are not alphanumeric.

Example: - select initcap ('h23l4 hi') from dual;

INITCAP (

H23l4 Hi

LOWER

Syntax: - lower(chr)

LOWER returns char, with all letters lowercase. char can be any of the datatypes CHAR,

VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same

datatype as char. Example: - select chr (65) from dual;

LOWER

h2334

LPAD

Syntax: - lpad (expr1, n, expr2)

LPAD returns expr1, left-padded to length n characters with the sequence of characters in

expr2. This function is useful for formatting the output of a query.

If you do not specify expr2, then the default is a single blank. If expr1 is longer than n,

11
then this function returns the portion of expr1 that fits in n.

Example: - select lpad ('h2334',10,'0') from dual;

LPAD ('H233

00000h2334

LTRIM

Syntax: - ltrim (char, set)

LTRIM removes from the left end of char all of the characters contained in set. If you

do not specify set, it defaults to a single blank. If char is a character literal, then you

must enclose it in single quotes. Oracle Database begins scanning char from its first

character and removes all characters that appear in set until reaching a character not in

set and then returns the result. Example: - select ltrim('hi2334','h') from dual;

LTRIM

i2334

REPLACE

Syntax: - replace (char, search string, replacement string)

REPLACE returns char with every occurrence of search string replaced with replacement

string. If replacement string is omitted or null, then all occurrences of search string are

removed. If search string is null, then char is returned.

REPLACE provides functionality related to that provided by the TRANSLATE

function. TRANSLATE provides single-character, one-to-one substitution. REPLACE

lets you substitute one string for another as well as to remove character strings.

Example: - select replace('hhih2334','hh','09') from dual;

REPLACE (

12
09ih2334

RPAD

Syntax: - rpad (expr1, n, expr2)

RPAD returns expr1, right-padded to length n characters with expr2, replicated as many
times as necessary.
This function is useful for formatting the output of a query.

expr1 cannot be null. If you do not specify expr2, then it defaults to a single blank. If

expr1 is longer than n, then this function returns the portion of expr1 that fits in n.

The argument n is the total length of the return value as it is displayed on your terminal

screen. In most character sets, this is also the number of characters in the return value.

However, in some multibyte character sets, the display length of a character string can

differ from the number of characters in the string.

Example: - select rpad ('h2334',10,'0') from dual;

RPAD ('H233

h233400000

RTRIM

Syntax: - rtrim (char, set)

RTRIM removes from the right end of char all of the characters that appear in set. This

function is useful for formatting the output of a query.

If you do not specify set, then it defaults to a single blank. If char is a character literal,

then you must enclose it in single quotes. RTRIM works similarly to LTRIM.

Example: - select rtrim('hi2334','24') from dual;

RTRIM

hi233

13
SUBSTR

Syntax: - substr (char, position, substring length)

The SUBSTR functions return a portion of char, beginning at character position, substring

length characters long. SUBSTR calculates lengths using characters as defined by the

input character set. SUBSTRB uses bytes instead of characters.

• If position is 0, then it is treated as 1.

• If position is positive, then Oracle Database counts from the beginning of char to

find the first character.

• If position is negative, then Oracle counts backward from the end of char.

• If substring length is omitted, then Oracle returns all characters to the end of char. If

substring length is less than 1, then Oracle returns null.

Example: -

• select substr('hello',3,2) from dual;


SU

--

ll

• select substr ('hello',3) from dual;

SUB
---

llo

• select substr ('hello’, -2,2) from dual;

SU
--

lo

TRANSLATE

Syntax: - translate (expr, from string, to string)

14
TRANSLATE returns expr with all occurrences of each character in from string replaced by

its corresponding character in to string. Characters in expr that are not in from string are not

replaced. If expr is a character string, then you must enclose it in single quotation marks. The

argument from string can contain more characters than to string. In this case, the extra

characters at the end of from string have no corresponding characters in to string. If these

extra characters appear in char, then they are removed from the return value.

TRANSLATE provides functionality related to that provided by the REPLACE

function. REPLACE lets you substitute a single string for another single string, as well

as remove character strings. TRANSLATE lets you make several single-character,

one-to-one substitutions in one operation. Example: - select

translate('hei2h334','hi','09') from dual;

TRANSLAT

0e920334

TRIM

Syntax: - trim (trim character from trim source)

TRIM enables you to trim leading or trailing characters (or both) from a character

string. If trim character or trim source is a character literal, then you must enclose it in

single quotes. • If you specify LEADING, then Oracle Database removes any leading

characters equal to trim character.

• If you specify TRAILING, then Oracle removes any trailing characters

equal to trim character.

• If you specify BOTH or none of the three, then Oracle removes leading and

trailing characters equal to trim character.

• If you do not specify trim character, then the default value is a blank space.

• If you specify only trim source, then Oracle removes leading and trailing blank

15
spaces. • The function returns a value with datatype VARCHAR2. The maximum

length of the value is the length of trim source.

• If either trim source or trim character is null, then the TRIM function

returns null. Example: - select trim ('h' from 'hi2334') from dual;

TRIM (

i2334

UPPER

Syntax: - upper (chr)

UPPER returns char, with all letters uppercase. char can be any of the datatypes CHAR,

VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same

datatype as char. Example: -

• select upper('h2334') from dual;

UPPER

H2334

• select upper('hello') from dual;

UPPER

HELLO
Character Functions Returning Number Values

Character functions that return number values can take as their argument any character

datatype. The character functions that return number values are:

ASCII

INSTR

LENGTH

16
ASCII

Syntax: - ascii (chr)

ASCII returns the decimal representation in the database character set of the first character

of char. char can be of datatype CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The

value returned is of datatype NUMBER. If your database character set is 7-bit ASCII, then

this function returns an ASCII value.

Example: -

• select ascii('h') from dual;

ASCII('H')

104

• select ascii('H') from dual;

ASCII('H')

72

INSTR

Syntax: - instr (string, substring, position, occurrence)

The INSTR functions search string for substring. The function returns an integer

indicating the position of the character in string that is the first character of this

occurrence. INSTR calculates strings using characters as defined by the input character

set.

• position is an nonzero integer indicating the character of string where Oracle

Database begins the search. If position is negative, then Oracle counts backward

from the end of string and then searches backward from the resulting position.

Example: -

• select instr('hello','h') from dual;

INSTR('HELLO','H')
17
1

• select instr ('hello','y') from dual;

INSTR('HELLO','Y')

LENGTH

Syntax: - length (chr)

The LENGTH functions return the length of char. LENGTH calculates length using

characters as defined by the input character set.

Example: - select length('h') from dual;

Output: -

LENGTH('H')

3. AIM: Write the sample queries on date functions

Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP

WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval

(INTERVAL DAY TO SECOND, INTERVAL YEAR TO MONTH) values.

Some of the datetime functions were designed for the Oracle DATE datatype

(ADD_MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If

you provide a timestamp value as their argument, Oracle Database internally converts the

input type to a DATE value and returns a DATE value. The exceptions are the

MONTHS_BETWEEN function, which returns a number, and the ROUND and TRUNC

functions, which do not accept timestamp or interval values at all. The datetime functions

18
are:

ADD_MONTHS

CURRENT_DATE

CURRENT_TIMESTAMP

LAST_DAY

LOCALTIMESTAMP

MONTHS_BETWEEN

NEW_TIME
NEXT_DAY

ROUND (date)

SYSDATE

SYSTIMESTAMP

TO_CHAR (datetime)
TRUNC (date)
ADD_MONTHS

Syntax: - add_months (date, integer)

ADD_MONTHS returns the date date plus integer months. The date argument can be a
datetime value or

any value that can be implicitly converted to DATE. The integer argument can be an integer or

any value that can be implicitly converted to an integer. The return type is always DATE,

regardless of the datatype of date. If date is the last day of the month or if the resulting month

has fewer days than the day component of date, then the result is the last day of the resulting

month. Otherwise, the result has the same day component as date.

Example: -

• select add_months ('12/11/2019',3) from dual;

ADD_MONT

12-02-20

19
• select add_months ('12/8/2019',3) from dual;

ADD_MONT

12-11-19

CURRENT_DATE

Syntax: - current_date

CURRENT_DATE returns the current date in the session time zone, in a value in the
Gregorian calendar of datatype DATE.

Example: - select current_date from dual;

CURRENT_

23-12-19

CURRENT_TIMESTAMP

Syntax: - current_timestamp(precision)

CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value

of datatype TIMESTAMP WITH TIME ZONE. The time zone offset reflects the current local

time of the SQL session. If you omit precision, then the default is 6. The difference between this

function and LOCALTIMESTAMP is that CURRENT_TIMESTAMP returns a TIMESTAMP

WITH TIME ZONE value while LOCALTIMESTAMP returns a TIMESTAMP value.

Example: -

select current_timestamp from dual;

CURRENT_TIMESTAMP

23-12-19 10:36:58.577000000 AM GMT

LAST_DAY

Syntax: - last_day(date)

20
LAST_DAY returns the date of the last day of the month that contains the date. The

return type is always DATE, regardless of the datatype of date.

Example: -

• select last_day ('1-01-2019') from dual;

LAST_DAY

31-01-19

• select last_day(sysdate) from dual;

LAST_DAY

31-12-19

MONTHS_BETWEEN

Syntax: - months_between (date1, date2)

MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is

later than date2, then the result is positive. If date1 is earlier than date2, then the result is

negative. If date1 and date2 are either the same days of the month or both last days of months,

then the result is always an integer. Otherwise Oracle Database calculates the fractional

portion of the result based on a 31-day month and considers the difference in time components

date1 and date2.

Example: -

• select months_between ('27/02/2001','11/10/1998') from dual;

MONTHS_BETWEEN ('27/02/2001','11/10/1998')

28.516129

• select months_between ('27/02/2001','27/10/2001') from dual;

21
MONTHS_BETWEEN ('27/02/2001','27/10/2001')

-8

NEW_TIME

Syntax: - new_time (date, timezone1, timezone2)

NEW_TIME returns the date and time in time zone timezone2 when date and time in time

zone timezone1 are date. Before using this function, you must set the

NLS_DATE_FORMAT parameter to display 24-hour time. The return type is always

DATE, regardless of the datatype of date.

Example: - select new_time ('11-10-99 ', 'ast', 'pst') from dual;

NEW_TIME

10-10-99

NEXT_DAY

Syntax: - next_day (date, char)

NEXT_DAY returns the date of the first weekday named by char that is later than the date

date. The return type is always DATE, regardless of the datatype of date. The argument char

must be a day of the week in the date language of your session, either the full name or the

abbreviation. The minimum number of letters required is the number of letters in the

abbreviated version. Any characters immediately following the valid abbreviation are

ignored. The return value has the same hours, minutes, and seconds component as the

argument date.

Example: - select next_day('23/12/2019','wednesday') from dual;

NEXT_DAY

25-12-19

22
ROUND (date)

Syntax: - round (date, fmt)

ROUND returns date rounded to the unit specified by the format model fmt. The value

returned is always of datatype DATE, even if you specify a different datetime datatype for

date. If you omit fmt, then date is rounded to the nearest day. The date expression must

resolve to a DATE value.

Example: -

• select round(to_date('10/10/2019'),'mon') from dual;

ROUND (TO

01-10-19

• select round(to_date('23/10/2019'),'mon') from dual;

ROUND (TO

01-11-19
• select round(to_date('23/12/2019'),'mon') from dual;

ROUND (TO

01-01-20

• select round(to_date('23/10/2019'),'year') from dual;

ROUND (TO

01-01-20

• select round(to_date('10/10/2019'),'mon') from dual;

ROUND (TO

23
01-10-19

SYSDATE

Syntax: - sysdate

SYSDATE returns the current date and time set for the operating system on which the database
resides. The datatype of the returned value is DATE, and the format returned depends on the
value of the NLS_DATE_FORMAT initialization parameter. The function requires no
arguments. In distributed SQL statements, this function returns the date and time set for the
operating system of your local database.
Example: - select sysdate from dual;

SYSDATE

23-12-19

SYSTIMESTAMP

Syntax: - systimestamp

SYSTIMESTAMP returns the system date, including fractional seconds and time

zone, of the system on which the database resides. The return type is TIMESTAMP

WITH TIME ZONE. Example: - select systimestamp from dual;

SYSTIMESTAMP

23-12-19 02:36:58.702000000 AM -08:00

TRUNC (date)
Syntax: - trunc (date, fmt)

The TRUNC (date) function returns date with the time portion of the day truncated to the

unit specified by the format model fmt. The value returned is always of datatype DATE,

even if you specify a different datetime datatype for date. If you omit fmt, then date is

truncated to the nearest day. Please refer to "ROUND and TRUNC Date Functions" for the

permitted format models to use in fmt.

24
Example: - select trunc(to_date('25-oct-2001','DD-MON-YY'), 'YEAR')

from dual; TRUNC (TO

01-01-01

4. AIM: Write the sample queries on conversion functions- to_date and to_char

Conversion functions convert a value from one datatype to another. Generally, the

form of the function names follows the convention datatype TO datatype. The first

datatype is the input datatype. The second datatype is the output datatype.

The SQL conversion functions are:

TO_CHAR

TO_DATE

TO_CHAR
Syntax: - to_char (n, fmt, ‘nlsparam’)

TO_CHAR (number) converts n to a value of VARCHAR2 datatype, using the

optional number format fmt. The value n can be of type NUMBER,

BINARY_FLOAT, or BINARY_DOUBLE. If you omit fmt, then n is converted to a

VARCHAR2 value exactly long enough to hold its significant digits.

Example: -

• select to_char (to_date ('27-02-2001'),'day dd-month-yyyy') from dual;

TO_CHAR (TO_DATE ('27-02-2001

Tuesday 27-february -2001

• select to_char (sysdate, ‘day mm-dd-yyyy') from dual;


TO_CHAR (SYSDATE,'DAY

Monday 12-23-2019

25
TO_DATE

Syntax: - to_date (char, fmt, ‘nlsparam’)

TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype

to a value of DATE datatype. The fmt is a datetime model format specifying the format of

char. If you omit fmt, then char must be in the default date format. If fmt is J, for Julian,

then char must be an integer. Example: -

• select to_date('10-02-2001','mm-dd-yy') from dual;

TO_DATE (

02-10-01

• select to_date('12-feb-19','dd-mm-yy') from dual;

TO_DATE (

12-02-19

5. AIM: Write the sample queries using DML commands – insert, update,

delete and select

Data Manipulation Language (DML) statements or commands are used for managing

data within tables. Some commands of DML are:

Some commands of DML are:

• SELECT – retrieve data from the database

• INSERT – insert data into a table

• UPDATE – updates existing data within a table

• DELETE – deletes all records from a table, the space for the records remain

Insert:

The insert statement is used to add new row to a table.

INSERT INTO <table name> VALUES (<value 1>, ... <value n>);

26
Example:

INSERT INTO STUDENT VALUES (1001, ‘Ram’);


The inserted values must match the table structure exactly in the number of attributes

and the data type of each attribute. Character type values are always enclosed in single

quotes; number values are never in quotes; date values are often (but not always) in the

format ‘yyyy-mm-dd’ (for example, ‘2006-11- 30’).

UPDATE:

The update statement is used to change values that are already in a table.
UPDATE <table name> SET <attribute> = <expression> WHERE <condition>;
Example:
UPDATE STUDENT SET Name = ‘Amar’ WHERE StudID=1001;

The update expression can be a constant, any computed value, or even the result of a

SELECT statement that returns a single row and a single column.

DELETE:

The delete statement deletes row(s) from a table.


DELETE FROM <table name> WHERE <condition>;

Example:
DELETE FROM STUDENT WHERE StudID=1001;

If the WHERE clause is omitted, then every row of the table is deleted that matches

with the specified condition.

SELECT:

The SELECT statement is used to form queries for extracting information out of the

database. SELECT <attribute>, ...... , <attribute n> FROM <table name>;

Example:

SELECT StudID, Name FROM STUDENT;

27
6. AIM: Write the sample queries on aggregate functions (min, max, count, sum,

avg) Aggregate functions in DBMS take multiple rows from the table and return a value

according to the query.

All the aggregate functions are used in Select statement.

Syntax:

SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>

Example: - select * from SCOTT.EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-12-80 800 20

7499 ALLEN SALESMAN 7698 20-02-81 1600 300 30

7521 WARD SALESMAN 7698 22-02-81 1250 500 30

7566 JONES MANAGER 7839 02-04-81 2975 20

7654 MARTIN SALESMAN 7698 28-09-81 1250 1400 30


7698 BLAKE MANAGER 7839 01-05-81 2850 30

7782 CLARK MANAGER 7839 09-06-81 2450 10

7788 SCOTT ANALYST 7566 19-04-87 3000 20

7839 KING PRESIDENT 17-11-81 5000 10

7844 TURNER SALESMAN 7698 08-09-81 1500 0 30

7876 ADAMS CLERK 7788 23-05-87 1100 20


7900 JAMES CLERK 7698 03-12-81 950 30

7902 FORD ANALYST 7566 03-12-81 3000 20

7934 MILLER CLERK 7782 23-01-82 1300 10

AVG Function

This function returns the average value of the numeric column that is supplied as a

parameter. Example: - select avg(sal) from scott.emp;

AVG(SAL)

28
2073.21429

COUNT Function

The count function returns the number of rows in the result. It does not count the null

values. Types:

1. COUNT (*): Counts all the number of rows of the table including null.

2. COUNT(COLUMN_NAME): count number of non-null values in column.

3. COUNT (DISTINCT COLUMN_NAME): count number of distinct values

in a column. Example:

select count(sal) from scott.emp;

COUNT(SAL)

14

MAX Function

The MAX function is used to find maximum value in the column that is supplied as a

parameter. It can be used on any type of data.

Example: - select max(sal) from scott.emp;

MAX(SAL)

5000

MIN Function

The MIN function is used to find minimum value in the column that is supplied as a

parameter. It can be used on any type of data.

Example: - select min(sal) from scott.emp;

MIN(SAL)

29
800

SUM Function

This function sums up the values in the column supplied as a parameter.

Example: - select sum(sal) from scott.emp;

SUM(SAL)

29025

7. AIM: Write the sample queries on set operations (union, intersect and minus) SQL

supports few Set operations which can be performed on the table data. These are used to

get meaningful results from data stored in the table, under different special conditions. In

this tutorial, we will cover 4 different types of SET operations, along with example: 1.

UNION

2. INTERSECT

3. MINUS

UNION

UNION is used to combine the results of two or more SELECT statements. However,

it will eliminate duplicate rows from its result set. In case of union, number of columns

and datatype must be same in both the tables, on which UNION operation is being

applied.

Example: - select * from scott.emp where deptno=10 union select * from scott.emp

where sal>3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7782 CLARK MANAGER 7839 09-06-81 2450 10

7839 KING PRESIDENT 17-11-81 5000 10

7934 MILLER CLERK 7782 23-01-82 1300 10

30
INTERSECT

Intersect operation is used to combine two SELECT statements, but it only returns the

records which are common from both SELECT statements. In case of Intersect the

number of columns and datatype must be same.

NOTE: MySQL does not support INTERSECT operator.

Example: - select * from scott.emp where deptno=10 intersect select * from scott.emp

where sal>3000; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

----------- ---------- 7839 KING PRESIDENT 17-11-81 5000 10

MINUS

The Minus operation combines results of two SELECT statements and return only

those in the final result, which belongs to the first set of the result.

Example: - select * from scott.emp where deptno=10 intersect select * from scott.emp where

sal>3000; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

------------- ----------- 7782 CLARK MANAGER 7839 09-06-81 2450 10

7934 MILLER CLERK 7782 23-01-82 1300 10

8. AIM: Write the sample queries using group by and order by functions

SQL’s ORDER BY, GROUP BY, are a few of the cornerstones in SQL for managing

and organizing the data received from the database. ORDER BY handles the order the

records will be returned. GROUP BY finds similar results and clumps them together.

Two more important keywords are commonly used with ORDER BY, they are

DESC for descending and ASC for ascending. SQL defaults with ascending

order. You would just implement it like so: ORDER BY username DESC.

31
Syntax for order by function:

Select column_name from table_name order by column_name

Example: - select * from scott.emp where deptno=10 order by empno;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7782 CLARK MANAGER 7839 09-06-81 2450 10

7839 KING PRESIDENT 17-11-81 5000 10


7934 MILLER CLERK 7782 23-01-82 1300 10

The GROUP BY Statement in SQL is used to arrange identical data into groups with

the help of some functions. i.e. if a particular column has same values in different rows

then it will arrange these rows in a group.

Important Points:

• GROUP BY clause is used with the SELECT statement.

• In the query, GROUP BY clause is placed after the WHERE clause.

• In the query, GROUP BY clause is placed before ORDER BY clause if used any.

Syntax:

SELECT column1, function_name(column2)

FROM table_name
WHERE condition

GROUP BY column1, column2


ORDER BY column1, column2;

Example: -

• select bname, avg(a_bal) from account group by bname;

BNAME AVG(A_SAL)

HYDERABAD 25500

32
MADHAPUR 95000

• select bname, count(a_no) from account group by bname;

BNAME COUNT(A_NO)

HYDERABAD 2

MADHAPUR 1

HAVING Clause

We know that WHERE clause is used to place conditions on columns but what if we

want to place conditions on groups?

This is where HAVING clause comes into use. We can use HAVING clause to place

conditions to decide which group will be the part of final result-set. Also, we cannot

use the aggregate functions like SUM (), COUNT () etc. with WHERE clause. So,

we have to use HAVING clause if we want to use any of these functions in the

conditions.

Syntax:

SELECT column1, function_name(column2)

FROM table_name
WHERE condition

GROUP BY column1, column2


HAVING condition
ORDER BY column1, column2;

Example: -

• select bname, avg(a_bal) from account group by bname having

avg(a_bal)>12000; BNAME AVG(A_SAL)

HYDERABAD 25500

MADHAPUR 95000

33
• select avg(a_bal) from account, customer, depositor

where customer. ccity='hyderabad' and customer. cname=depositor. cname and

depositor. a_no=account. A_no

group by depositor. a_no having count (depositor. a_no)>=1;

AVG(A_SAL)

5000

9. AIM: Write the sample queries using some, any and all operators

The ‘ALL’, ‘ANY’, ’SOME’ operator compares value to every value returned by the

subquery. All of these operators must follow a comparison operator. The syntax of

using these operators with MySQL subquery is as follows:

Syntax for using ‘ALL’

Operand comparison operator ALL (subquery)

Example: -

select ename, sal from scott.emp where sal>=all ('1300','1500');

ENAME SAL

ALLEN 1600

JONES 2975

BLAKE 2850
CLARK 2450
SCOTT 3000

KING 5000

TURNER 1500

FORD 3000

Syntax for using ‘ANY’

Operand comparison operator ANY (subquery)

34
Example: -

select * from scott.emp where sal = any (800,1200);

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

------------- ------------- 7369 SMITH CLERK 7902 17-DEC-80 800 20

Syntax for using ‘SOME’

Operand comparison operator SOME (subquery)

Example: -

select job from scott.emp where sal = some (800,1500);

JOB

CLERK

SALESMAN

10) AIM :To create the following tables


EMP(eno,ename,job,… ........................................ )

DEPT(deptno,dname,……)

SALGRADE(… .... )

Using the various integrity constraints like primary key, foreign key, not null, check constraints
while creating and altering the tables.
QUERY:
create table aemp(
eno number(4) CONSTRAINT aemp_eno_u UNIQUE ,
ename varchar(20) CONSTRAINT aemp_name_nn NOT NULL,
ejob varchar(20), esal number(10),
edept number(5) CONSTRAINT aemp_edept_pk PRIMARY KEY);
create table adept(

35
deptno number(5) CONSTRAINT adept_no_fk REFERENCES
aemp(edept), deptname varchar(10)); create table asalgrade( asal
number(10), agrade varchar(5));
OUTPUT :

11. AIM :Write the sample queries using other DDL commands- alter, truncate,
drop.
QUERY :
create table aemp(
eno number(4) CONSTRAINT aemp_eno_u UNIQUE ,
ename varchar(20) CONSTRAINT aemp_name_nn NOT NULL,
ejob varchar(20), esal number(10),
edept number(5) CONSTRAINT aemp_edept_pk PRIMARY KEY);
create table adept(
deptno number(5) CONSTRAINT adept_no_fk REFERENCES
aemp(edept), deptname varchar(10)); create table asalgrade( asal
number(10), agrade varchar(5)); alter table aemp drop column eno; truncate
table asalgrade;
OUTPUT :

36
12. AIM: Write the sample queries using DML commands – insert, update, delete

and select

Data Manipulation Language (DML) statements or commands are used for managing data within
tables. Some commands of DML are:
Some commands of DML are:
• SELECT – retrieve data from the database
• INSERT – insert data into a table
• UPDATE – updates existing data within a table
• DELETE – deletes all records from a table, the space for the records remain

Insert:
The insert statement is used to add new row to a table.
INSERT INTO <table name> VALUES (<value 1>, ... <value n>);

Example:-
INSERT INTO student(Roll_no,NAM,Marks,CGPA,Attendence,phone_no)
VALUES(130,jyoshna,98,8.6,97,9999999999);

1 row inserted.

UPDATE:
The update statement is used to change values that are already in a table. UPDATE
<table name> SET <attribute> = <expression> WHERE <condition>;

Example:
UPDATE STUDENT SET Name = ‘Amar’ WHERE StudID=1001;
1 row updated

DELETE:
The delete statement deletes row(s) from a table.
DELETE FROM <table name> WHERE <condition>;

37
Example:-
DELETE FROM student WHERE Attendence<65;
1 row deleted.

SELECT:
The SELECT statement is used to form queries for extracting information out of the database.
SELECT <attribute>, ....... , <attribute n> FROM <table name>;
Example:
SELECT StudID, Name FROM STUDENT;

AIM:Write the sample queries using DCL commands – grant and revoke.

DESCRIPTION:Data Control Language(DCL) is used to control privileges in Database. To


perform any operation in the database, such as for creating tables, sequences or views, a user
needs privileges. Privileges are of two types,

• System: This includes permissions for creating session, table, etc and all types of other

system privileges.

• Object: This includes permissions for any command or query to perform any operation

on the database tables.


In DCL we have two commands,

• GRANT: Used to provide any user access privileges or other priviliges for the database.

• REVOKE: Used to take back permissions from any user.

QUERIES:grant select on myemp to cse_132;

revoke select on myemp from cse_132;

OUTPUT:

38
13. AIM:Write the sample queries using TCL commands – commit, rollback and savepoint.

COMMIT :

DESCRIPTION: command is used to permanently save any transaction into the database.

ROLLBACK command restores the database to last commited state. It is also used with the
SAVEPOINT command to jump to a savepoint in an ongoing transaction.

SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.

QUERIES:

1) CREATE TABLE EMP130 AS(SELECT * FROM MYEMP);

DELETE FROM EMP130 WHERE SAL<1500;


COMMIT;

SELECT * FROM EMP130;

OUTPUT :

2)DELETE FROM EMP130 WHERE EMPNO=7788;

SAVEPOINT A; SELECT

* FROM EMP130;

39
OUTPUT :

DELETE FROM EMP130 WHERE EMPNO=7902;

SAVEPOINT B; SELECT

* FROM EMP130;

OUTPUT :

3)ROLLBACK TO A;

SELECT * FROM EMP130;

OUTPUT :

40
41
42
43
44
[Type here]

45
46
47
U cH
using the
li t OrdCr to ••• a s cq'Llcncc, you must first gcnCratC the initial sequence nlJ mbcr by

insert into student3


values(Order 'N umbcr_ScqucnCC.N EXTVAL,’rOSv’,990,8 . 99,88, I 290374873) t

insert into studei›t3


values(Ord cr_fi umbc i_Scqucncc. NEXT VAL,’rr\0 l',980,g.89,84,1290774878); Select
* from studcnl3;

OUTPUT :

2 l0lbobby 83.2 123t56765


3 100 zac . 88.6 12345S7951
4 ! * ^Y 950 8 • 55 66 12S037t87S
!5 2saggl 560 6 • 29 54 1 290T7tg 78

The CURRV AL option returns ihc current sequence number, but ivlll not e.tecute unless the
Sequence has been callCd at lCdSi one time using ilie N EXTVAL option.

An example usine CURR¥'AL:

QUERY :

insert into student3


values(Ordcr_Numbcr_Scquence.CURRVAL,’NODDl',987,8.00,84,I 290684g 78);

insert into sNdent3


48
49
50
51
17. Display the last 3 characters of the employee name in uppercase directly followed by the

job.
QUERY:
select
upper(SUBSTR(ENAME,-3,3)),JOB
FROM myemp;
OUTPUT:

18. Display all the employees who earning salary not in the range of 2500 and5000 in
department 10 &20
QUERY:
SELECT *
FROM myemp
where (sal NOT BETWEEN 2500 AND 5000)AND(deptno=10 OR deptno=20);
OUTPUT:

52
19. List the emps whose jobs are same as SMITH or ALLEN.

QUERY:
select *
from myemp where job in(select job from myemp where ename
in('SMITH','ALLEN'));
OUTPUT:

20.

a.How many clerks are there in the company?


QUERY:
SELECT
JOB,count(*) from
myemp where
job='CLERK' group
by job;
OUTPUT:

b.Which department exactly employs one clerk?


QUERY:
SELECT
deptno,JOB,count(*) from
myemp where
job='CLERK' GROUP BY
job,deptno
HAVING count(*)=1;
OUTPUT:

53
21. How many employees are there in each department?

QUERY:

SELECT deptno,count(*)
no_of_employees from myemp group by
deptno;

54
22. Display the number of employee for each job group deptno wise.

QUERY:
SELECT deptno,job,count(*) no_of_employees from
myemp
group by deptno,job;
OUTPUT:

23. Display the employees who do not manage any one.


QUERY:
select ename,job from
myemp where job !=
'MANAGER';
OUTPUT:

55
24. List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order.

QUERY:
SELECT ENAME,JOB
FROM myemp
WHERE job IN ('CLERK','ANALYST')
order by ename DESC;
OUTPUT:

25. Which department has highest number of salesman, show the department number and the
Count?
QUERY:
select deptno,count(*) from myemp where
job='SALESMAN' and deptno in
(select deptno from myemp where job='SALESMAN' group by deptno having count(*) in (select
max(count(*)) from myemp where job='SALESMAN' group by deptno)) group by deptno;
OUTPUT:

26. Find the lowest paid employee of sales department.

QUERY:
select * from myemp where sal in (select
min(sal) from myemp
where deptno in(select deptno from scott.dept where dname='SALES'));
OUTPUT:

27. Display the unique jobs in the company


QUERY:

56
select DISTINCT job from
myemp;

28. List the details of the emps working at Chicago.


QUERY:
select * from myemp
where deptno in(select deptno from scott.dept where loc='CHICAGO');

OUTPUT:

29. Find all the employees whose salary can be &lt;2000 or &gt;4000 QUERY:
SELECT ename,sal
FROM myemp
WHERE sal NOT BETWEEN 2000 AND 4000;
OUTPUT:

57
30. Find all the employees whose name starts with ‘S’ and has 6 characters in the name.

QUERY:
select ename from myemp
where ename like 'S ';
OUTPUT:

no rows selected
31. Find out all those managers and jr.managers who are drawing salary more than 10,000
QUERY:
select ename,sal from
myemp
where job='MANAGER' AND sal>=10000;
OUTPUT:

no rows selected
32. Write the query to display the employee as well as department details department wise.
QUERY:
select ename,sal,dname,loc from
myemp,scott.dept
where myemp.deptno=scott.dept.deptno;

58
OUTPUT:

33. List the details of most recently hired emp of dept 30.
QUERY:
SELECT *
FROM myemp where deptno=30 AND HIREDATE IN (SELECT MAX(HIREDATE)
FROM myemp where deptno=30);

34. List the emps who joined in the company on the same date.
QUERY:
select e.*
from myemp e,myemp s
where e.HIREDATE=s.HIREDATE AND e.empno<>s.empno;
OUTPUT:

59
35. Get employee details from employee table who joined before January 1st 2013 QUERY:
select *
from myemp
where HIREDATE<'01-JAN-2013';
OUTPUT:

60
36. AIM : Select all the employees who are earning same as SMITH

QUERY :
select ename from MYEMP where sal=(select sal from MYEMP where ename='SMITH');

OUTPUT :

37. AIM :Write a query to display the ith maximum salary.

QUERY:
select empno,ename,sal from MYEMP e1 where &n=(select count(distinct(sal)) from MYEMP
e2 where e2.sal>=e1.sal);

OUTPUT :

38. AIM :For each department show its deptno and average salary. Sort the result in
descending order of the average salary.

QUERY :
select deptno,avg(sal) from MYEMP group by deptno order by avg(sal) desc;

OUTPUT :

61
39. AIM :Display the Empno, Ename, job, Hiredate, Experience of all Managers.

QUERY :
select ename,empno,job,hiredate,round((current_date-hiredate)/365) experience from MYEMP
where job='MANAGER';

OUTPUT :

40. AIM :Form the employee table by generating the following output:
Who , what , and when
…………………………………………………………………………………………..

Eg: ford is held the position of analyst in dept no 20

QUERY :
select ename || ' is held the position of '||job ||' in dept no '|| deptno from MYEMP;

OUTPUT :

41. AIM :Find the minimum, maximum and average salary for each job title.

62
QUERY :
SELECT JOB,MIN(SAL),MAX(SAL),AVG(SAL) FROM MYEMP
GROUP BY JOB;

OUTPUT :

42. AIM :Show the details of the staff who are not working in the research department.
QUERY :
select empno,ename,job,DNAME
from myemp NATURAL JOIN DEPT
where deptno NOT in (select deptno from dept where dname='RESEARCH');
OUTPUT :

43. AIM:Calculate the number of months between today and hired date of the employee.
Order the results by the number of months.

QUERY :
select MONTHS_BETWEEN(current_date,hiredate) months,ename from myemp order by
months;

OUTPUT :

63
44. AIM :List the details of the department where maximum number of emps are working.

QUERY :
select deptno,dname,loc,count(*)
from myemp natural join dept
group by deptno,dname,loc
having count(*) in (select max(count(*)) from myemp group by deptno);

OUTPUT :

45. AIM :Get the first day of the given month.

QUERY and OUTPUT :

select last_day(add_months(sysdate,-1))+1 as first_day_of_given_month from dual;

select trunc(to_date('23-feb-20'),'month') from dual;

64
pl/sql programs :

46. AIM : Write a pl/sql block to find out if a number is odd or even.

PROGRAM:
declare
n integer:= &n;
begin
if mod(n,2)=0 then
dbms_output.put_line('num1 is even');
else
dbms_output.put_line('num1 is odd');
end if;
end;
OUTPUT :

47. AIM :Write a pl/sql block to input a number with substitution variable and then print
its multiplication table using for and while loop

65
PROGRAM:
declare
n integer:=&n;
i integer;
m integer;
limit integer:=&limit;
begin
i:=1;
dbms_output.put_line('multiplication table of:'||n);
for i in 1..limit
loop
m:=n*i;
dbms_output.put_line(n||'*'||i||'='||m);
end loop;
end;

OUTPUT :

66
48. AIM :Write a pl/sql block to avail 20% bonus to all employees who are receiving the
commission.

PROGRAM :
select * from myemp;
begin
update myemp
set sal=sal+(sal*0.2)
where comm is not null;
end;

OUTPUT :

49. AIM :Write a pl/sql block using implicit cursors to get the number of employees.

PROGRAM :
IMPLICIT :
declare
total number(10);
begin
update myemp
set comm=comm+0;
total:=sql%rowcount;
dbms_output.put_line('total number of employees are :' || total);
end;
OUTPUT :

67
EXPLICIT:
declare
e_no myemp.empno%type;
e_name myemp.ename%type;
e_job myemp.job%type;
e_sal myemp.sal%type;
cursor e_emp1 is select empno,ename,job,sal
from myemp;
begin
open e_emp1;
dbms_output.put_line('total number of employees are:');
loop
fetch e_emp1 into e_no,e_name,e_job,e_sal;
exit when e_emp1%notfound;
end loop;
dbms_output.put_line(e_emp1%rowcount);
close e_emp1;
end;

OUTPUT :

50. AIM :Write a pl/sql block using explicit cursors to get the employee data. Print the
employee’s annual salary if the amount is less than 50000.

PROGRAM :
declare
e_no myemp.empno%type;
e_name myemp.ename%type;
e_job myemp.job%type;
e_sal myemp.sal%type;
cursor e_emp is
select empno,ename,job,sal*12 from myemp
where((sal*12)<50000);
begin
open e_emp;
dbms_output.put_line('salaries of emloyees who earn less than 50000 per annum are:');
loop
fetch e_emp into e_no,e_name,e_job,e_sal;
exit when e_emp%notfound;

68
dbms_output.put_line(e_sal);
end loop;
close e_emp;
end;

OUTPUT :

51. AIM :Write a pl/sqlblock to find the maximum of two numbers using functions.

PROGRAM:
DECLARE
a number :=&a;
b number :=&b;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
c := findMax(a, b);
dbms_output.put_line(' Maximum of (a,b): ' || c);
END;

OUTPUT :

69
70

You might also like