Chaitanya Bharathi Institute of Technology (Autonomous) Department of Computer Science and Engineering Year-II Semester-IV
Chaitanya Bharathi Institute of Technology (Autonomous) Department of Computer Science and Engineering Year-II Semester-IV
Roll No:-160118733122
(Autonomous)
Year-II Semester-IV
RECORD
(Code- 18CSC15)
Submitted to :
Mrs.D.Naga Jyothi
Assistant Professor,Dept of CSE.
Submitted by :
B.E-2/4, CSE-3
LIST OF EXPERIMENTS
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
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
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
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.
20 How many clerks are there in the company? Which department exactly employs one clerk? 35
22 Display the number of employee for each job goup deptno wise. 36
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
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
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
38 For each department show its deptno and average salary. Sort the result in descending order of the 43
average salary.
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
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.
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.
CEIL
Syntax: - ceil(n)
CEIL returns smallest integer greater than or equal to n.
Mamidi Aishwarya. . Roll No:-160118733122
FLOOR
Syntax: - floor(n)
FLOOR returns largest integer equal to or less than n.
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.
MOD
POWER
----------
16
ROUND (number)
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
Example: -
select sign (23.587) from dual;
SIGN (23.587)
------------
1
TRUNC (number)
Mamidi Aishwarya. . Roll No:-160118733122
Example: -
• select trunc (23.587) from dual;
TRUNC (23.587)
-------------
23
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.
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
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.
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.
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.
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
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
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.
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 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
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.
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.
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 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
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
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.
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;
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;
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;
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.
Example:-
select *
from student
WHERE Attendence>=75
order by roll_no DESC;
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;
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:
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
JOB
---------
CLERK
SALESMAN
Mamidi Aishwarya. . Roll No:-160118733122
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
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
values(12,'Aish','manager',100000,30);
update aemp
set eno=10;
12. Write the sample queries using DCL commands – grant and revoke
GRANT:-
To grant privileges to a user account, the GRANT statement is used.
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.
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;
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
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;
Output:-
14. Write the sample queries to exercise all the joins – inner join, left outer join, right
outer join and full outer joins
select *
from students;
select *
from stud_record;
Mamidi Aishwarya. . Roll No:-160118733122
NATURAL JOIN
select *
from students natural join stud_record;
SELF JOIN:-
select e.ename,e.mgr,s.ename,s.empno
from myemp e,myemp s
where e.mgr=s.empno;
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:-
Output;:-
Query:-
Output:-
Mamidi Aishwarya. . Roll No:-160118733122
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);
20.
a.How many clerks are there in the company?
SELECT JOB,count(*)
from myemp
where job='CLERK'
group by job;
SELECT deptno,JOB,count(*)
from myemp
where job='CLERK'
GROUP BY job,deptno
HAVING count(*)=1;
22.Display the number of employee for each job group deptno wise.
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
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;
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.
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';
41. Find the minimum, maximum and average salary for each job title .
42. Show the details of the staff who are not working in the research department.
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
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.
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;
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;