0% found this document useful (0 votes)
83 views52 pages

Chaitanya Bharathi Institute of Technology (Autonomous) Department of Computer Science and Engineering Year-II Semester-IV

The document contains sample queries on various single row numeric functions in Oracle such as ABS, CEIL, FLOOR, LOG, MOD, POWER and ROUND. These functions accept numeric inputs and return numeric outputs. Examples are provided for each function to demonstrate how it works and the output it returns. Functions like ABS return absolute value, CEIL returns smallest integer greater than or equal to input, FLOOR returns largest integer less than or equal to input, LOG returns logarithm, MOD returns remainder, POWER returns exponent and ROUND rounds number to specified number of decimal places.

Uploaded by

P Sai Kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views52 pages

Chaitanya Bharathi Institute of Technology (Autonomous) Department of Computer Science and Engineering Year-II Semester-IV

The document contains sample queries on various single row numeric functions in Oracle such as ABS, CEIL, FLOOR, LOG, MOD, POWER and ROUND. These functions accept numeric inputs and return numeric outputs. Examples are provided for each function to demonstrate how it works and the output it returns. Functions like ABS return absolute value, CEIL returns smallest integer greater than or equal to input, FLOOR returns largest integer less than or equal to input, LOG returns logarithm, MOD returns remainder, POWER returns exponent and ROUND rounds number to specified number of decimal places.

Uploaded by

P Sai Kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Mamidi Aishwarya. .

Roll No:-160118733122

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 Mamidi

Roll no: 160118733122


Mamidi Aishwarya. . Roll No:-160118733122

B.E-2/4, CSE-3

LIST OF EXPERIMENTS

S.No NAME OF THE EXPERIMENT PAGE


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

2 Write the sample queries on single row character functions 5

3 Write the sample queries on date functions 11

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

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

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

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

8 Write the sample queries using ​group by​ and ​order by​ functions 22

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

10 Create the following tables 25

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 26

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

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

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

15 Write the sample queries to create the view and show an updation on the view 33
Mamidi Aishwarya. . Roll No:-160118733122

16 Write the sample queries on ​sequences, indexes​ and ​synonyms 34

17 Display the last 3 characters of the employee name in uppercase directly followed by the job. 34

18 Display all the employees who earning salary not in the range of 2500 and5000 in department 10 34
& 20.

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

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

21 How many employees are there in each department? 35

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

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

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

25 Which department has highest number of salesman, show the department number and the count? 39

26 Find the lowest paid employee of sales department. 39

27 Display the unique jobs in the company 39

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

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

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

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

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

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

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

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

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

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


Mamidi Aishwarya. . Roll No:-160118733122

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

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

40 Form the employee table by generating the following output: 43


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 . 44

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

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

44 List the details of the department where maximum number of emps are working. 45

45 Get the first day of the given month. 45

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

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

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

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

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

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


Mamidi Aishwarya. . Roll No:-160118733122

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

CEIL

Syntax​: - ceil(n)
CEIL returns smallest integer greater than or equal to n.
Mamidi Aishwarya. . Roll No:-160118733122

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)


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)
----------
3

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)
Mamidi Aishwarya. . Roll No:-160118733122

----------
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)
---------------
23.6
• select round (23.587, -1) from dual;
ROUND (23.587, -1)
----------------
20

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)
------------
1

TRUNC​ (number)
Mamidi Aishwarya. . Roll No:-160118733122

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​: -
• 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)
----------------
0
Mamidi Aishwarya. . Roll No:-160118733122

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
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;
C
-
A

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. In concatenations of
two different datatypes, Oracle Database returns the datatype that results in a lossless
conversion.
Mamidi Aishwarya. . Roll No:-160118733122

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 lower('HI') from dual;
LOWER
-----

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, 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)
Mamidi Aishwarya. . Roll No:-160118733122

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 (
--------
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.
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
Mamidi Aishwarya. . Roll No:-160118733122

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

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


RTRIM
-----
hi233

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 cha
• 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)
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.
Mamidi Aishwarya. . Roll No:-160118733122

TRANSLATE provides functionality related to that provided by the REPLACE function.


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 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

Character Functions Returning Number Values


Mamidi Aishwarya. . Roll No:-160118733122

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

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

INSTR
Syntax:​ - instr (string, substring, position, occu)
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')
------------------
1

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;
LENGTH('H')
-----------
Mamidi Aishwarya. . Roll No:-160118733122

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 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
• select add_months ('12/8/2019',3) from dual;
ADD_MONT
Mamidi Aishwarya. . Roll No:-160118733122

--------
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
LOCALTIMESTAM 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)
LAST_DAY returns the date of the last day of the month that contains 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
Mamidi Aishwarya. . Roll No:-160118733122

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;
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;
Mamidi Aishwarya. . Roll No:-160118733122

NEXT_DAY
--------
25-12-19

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'),'year') from dual;
ROUND (TO
--------
01-01-20

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
-------------------------------------
Mamidi Aishwarya. . Roll No:-160118733122

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.

Example​: -
select trunc(to_date('25-oct-2001','DD-MON-YY'), 'YEAR') from dual;
TRUNC (TO
--------
01-01-01
Mamidi Aishwarya. . Roll No:-160118733122

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

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 (
--------
Mamidi Aishwarya. . Roll No:-160118733122

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>);

Example​:-
INSERT INTO student(Roll_no,NAM,Marks,CGPA,Attendence,phone_no)
VALUES(121,'Aishwarya',98,9.8,97,9603884455);

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>;

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​:
Mamidi Aishwarya. . Roll No:-160118733122

SELECT StudID, Name FROM STUDENT;

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>

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)
----------
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
Mamidi Aishwarya. . Roll No:-160118733122

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)
----------
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
Mamidi Aishwarya. . Roll No:-160118733122

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

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
Mamidi Aishwarya. . Roll No:-160118733122

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
Mamidi Aishwarya. . Roll No:-160118733122

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.

Syntax for order by function:


Select column_name from table_name order by column_name

Example​:-
select *
from student
WHERE Attendence>=75
order by roll_no DESC;

ROLL_NO NAM MARKS CGPA ATTENDENCE


---------- -------------------- ---------- ---------- ----------
. 143 qwer 101 4 67
122 anvesh 98 9 97
124 ashish 45 8 78
125 eshid 67 5 90
126 dev 34 6 87

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;
Mamidi Aishwarya. . Roll No:-160118733122

Example:-
SELECT gender,count(*)
FROM class122
GROUP by gender;

GENDER COUNT(*)
---------- ----------
f 1
m 3

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 gender,count(*)
from class122
group by gender
HAVING count(*)=3;

ROLL_NO GENDER ADM_NO


---------- ---------- ----------
124 . m 4567
125 m 4578
126 m 3456
Mamidi Aishwarya. . Roll No:-160118733122

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)
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
Mamidi Aishwarya. . Roll No:-160118733122

10. Create the following table

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.

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


add constraint esal_ck check(esal>=10000);
Mamidi Aishwarya. . Roll No:-160118733122

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

ALTER:-
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also
used to add and drop various constraints on the existing table.

Syntax:-
ALTER TABLE table_name;

DROP:-
DROP is used to delete a whole database or just a table.The DROP statement destroys the
objects like an existing database, table, index, or view.

Syntax:-
DROP object object_name

QUERY:-
alter table asalgrade
drop column asal;

OUTPUT:-

TRUNCATE:-
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark the
extents of a table for deallocation (empty for reuse).

Syntax:-
TRUNCATE TABLE table_name;

QUERY:-
truncate table asalgrade;

OUTPUT:-
Mamidi Aishwarya. . Roll No:-160118733122

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

insert into aemp(eno,ename,ejob,esal,edept)

values(12,'Aish','manager',100000,30);

update aemp
set eno=10;

select * from aemp;

delete from aemp where ename='Aish';

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

GRANT:-
To grant privileges to a user account, the GRANT statement is used.

Syntax:​GRANT privileges_names ON object TO user;

Query
create table employee(
emp_name varchar(20),
emp_id number(10),
sal number(10));
grant SELECT
on employee
Mamidi Aishwarya. . Roll No:-160118733122

to cse_123;

REVOKE:-
The Revoke statement is used to revoke some or all of the privileges which have been granted
to a user in the past.

Syntax:​REVOKE privileges ON object FROM user;

Query
create table employee(
emp_name varchar(20),
emp_id number(10),
sal number(10));

grant SELECT,INSERT
on employee
to cse_123,cse_121;

REVOKE INSERT ON employee


FROM cse_121,cse_123;

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

COMMIT: ​If everything is in order with all statements within a single transaction, all changes
recorded together in the database are called committed. The COMMIT command saves all the
transactions to the database since the last COMMIT or ROLLBACK command.

Syntax:-​COMMIT;

ROLLBACK: ​If any error occurs with any of the SQL grouped statements, all changes need to
be aborted. The process of reversing changes is called ​rollback​. This command can only be
used to undo transactions since the last COMMIT or ROLLBACK command was issued.

Syntax:-​ROLLBACK;
Mamidi Aishwarya. . Roll No:-160118733122

SAVEPOINT:​ creates points within the groups of transactions in which to ROLLBACK.A


SAVEPOINT is a point in a transaction in which you can roll the transaction back to a certain
point without rolling back the entire transaction.

Syntax:-​SAVEPOINT SAVEPOINT_NAME;

Employee table:-

Query:-

update employee2

set sal=2000

where emp_name='bbb';

savepoint bbb_sal;

update employee2

set sal=30000

where emp_name='ccc';

Commit;

update employee2

set sal=30

where emp_name='ccc';

savepoint ccc_sal;

rollback;

select * from employee2;


Mamidi Aishwarya. . Roll No:-160118733122

Output:-

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

create table students


(
roll_no NUMBER(10),
stud_names varchar(10),
age NUMBER(5),
gender VARCHAR(4)
);
create table stud_record
(
roll_no NUMBER(10),
m1 NUMBER(5),
m2 NUMBER(6),
attendance NUMBER(4)
);
INSERT INTO students VALUES(&roll_no,'&stud_names',&age,'&gender');
INSERT INTO stud_record VALUES(&roll_no,&m1,&m2,attendance);

select *
from students;

select *
from stud_record;
Mamidi Aishwarya. . Roll No:-160118733122

NATURAL JOIN

select *
from students natural join stud_record;

LEFT OUTER JOIN


select st.*,m1,m2,attendence
from students st left outer join stud_record re
on st.roll_no=re.roll_no;

RIGHT OUTER JOIN


select re.*,stud_names,age,gender
from students st right outer join stud_record re
on st.roll_no=re.roll_no;
Mamidi Aishwarya. . Roll No:-160118733122

SELF JOIN:-

select e.ename,e.mgr,s.ename,s.empno
from myemp e,myemp s
where e.mgr=s.empno;

FULL OUTER JOIN:

select *
from students full outer join stud_record
USING(roll_no);

INNER JOIN

select *
from students inner join stud_record
on students.roll_no=stud_record.roll_no;
Mamidi Aishwarya. . Roll No:-160118733122

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

Query:-

create view managers as


select empno,ename,job,sal
from emp
where job=’MANAGER’;
select * from managers;

Output​;:-

Query:​-

create or replace view managers as


select empno,ename,job,sal,mgr
from emp
where job=’MANAGER’;
select * from managers;

Output​:-
Mamidi Aishwarya. . Roll No:-160118733122

drop view managers

17.Display the last 3 characters of the employee name in uppercase directly followed by
the job.

select upper(SUBSTR(ENAME,-3,3)),JOB
FROM myemp

18.Display all the employees who earning salary not in the range of 2500 and5000 in
department 10 &20

SELECT *
FROM myemp
where (sal NOT BETWEEN 2500 AND 5000)AND(deptno=10 OR deptno=20);

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


select *
from myemp
where job in(select job from myemp where ename in('SMITH','ALLEN'));
Mamidi Aishwarya. . Roll No:-160118733122

20.
a.How many clerks are there in the company?

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

b.Which department exactly employs one clerk?

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

21.How many employees are there in each department?

SELECT deptno,count(*) no_of_employees


from myemp
group by deptno;
Mamidi Aishwarya. . Roll No:-160118733122

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

SELECT deptno,job,count(*) no_of_employees


from myemp
group by deptno,job;

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

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

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

SELECT ENAME,JOB
FROM myemp
Mamidi Aishwarya. . Roll No:-160118733122

WHERE job IN ('CLERK','ANALYST')


order by ename DESC;

25.Which department has highest number of salesman, show the department number and
the Count?

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;

26.Find the lowest paid employee of sales department.

select * from myemp


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

27.Display the unique jobs in the company

select DISTINCT job


from myemp;
Mamidi Aishwarya. . Roll No:-160118733122

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

select * from myemp


where deptno in(select deptno from scott.dept where loc='CHICAGO');

29.Find all the employees whose salary can be &lt;2000 or &gt;4000

SELECT ename,sal
FROM myemp
WHERE sal NOT BETWEEN 2000 AND 4000;

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

select ename
from myemp
where ename like 'S_____';
Mamidi Aishwarya. . Roll No:-160118733122

no rows selected

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

select ename,sal
from myemp
where job='MANAGER' AND sal>=10000;

no rows selected

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

select ename,sal,dname,loc
from myemp,scott.dept
where myemp.deptno=scott.dept.deptno;

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

SELECT *
FROM myemp
where deptno=30 AND HIREDATE IN (SELECT MAX(HIREDATE) FROM myemp where
deptno=30);
Mamidi Aishwarya. . Roll No:-160118733122

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

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

select *
from myemp
where HIREDATE<'01-JAN-2013';

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

select e.*
from myemp e
WHERE sal in (select sal from myemp where ename='SMITH');
Mamidi Aishwarya. . Roll No:-160118733122

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

SELECT deptno,ROUND(AVG(sal),2) avgsal


from myemp
group by deptno
order by avgsal DESC;

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

select
empno,ename,job,HIREDATE,ROUND((MONTHS_BETWEEN(CURRENT_DATE,HIREDATE)/
12),1) Exp
from myemp
where job='MANAGER';

40.From the employee table by generating the following output


Who, what, and when

Eg:-ford is held in the position of analyst in deptno 30

select ename ||' is held the position of '||job||' in deptno'||deptno as str


from myemp;
Mamidi Aishwarya. . Roll No:-160118733122

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

SELECT JOB, MIN(SAL) MINSAL,MAX(SAL) MAXSAL,ROUND(AVG(SAL),1) AVGSAL


FROM myemp
GROUP BY JOB;

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

select *from myemp,scott.dept


where dname<>'RESEARCH' AND myemp.deptno=scott.dept.deptno;
Mamidi Aishwarya. . Roll No:-160118733122

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

SELECT empno,ename,HIREDATE,ROUND(months_between(current_date,HIREDATE),0)
MONTHSBETWEEN
from myemp;

44. List the details of the department where maximum number of emps are working.
select *from mydept
where deptno in (select deptno from myemp group by deptno having count(*) in (select
max(count(*)) from myemp group by deptno))
Mamidi Aishwarya. . Roll No:-160118733122

PL/SQL PROGRAMS

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

DECLARE
a number(3):=65;
BEGIN

IF MOD(a,2)=0 THEN
dbms_output.put_line('The given number is even');
ELSE
dbms_output.put_line('The given number is odd');
END IF;
dbms_output.put_line('Value of a is:- '||a);
END;

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

WHILE LOOP:-

DECLARE
a number(3):=&a;
i NUMBER:=1;
BEGIN
WHILE i<=10 LOOP
dbms_output.put_line(a||'*'||i||'='||a*i);
i:=i+1;
END LOOP;
END;
Mamidi Aishwarya. . Roll No:-160118733122

FOR LOOP:-

DECLARE
a number(3):=&a;
i NUMBER:=1;
BEGIN
FOR i IN 1..10 loop
dbms_output.put_line(a||'*'||i||'='||a*i);

END LOOP;
END;

3.Write a pl/sql block to avail 20% bonus to all employees who are receiving the
Commission.

SELECT * FROM MYEMP;


BEGIN
UPDATE MYEMP SET SAL=(SAL+(SAL*0.2))
WHERE COMM IS NOT NULL;
END;
Mamidi Aishwarya. . Roll No:-160118733122

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

DECLARE
m_empno myemp.empno%type;
m_ename myemp.ename%type;
r NUMBER(10);
CURSOR m_myemp is
select empno,ename from myemp;

begin
open m_myemp;
loop
fetch m_myemp INTO m_empno,m_ename;
exit when m_myemp%notfound;

end loop;
r:=m_myemp%rowcount;
dbms_output.put_line('The number of employees are:- '||r);
close m_myemp;
End;

5. 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.

DECLARE
Mamidi Aishwarya. . Roll No:-160118733122

m_empno myemp.empno%type;
m_ename myemp.ename%type;
m_sal myemp.sal%type;
CURSOR m_myemp is
select empno,ename,sal from myemp;

begin
open m_myemp;
dbms_output.put_line('Empno sal');
loop
fetch m_myemp INTO m_empno,m_ename,m_sal;
exit when m_myemp%notfound;
if m_sal<50000 then
dbms_output.put_line(m_empno||' '|| m_sal);
end if;
end loop;
close m_myemp;
end;

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

DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
Mamidi Aishwarya. . Roll No:-160118733122

IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;

RETURN z;
END;
BEGIN
a:= 34;
b:= 9;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (34,9): ' || c);
END;

You might also like