Dbms Lab Workbook Mca
Dbms Lab Workbook Mca
SQL> commit;
table-name is the name of the table from which the information is retrieved.
column_list includes one or more columns from which data is retrieved.
The code within the brackets is optional.
3. List all employee names along with their salaries from emp table
SELECT ename, sal FROM emp;
Assignment:
1. Write an SQL statement to retrieve empno, comm. and hiredate from emp table.
Conditional Retrieval
Conditional retrieval enables selective rows to be selected. Although selecting rows, restriction can be applied
by a condition which governs the selection. F
urther clause called WHERE must be provided along with the SELECT statement to apply the condition to
select a specific set of rows. The order of prior first goes to the WHERE clause and the records that match the
condition are alone selected.
Syntax:
Select (column name(s)) FROM (table name(s)) WHERE condition(s)
The following table lists the comparison operators that you can use:
2. Use many different conditional operators in a WHERE clause. The following table lists other operators that
you can use:
ANY specifies that at least one of a set of where Population > any (select Population
values obtained from a subquery must from sql.countries)
satisfy a given condition
ALL specifies that all of the values obtained where Population > all (select Population from
from a subquery must satisfy a given sql.countries)
condition
CONTAINS tests for values that contain a specified where Continent contains 'America';
string
EXISTS tests for the existence of a set of values where exists (select * from sql.oilprod);
obtained from a subquery
IN tests for values that match one of a list where Name in ('Africa', 'Asia');
of values
LIKE tests for values that match a specified where Continent like 'A%';
pattern (table note 1)
All of these operators can be prefixed with the NOT operator to form a negative condition.
The IN operator enables to include values within a list that you supply.
The IS MISSING operator enables to identify rows that contain columns with missing values.
To select rows based on a range of values, you can use the BETWEEN-AND operators. Because the
BETWEEN-AND operators are inclusive, the values that you specify in the BETWEEN -AND expression are
included
The LIKE operator enables you to select rows based on pattern matching.
2. List the name and salary of the employees whose salary is more than 1000
SELECT ename, sal FROM emp WHERE sal > 1000;
6. List the details of the employees who have joined before the end of September 1981
SELECT * FROM emp WHERE hiredate <= ’30-SEP-1981’;
8. List the name of the employees whose employee numbers are 7369, 7521, 7839, 7934, 7788
SELECT ename FROM emp WHERE empno = 7369 OR empno = 7521 OR empno = 7839 OR empno = 7934
OR empno = 7788;
The Special Operators IN and BETWEEN can be used in place of complex relational or logical operators
SELECT ename FROM emp WHERE empno IN (7369, 7521, 7839, 7934, 7788);
9. List the employee details not belonging to the department 10, 30 and 40
SELECT * FROM emp WHERE deptno NOT IN (10, 30, 40);
10. List the employee name and salary, whose salary is between 1000 and 2000
SELECT ename, sal FROM emp WHERE sal BETWEEEN 1000 AND 2000;
11. List employee names who have joined before 30 th June 1981 and after December1981
SELECT ename FROM emp WHERE hiredate NOT BETWEEN ’30-JUN-1981’ AND ’31-DEC-1981’;
13. List the employee names who are not eligible for commission
SELECT ename FROM emp WHERE comm IS NULL;
14. List the name of the employee and job of the employee who does not report to anybody (managers is
NULL)
SELECT ename, job FROM emp WHERE mgr IS NULL;
17. List the details of employees whose salary is greater than 2000 and commission is null.
SELECT * FROM emp WHERE sal > 2000 AND comm IS NULL;
The LIKE operator is used only with CHAR and VARCHAR2 to match a pattern.
‘%’ represents a sequence of zero or more characters
‘_’ underscore stands for any single character
20. List the names of employees whose names have exactly 5 characters
SELECT ename FROM emp WHERE ename LIKE ‘ ’;
21. List the employee names having ‘I’ as the second character
SELECT ename FROM emp WHERE ename LIKE ‘_I’;
22. List the name, salary and PF amount of all the employees (PF is calculated as 10% of salary)
SELECT ename, sal, sal * .1 FROM emp;
or
SELECT ename, sal, sal * .1 as “PF” FROM emp;
23. List the names of employees who are more than 25 years old in the organization
SELECT ename FROM emp WHERE (SYSDATE – hiredate) > ( 25 * 365);
DUAL table is owned by the user ‘SYS’ and can be accessed by all users. It contains one DUMMY column and
one row with a value X. It is useful to return a value once only.
25. List the empno, ename, sal, hiredate in descending order of hiredate.
SELECT empno, ename, sal, hiredate FROM emp ORDER BY hiredate DESC;
26. List the employee name, Salary, job and department no. in ascending order of deptno and then on
descending order of salary
SELECT deptno, job, ename, sal FROM emp ORDER BY deptno, sal desc;
28. List the employee name, salary, PF, HRA, DA and gross; order the result in ascending order of gross. HRA
is 50% of salary and DA is 30% of salary
SELECT ename, sal, sal * .1 “PF”, sal * .5 “HRA”, sal * .3 “DA”, sal + (sal * .5) + (sal * .3) – (sal * .1) “GROSS”
FROM emp ORDER BY 6;
AGGREGATE FUNCTIONS
The aggregate functions produce a single value for an entire group or table
COUNT(*| [Distinct ] | ALL | column name ) - Determines the number of rows or non-NULL column
values. If * is passed, then the total number of rows is returned.
SUM([DISTINCT | ALL] column name) – Determines the sum of all selected columns
MAX(column name) – Returns the maximum value of the selected list of item.
MIN(column name) – Returns the minimum value of the selected list of item.
34. List the average salary and number of employees working in the department 20
SELECT AVG (sal), COUNT (*) FROM emp WHERE deptno = 20;
GROUP BY clause is used with SELECT to combine a group of rows based on the values of a particular
column or expression. Aggregate functions are used to return summary information for each group. The
aggregate functions are applied to the individual groups.
The WHERE clause is used to conditionally retrieve rows from a table, hence it cannot be applied to grouped
result.
The HAVING clause is used only with the expressions and/or columns that are specified with the GROUP BY
clause.
36. List the department number and the total salary payable in each department
SELECT deptno, SUM(sal) FROM emp GROUP BY deptno;
37. List the jobs and the number of employees in each job. The result should be in descending order of the
number of employees:
SELECT job, COUNT(*) FROM emp GROUP BY job ORDER BY job DESC;
38. List the total salary, maximum, minimum and the average salary of employees job wise
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp GROUP BY job;
39. List the average salary from each job excluding managers
SELECT job, AVG(sal) FROM emp WHERE job <> ‘MANAGER’ GROUP BY job;
SELECT job, AVG(sal) FROM emp WHERE job = ‘MANAGER’ ;
40. List the total salary, maximum, minimum and the average salary of employees job-wise, for department
number 20 only
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp WHERE deptno = 20 GROUP BY job;
Groups within groups GROUP BY clause can be used to provide results for groups within groups
41. List the average salary for each job type within department
SELECT deptno, job, AVG (sal) FROM emp GROUP BY deptno, job;
HAVING clause is used to specify which groups are to be displayed, i.e., restricts the groups that return on
the basis of aggregate functions
42. List average salary for all departments employing more than five people
SELECT deptno, AVG(sal) FROM emp GROUP BY deptno HAVING COUNT (*) > 5
43. List jobs of all the employees where maximum salary is >= 5000
SELECT job, MAX(sal) FROM emp GROUP BY job HAVNG MAX(SAL) >= 5000;
44. List the total salary, maximum, minimum and the average salary of employees jobwise, for department
number 20 only and display only those rows having average salary greater than 1000
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp WHERE deptno = 20 GROUP BY job HAVING
AVG(sal) > 1000;
45. For the above query, the output should be arranged in the ascending order of SUM(sal)
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp WHERE deptno = 20 GROUP BY job HAVING
AVG(sal) > 1000 ORDER BY SUM(sal);
SQL joins are used to combine rows from two or more tables.
The join clause is used to combine tables based on a common column and a join condition.
An equi join is a type of join that combines tables based on matching values in specified columns.
Please remember that:
The column names do not need to be the same.
The resultant table contains repeated columns.
It is possible to perform an equi join on more than two tables.
OR
SELECT *
FROM TableName1
JOIN TableName2
ON TableName1.ColumnName = TableName2.ColumnName;
3. To display King's employee number, name, department number, and departments location.
SELECT EMP.EMPNO, EMP.ENAME, EMP.DEPTNO,
DEPT.DEPTNO, DEPT.LOC
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO
AND INITCAP(ename) = 'King' ;
The most common type of join is: SQL INNER JOIN (simple join).
An SQL INNER JOIN returns all rows from multiple tables where the join condition is met.
1. List the employee numbers, names, department numbers and the department name
SELECT emp.empno, emp.ename, emp.deptno, dept.dname FROM emp, dept
WHERE emp.deptno = dept.deptno;
2. List the employee numbers, names, department numbers and the department name using table aliases
(effectively speeds up the query)
SELECT e.empno, e.ename, e.deptno, d.dname FROM emp e, dept d WHERE e.deptno = d.deptno;
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table
(table2). The result is NULL in the right side when there is no match.
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns.
Syntax
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
or:
SELECT column_name(s) FROM table1LEFT OUTER JOIN table2 ON table1.column_name =
table2.column_name;
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left
table (table1). The result is NULL in the left side when there is no match.
Note: The RIGHT JOIN keyword returns all the rows from the right table, even if there are no matches in the
left table.
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
Syntax
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Note: The FULL OUTER JOIN keyword returns all the rows from the left table and all the rows from the right
table. If there are rows in table1 that do not have matches in table2, or if there are rows in table2 that do not
have matches in table1 those rows will be listed as well.
CARTESIAN JOINS
When no join condition clause is specified in WHERE clause, each row of one table matches every row of
another table. This results in a Cartesian Product.
SELF JOIN
To join a table to itself means that each row of the table is combined with itself and with every other row of
the table. It can be viewed as a join of two copies of the same table.
7. List all the employees who joined the company before their manager
SELECT e.ename, e.hiredate, m. ename manager, m.hiredate FROM emp e, emp m
WHERE e.mgr = m.empno and e.hiredate < m.hiredate;
SET OPERATORS
10. Display empno, ename from emp where deptno is 10 and 30 in ascending order of empno
SELECT empno, ename FROM emp WHERE deptno = 10
UNION
SELECT empno, ename FROM emp WHERE deptno = 30
ORDER BY 1;
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the ALL
keyword with UNION.
Or we can copy only the columns we want into the new table:
The new table will be created with the column-names and types as defined in the SELECT statement. You can
apply new names using the AS clause.
INTERSECT Operator
Returns the rows that are common between two sets of rows
Syntax
SELECT column_name(s) FROM table1
INTERSECT
SELECT column_name(s) FROM table2;
MINUS Operator
Returns the rows unique to first query
Syntax
SELECT column_name(s) FROM table1
MINUS
SELECT column_name(s) FROM table2;
OR
A Subquery or Inner query or Nested query is a query within another SQL query and embedded within the
WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the
data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main
query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The
GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN
operator.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or
NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used
within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows:
15. List all employee details of an employee whose salary is greater than the average salary of employees
whose hiredate is before ’01-APR-1981’
SELECT * FROM emp WHERE
sal > (SELECT AVG(sal) FROM emp WHERE hiredate < ‘01-APR-1981’’);
18. List the names of the employees who earn lowest salary in each department
SELECT ename, deptno FROM emp
WHERE sal IN (SELECT MIN(sal) FROM emp GROUP BY deptno);
A correlated subquery is a SQL query that depends on values executed by an outer query in order to
complete.
Because a correlated subquery requires the outer query to be executed first, the correlated subquery must
run once for every row in the outer query. This causes correlated subqueries to be less efficient than other
subqueries.
A correlated subquery is a nested subquery which is executed once for each ‘candidate row’ considered by the
main query and which on execution uses a value from a column in the outer query.
In a correlated subquery, the column value used in inner sub query refers to the column value represent in
the outer query forming a correlated subquery. The subquery is executed repeatedly, once for each row of the
main (outer) query table.
19. List employee details who earn salary greater than the average salary
SELECT empno, ename, sal, deptno FROM emp e
WHERE sal > (SELECT AVG(sal) FROM emp);
20. List all employees who have atleast one person reporting to them
SELECT empno, ename, job, deptno FROM emp e
WHERE EXISTS (SELECT empno FROM emp WHERE emp.mgr = e.empno);
21. List the employee details iff more than 2 employees are present in deptno 10
SELECT * FROM emp WHERE deptno = 10 AND EXISTS
(SELECT COUNT(*) FROM emp WHERE deptno = 10 GROUP BY deptno HAVING COUNT(*) > 2);
22. List all the employee details who do not manage any one
SELECT ename, job FROM emp e WHERE NOT EXISTS
(SELECT mgr FROM emp WHERE mgr = e.empno);
2. ANY operator - This compares the lowest value from the set. Used along with the relational operators.
23. List the employee names whose salary is greater than the lowest salary of an employee belonging to
deptno 20
SELECT ename FROM emp WHERE sal > ANY (SELECT sal FROM emp WHERE deptno = 20);
24. List the employee details of those employees whose salary is greater than any of the managers
SELECT empno, ename, sal FROM emp WHERE sal > ANY
(SELECT sal FROM emp WHERE job = ‘MANAGER’);
25. List the employee names whose salary is greater than the highest salary of all employee belonging to dept
20
SELECT ename FROM emp WHERE sal > ALL (SELECT sal FROM emp WHERE deptno = 20);
26. List the employee details of those employees whose salary is more than the highest paid manager
SELECT empno, ename, sal FROM emp
WHERE sal > ALL(SELECT sal FROM emp WHERE job = ‘MANAGER’);
Hands on Session
1. List all employees, their job and deptno, who are having same job as that of any employee of deptno 20
2. Using self join, list all the employees who have joined before their manager
3. List all employees who earn less than the average salary of all the employees
4. List all employees name along with their manager’s name.
5. Also list the name of employee who has no manager
6. Display the dept that has no employee
7. List the employee details who earn minimum salary for their job
8. List the ename, sal, deptno for those employees who earn sal greater than the avg sal of their dept. Sort
the output in deptno order
9. List the employee details who earn highest salary for their job
10. List the details of those employees who are among the five highest earners of the company
Creating Tables
Tables are created using the CREATE TABLE command. Tables are owned by the user who creates them. The
names of tables owned by a given user must be unique. The column names in the table must be unique.
Column names can be duplicated across tables.
Tables can be created at any time. Table structure can also be modified. Specifying table name is compulsory
while creating a table.
The column_name parameters specify the names of the columns of the table.
The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer, decimal, date,
etc.).
The size parameter specifies the maximum length of the column of the table.
Or
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns.
If we require to declare the combination of ITNO and NAME as Primary Key, then this can be defined as:
CREATE TABLE itemmast5(
ITNO NUMBER(4), NAME VARCHAR2(20), QOH NUMBER(5), CLASS CHAR(1), UOM CHAR(4), ROL
NUMBER(5) NOT NULL, ROQ NUMBER(5) NOT NULL, RATE NUMBER(8,2) NOT NULL,
PRIMARY KEY(ITNO, NAME));
CHECK Constraint: Specific condition is specified, which must evaluate to true for constraint to be satisfied.
SQL DEFAULT Constraint is used to insert a default value into a column. The default value will be added to
all new records, if no other value is specified.
Using this option whenever a parent row is deleted then all the corresponding child rows are deleted from the
child table. This option is always used with the foreign key.
Syntax is:
CREATE TABLE tablename [ (column name, ……, ….) ] AS SELECT statement;
The table will be created with the specified columns and the rows retrieved by the SELECT statement
inserted into it.
If all the columns in the SELECT statement have well-defined names, the column specifications may be
omitted
1. Create a table EMP2 from EMP table having employee number, name, job, manager, salary of employees
from department 10 and 20.
CREATE TABLE emp2 AS
SELECT empno, ename, job, mgr, sal FROM emp WHERE deptno IN (10, 20);
2. Create a table SALARY from EMP table having ename and salary
CREATE TABLE salary (Name, Salary) AS SELECT ename, sal FROM emp;
Syntax;
INSERT INTO table_name VALUES(<list-of-values>);
Syntax:
UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... [WHERE condition]
table_name - the table name which has to be updated.
column_name1, column_name2.. - the columns that gets changed.
value1, value2... - are the new values.
NOTE: In the Update statement, WHERE clause identifies the rows that get affected. If you do not include the
WHERE clause, column values for all the rows get affected.
3. All employees who have more than 2 people reporting to them, are to directly report to the PRESIDENT
UPDATE emp SET mgr = 7839 WHERE mgr <> 7839 AND empno IN (SELECT mgr FROM emp GROUP BY mgr
HAVING COUNT (*) > 2);
Syntax:
DELETE FROM <tablename> [WHERE <condition>]
Dropping Columns
ALTER TABLE command removes the column from the table description and removes the column length and
data from each row of the table.
If there are any unused columns in the table i.e., without data can also be removed using
ALTER TABLE <tablename> DROP UNUSED COLUMNS;
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:
Eg. ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the
following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD column_name datatype;
To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):
ALTER TABLE table_name DROP COLUMN column_name;
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name MODIFY column_name datatype;
The SQL ALTER TABLE command is used to modify the definition (structure) of a table by modifying the
definition of its columns. The ALTER command is used to perform the following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
Eg: To add a column "experience" to the employee table, the query would be like
ALTER TABLE employee ADD experience number(3);
Eg: To drop the column "location" from the employee table, the query would be like
ALTER TABLE employee DROP location;
Eg. To modify the column salary in the employee table, the query would be like
ALTER TABLE employee MODIFY salary number(15,2);
Add a column to the existing table emp, which will hold the grades for each employee
ALTER TABLE emp ADD grade CHAR(2);
Modify the emp table, add constraint REFERENCES to deptno of table emp referring deptno of table dept
ALTER TABLE emp ADD CONSTRAINT pk_c FOREIGN KEY (deptno) REFERENCES dept(deptno);
Modify the emp table, add constraint CHECK for sal of table emp where sal should be greater than 2500
ALTER TABLE emp ADD CONSTRAINT chk_sal CHECK (sal > 2500);
Modify the sal column of the emp table to NOT NULL and increases its size to 10
ALTER TABLE emp MODIFY sal NUMBER(10,2) NOT NULL;
To drop constraints:
ALTER TABLE <tablename> DROP <constraints>;
Syntax
RENAME old_table_name To new_table_name;
Eg: To change the name of the table employee to my_employee, the query would be like
RENAME employee TO my_employee;
1. "Find the names of sailors who have reserved boat number 103"
2. "Find the names of sailors who have never reserved boat number 103"
3. "Find the names of sailors who have reserved a red boat"
4. "Find the colors of boats reserved by Lubber"
5. "Find the names of sailors who have reserved at least one boat"
6. "Find the names of sailors who have reserved a red or a green boat"
7. "Find the names of sailors who have reserved both a red and a green boat"
8. "Find the names of sailors who have reserved a red but not a green boat"
9. "Find the names of sailors who have reserved at least two different boats"
10. "Find the names of sailors who have reserved at least n boats"
11. “Find the sids of sailors with age over 20 who have not reserved a red boat"
12. "Find the names of sailors who have reserved all boats"
13. "Find the names of sailors who have reserved all boats called Interlake"
14. “Find all sailors with a rating above 7"
15. "Find the names and ages of sailors with a rating above 7"
16. "Find the sailor name boat id and reservation date for each reservation"
17. "Find sailors who have reserved all red boats"
18. "Find the names and ages of all sailors"
19. "Find the sids of sailors who have reserved a red boat"
20. "Compute increments for the ratings of persons who have sailed two different boats on the same day"
21. “Find the ages of sailors whose name begins and ends with B and has at least three characters”
22. “Find the sids of all sailors who have reserved red boats but not green boats”
23. "Find all sids of sailors who have a rating of 10 or have reserved boat 104"
24. "Find the names of sailors who have not reserved a red boat"
25. "Find sailors whose rating is better than some sailor called Horatio"
26. "Find sailors whose rating is better than every sailor called Horatio"
27. "Find the sailors with the highest rating"
28. "Find the average of all sailors"
29. "Find the average age of sailors with a rating of 10"
30. "Find the name and age of the oldest sailor"
31. "Count the number of sailors"
32. "Count the number of different sailor names"
33. "Find the names of sailors who are older than the oldest sailor with a rating of 10"
34. "Find the age of the youngest sailor for each rating level"
35. "Find the age of the youngest sailor who is eligible to vote(i.e., is at least 18 years old) for each rating level
with at least two such sailors"
36. "For each red boat, find the number of reservations for this boat"
37. "Find the average age of sailors for each rating level that has at least two sailors"
38. "Find the average age of sailors who are of voting age(i.e., at least 18 years old) for each rating level that
has at least two sailors"
39. "Find the average age of sailors who are of voting age(i.e., at least 18 years old) for each rating level that
has at least two such sailors"
40. "Find those ratings for which the average age of sailors in the minimum overall ratings"
41. "Find the sailor ids with top 5 rating ranks."
3. List the name, salary, and comm. For those employees whose net pay is greater than or equal to any other
employee salary of the company.
A) select e.ename, e.sal, e.comm
from emp e
where nvl2(e.comm.,e.sal+e.comm,e.sal) >= any (select sal from emp);
(OR)
B) select ename,sal,comm. from emp
where sal+nvl(comm,0) >= any (select sal from emp);/
4. List the Name , Salary, Comm and Net Pay is more than any other employee.
Select e.ename, e.sal, e.comm, nvl2(comm, sal+comm, sal) NETPAY
from emp e
where nvl2(comm, sal+comm, sal) > any (select sal from emp where empno = e.empno) ;
5. List the Deptno, Name, Job, Salary and Sal+Comm of the SALESMAN who are earning maximum salary
and commission in descending order.
Select deptno, name, job, sal, sal+nvl(comm,0) from emp
where job = ‘SALESMAN’
and sal in
(select max(sal+nvl(comm, 0)) from emp where comm is not null)
Order by (sal +nvl(comm.,0)) desc;
6. List the Deptno, Name, Job, Salary and Sal+Comm of the emps who earn the second highest earnings (sal
+ comm.).
Select deptno, ename, sal, job, sal+nvl(comm,0)
7. List the Emps whose Sal is > the total remuneration of the SALESMAN.
select * from emp
where sal > (select sum(nvl2(comm, sal+comm, sal)) from emp where job = ‘SALESMAN’);
The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen.
Views do not contain data of their own. They are used to restrict access to the database or to hide data
complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSER T,
UPDATE, DELETE affects the data in the original table upon which the view is based.
Syntax
CREATE VIEW view_name AS
SELECT column_name(s) FROM table_name WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.
Functions
Functions are used to manipulate data items.
Advantages:
Can be used to perform complex calculations on data
Can modify individual data items
Can very easily manipulate output for group of rows
Can alter date formats for display
Arithmetic Functions
1. ABS(n) – This function returns absolute value of the column or value passed
Sql> SELECT ABS(-65) FROM dual;
3. FLOOR(n) – This function finds the largest integer less than or equal to the value of n. n can be either
column or expression.
SELECT FLOOR(sal), CEIL(88.9) FROM emp WHERE sal BETWEEN 3000 AND 5000;
5. POWER(m, n) – This function returns m raised to the power of n. The second argument n must be an
integer.
SELECT sal, POWER(sal, 2) FROM emp WHERE deptno = 10;
7. SQRT(n) – This function returns the square root of n. If value n is NULL or negative, then NULL is returned.
SELECT sal, SQRT(sal) FROM emp WHERE deptno=10;
8. TRUNC(m, [n]) – This function truncates the m or column to n decimal places, If n is omitted then it is
truncated to no decimal places. If n is negative then numbers left of decimal places are truncated to 0.
SELECT TRUNC(90.723, 1), TRUNC(90.723, -1), TRUNC(90.723) FROM dual;
ASCII(str) - Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty
string. Returns NULL if str is NULL. ASCII() works for characters with numeric values from 0 to 255.
SQL>SELECT ASCII('2') FROM DUAL;
INSTR(str,substr) Returns the position of the first occurrence of substring substr in string str.
SQL>SELECT INSTR('foobarbar', 'bar') FROM DUAL;
LENGTH(str) Returns the length of the string str, measured in bytes. A multi-byte character counts as
multiple bytes. This means that for a string containing five two-byte characters, LENGTH() returns 10,
whereas CHAR_LENGTH() returns 5.
LPAD(str,len,padstr) Returns the string str, left-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
SQL> SELECT LPAD('hi',4,'??') FROM DUAL;
LTRIM(str) Returns the string str with leading space characters removed.
SQL> SELECT LTRIM(' barbar') FROM DUAL;
REPLACE(str,from_str,to_str) Returns the string str with all occurrences of the string from_str replaced by
the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.
SQL> SELECT REPLACE('www.whatawalk.com', 'w', 'Ww') FROM DUAL;
REVERSE(str) Returns the string str with the order of the characters reversed.
SQL> SELECT REVERSE('abcd') FROM DUAL;
RPAD(str,len,padstr) Returns the string str, right-padded with the string padstr to a length of len
characters. If str is longer than len, the return value is shortened to len characters.
SQL> SELECT RPAD('hi',5,'?') FROM DUAL;
RTRIM(str) Returns the string str with trailing space characters removed.
SQL> SELECT RTRIM('barbar ') FROM DUAL;
TRIM(str) Returns the string str with all rem str prefixes or suffixes removed. If none of the specifiers BOTH,
LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if not specified, spaces are
removed.
SQL> SELECT TRIM(' bar ‘) FROM DUAL;
UPPER(str) Returns the string str with all characters changed to uppercase according to the current
character set mapping.
SQL> SELECT UPPER(‘Rupa Devi Singh') FROM DUAL;
DATE Functions
SYSDATE is a pseudo-column that returns the current date and time of type DATE.
SQL>SELECT SYSDATE FROM dual;
ADD_MONTHS(d, n)- Adds or subtracts months to or from a date. Returns a date as a result
SQL>SELECT hiredate, ADD_MONTHS(hiredate, 4), ADD_MONTHS(hiredate, -4) FROM emprd WHERE
deptno=10;
ROUND(d [,format]) - This function rounds the date d to the unit specified by format. If format is not specified,
it defaults to ‘DD’, which rounds to the nearest day
SQL>SELECT ROUND(TO_DATE(’12-APR-91’),’MM’) “Nearest Month” FROM dual;
TRUNC(d [,format]) - This function returns the date d truncated to the unit specified by format. If format is
omitted, it defaults to ‘DD’, which truncates d to the nearest day
SQL>SELECT TRUNC(TO_DATE(’12-APR-91 13:21:00’,’DD-MON-YY HH24:MI:SS’, ‘Year’) “First Day” FROM
dual;
MONTHS_BETWEEN(d1,d2) - This function returns the number of months between two dates, d1 and d2. If
d1 is later than d2, the result is positive else negative. The output will be a number.
SQL>SELECT MONTHS_BETWEEN(’05-JUN-98’, ’05-DEC-99’), MONTHS_BETWEEN(’05-DEC-99’, ’05-JUN-
98’), MONTHS_BETWEEN(’05-JUN-98’,’05-JUN-98’) FROM dual;
NEXT_DAY(date, day) -This function returns the date of next specified day of the week after the ‘date’.
SQL>SELECT SYSDATE, NEXT_DAY(SYSDATE, Wednesday) FROM dual;
TO_DATE(char, f) - This function converts the character string representing date into a date format according
to ‘f’ format specified. If no format is specified the default format is ‘DD-MON-YY’.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL language code can be stored in
the client system (client-side) or in the database (server-side).
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.
SQL commands are grouped into four major categories depending on their functionality. They are as follows:
These SQL commands are used for creating, modifying, and dropping the structure of database objects. The
commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
These SQL commands are used for storing, retrieving, modifying, and deleting data. These commands are
SELECT, INSERT, UPDATE, and DELETE.
These SQL commands are used for managing changes affecting the data. These commands are COMMIT,
ROLLBACK, and SAVEPOINT.
These SQL commands are used for providing security to database objects. These commands are GRANT and
REVOKE.
Advantages of PL/SQL
Program 6: To show the usage of Local and Global variables in its simple form
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
IF (a < b) then
dbms_output.put_line('Line 2 - a is less than b');
ELSE
dbms_output.put_line('Line 2 - a is not less than b');
END IF;
IF ( b >= a ) THEN
dbms_output.put_line('Line 5 - b is either equal or greater than a');
END IF;
IF ( a <> b ) THEN
dbms_output.put_line('Line 6 - a is not equal to b');
ELSE
dbms_output.put_line('Line 6 - a is equal to b');
END IF;
END;
/
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either equal or less than b
Line 5 - b is either equal or greater than a
Line 6 - a is not equal to b
BEGIN
compare('Zara Ali', 'Z%A_i');
compare('Nuha Ali', 'Z% A_i');
END;
/
True
False
e := ((a + b) * c) / d; -- (30 * 15 ) / 5
dbms_output.put_line('Value of ((a + b) * c) / d is : ' || e );
e := a + (b * c) / d; -- 20 + (150/5)
dbms_output.put_line('Value of a + (b * c) / d is : ' || e );
END;
/
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
a is less than 20
value of a is : 10
Prog 19:
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then dbms_output.put_line('Excellent');
when grade = 'B' then dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
end case;
END;
/
Very good
Program 30: Write a PL/SQL code to update salary of employee number 7788 to 5000 if salary is less than OR
EQUAL TO 3000
DECLARE
x NUMBER(7,2);
BEGIN
SELECT sal INTO x FROM emp WHERE empno = 7788;
IF x <= 3000 THEN
UPDATE emp SET sal = 5000 WHERE empno = 7788;
END IF;
END;
/
Program 31: Update the commission of the empno 7369 to Rs. 300; if it is null; else raise his commission by
25%
DECLARE
var_empno NUMBER(4) := 7369;
var_comm emp.comm% TYPE;
BEGIN
SELECT comm INTO var_comm FROM emp
WHERE empno = var_empno;
A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor
contains information on a select statement and the rows of data accessed by it.
This temporary work area is used to store the data retrieved from the database, and manipulate this data. A
cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds
is called the active set.
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit
statements are created to process these statements.
Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The
cursor attributes available are %FOUND, % NOTFOUND, % ROWCOUNT, and %ISOPEN.
For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us
whether any rows are affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to
find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no
data is selected.
Program 32: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:
Explicit Cursors
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row. We can provide a suitable name for the cursor.
General Syntax for creating a cursor is as given below:
CURSOR cursor_name IS select_statement;
In the above example we are creating a cursor ‘emp_cur’ on a query which returns the records of all the
employees with salary greater than 5000. Here ‘emp_tbl’ in the table which contains records of all the
employees.
When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the
record or variables and the logical pointer moves to the next row and it becomes the current row. On every
fetch statement, the pointer moves to the next row. If you want to fetch after the last row, the program will
throw an error. When there is more than one row in a cursor we can use loops along with explicit cursor
attributes to fetch all the records.
· We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.
· If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor.
· If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch
statement as the columns are present in the cursor.
Triggers could be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Triggers can be written for the following purposes:
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
Creating Triggers
The syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with the
trigger_name.
{BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF
clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML
statements, like INSERT, UPDATE, and DELETE.
[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being
affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called
a table level trigger.
WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid
only for row level triggers.
The following program creates a row level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON emprd
FOR EACH ROW WHEN (NEW.empno > 0)
DECLARE
sal_diff number;
BEGIN
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.
Here following two points are important and should be noted carefully:
OLD and NEW references are not available for table level triggers, rather you can use them for record level
triggers.
If you want to query the table in the same trigger, then you should use the AFTER keyword, because
triggers can query the table or change it again only after the initial changes are applied and the table is
back in a consistent state.
Above trigger has been written in such a way that it will fire before any DELETE or INSERT or UP DATE
operation on the table, but you can write your trigger on a single or multiple operations, for example
BEFORE DELETE, which will fire whenever a record will be deleted using DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the emprd table. Here is one INSERT statement, which will create a
new record in the table:
INSERT INTO emprd VALUES (7999,’RUPA’,’ANALYST’,7839,’23-OCT-85’,4500,100,10);
When a record is created in EMPRD table, above create trigger display_salary_changes will be fired and it will
display the following result:
Old salary:
New salary: 4500
Salary difference:
1 row created.