DBMS_Lab_Manual
DBMS_Lab_Manual
1. Objective (s):
INTRODUCTION TO DIFFERENT DATABASES SOFTWARE
AND INSTALLATION OF VARIOUS DATABASES.
2. Theory:
1. Oracle Database:
Installation Steps:
2. MySQL:
Installation Steps:
1. Download MySQL:
Visit the official MySQL website (https://dev.mysql.com/downloads/).
Choose the MySQL Community Server edition.
Download the appropriate installer for your operating system.
2. Install MySQL:
Run the installer and follow the installation wizard.
Choose setup type, configure server options, and set the root password.
Complete the installation process.
3. Configuration:
Optionally, configure MySQL as a Windows service or start it
manually.
Use MySQL Workbench or the command-line client to connect to the
server and perform initial configurations.
4. Post-Installation Tasks:
Verify the installation by executing basic SQL commands.
Secure MySQL by setting up user accounts, permissions, and
removing default accounts.
3. SQL Server:
Installation Steps:
4. Post-Installation Tasks:
Verify the installation by connecting to the SQL Server using SQL
Server Management Studio (SSMS).
Create databases, tables, and perform basic queries to test
functionality.
3. Software used:
Oracle Database (Recommended) or
MySQL
4. Solution: Installed Oracle 11g XE
5. Some Sample questions:
1. What is the primary purpose of a database management system
(DBMS)?
2. Can you name two examples of relational database management systems
(RDBMS) and briefly describe their characteristics?
3. What is the key difference between SQL and NoSQL databases?
4. What steps are typically involved in the installation of database software
on a computer?
5. Why is it important to consider the hardware and software requirements
before installing a database management system?
1. Objective (s):
APPLY SQL SELECT STATEMENTS ON “EMPLOYEES” TABLE.
1. Select the content of the columns named "LastName" and "FirstName" from
the”Employees” table.
2. Create a query to display all the contents of table "Employees".
3. Select only the different (distinct) values of manager_id in a table.
4. Display the firstname concatenated with Lastname from table “Employees” with
column name NAME.
5. Select only the employee with the first name equal to "Steven" AND the last
name equal to "King":
6. Select only the employee with the first name equal to " David" OR the first
name equal to " Nancy":
7. Select only the employee with the first name equal to "David" AND the last
name equal to "Austin" OR to "Lee":
8. Select the complete information about employee whose manager id is 103.
9. Display information about employee whose salary is more than 12000.
10. Display information about employee whose salary is less than 10000.
11. Display information about employee whose salary is in between 10000 and
30000.
12. Display information about employee with first_name in lower case.
13. Display information about employee with last_name in upper case.
14. Select the complete information about employee whose manager id is 100 and
department_id is 90
15. Display the employee id, last_name, email, hire date ,salary. Order the query in
ascending order by Salary.
16. Display the employee id,first_name, email, hire date ,salary,manager id. Order
the query in descending order by manager id.
17. Create a query to display all the contents of table "Employees" hire date
between '13-jan 93' and '17-aug-94'.
18.Create a query to display hire date, first_name, email,job_id hire date between
21-SEP-89 and 05 FEB-98. Order the query in descending order by hire date
from employees table.
2. Theory:
SQL Basics: The structure queries language is a language that enable to create and
operate on relational database, which are sets of related information stored in tables.
SQL has clearly established itself as the standard relational database language.
4. VIEW DEFINITION:
The SQL DDL also includes commands for defining views
5. AUTHORIZATION:
The SQL DDL includes command for specifying access rights to relation and views.
6. INTEGRITY:
The SQL provides forms of integrity checking. Future products and standard of SQL are
likely to include enhanced features for integrity checking.
2. WHERE CLAUSE:
select loan-number from loan
where amount between 8000 and 9000
it will select all loan-number from loan where amount is between the 8000 and 9000
3. FROM CLAUSE:
select customer-name,borrower.loan-number,amount from borrower, loan
where borrower.loan-no=loan.loan-no
RETRIEVING DATA:
3. Software used:
1. Oracle Database (Recommended) or
2. MySQL
4. Solution:
1. select last_name, first_name from Employees
2. Select *
from Employees
8. Select *
from employees
where manager_id=103
1. Explain the purpose of the SQL SELECT statement. How does it retrieve
data from a table?
2. What is the significance of the WHERE clause in a SELECT statement?
3. How is the ORDER BY clause used in a SELECT statement?
4. Explain the difference between the WHERE and HAVING clauses in
SQL.
5. How can you limit the number of rows returned in a SELECT statement?
1. Objective (s):
APPLY FOLLOWING COMPOUND CONDITION AND USE RELATIONAL OPERATORS (IN,
BETWEEN, LIKE, NULL, NOT NULL ETC) IN SQL STATEMENTS ON “EMPLOYEES” AND
“DEPARTMENT” TABLE.
1. Display the last name and salary for any employee whose salary is not in the range of 5,000 to
1,000?
2. Display the last name and department number of all employees in departments 60 or 100 in
ascending alphabetical order by name.
3. To display the last name and salary of employees who earn between 5,000 and 12,000 and are in
department 60 or 90. Label the columns Employee and Monthly Salary.
4. Create a report to display the last name, salary, and commission of all employees who
earn commissions. Sort data in descending order of salary and commissions.
5. Display the last name, job id, and salary for all employees whose job is IT-programmer or finance
manager and whose salary is not equal to 2,500, 3,500, or 7,000.
6. Display the last name, salary, and commission for all employees whose commission amount is
20%.
7. Display the employee number, last name, salary, and salary increased by 15.5% (expressed as a
whole number) for each employee. Label the column New Salary.
8. Modify above query to add a column that subtracts the old salary from the new salary. Label the
column Increase.
9. Create a query that produces the following for each employee: employee last name and
salary is 3 times. Label the column Dream Salaries.
10. Display the last name and manager id of those employees whose manager id is not 103.
11. Create a query to display the contents of those employees whose manager id is in the range of 100
and 103.
CS3CO39: Database Management System Laboratory Experiment no- 3
Experiment Title: Apply Following Compound condition and Page 2 of 10
use relational operators (IN, BETWEEN, LIKE, NULL, NOT
NULL etc) in SQL statements on “Employees” and “Department”
table.
12. Create a query to display the contents of those employees whose commission pct
is null.
13. Create a query to display the contents of those employees whose manager
id is not null fromdepartment table.
14. Create a query to see a listing of all rows for which manager _id is not 200.
Aggregate functions
17. How many different job id are stored in the relation employees.
18. How many tuples are stored in the relation employees? Also find the no. of
records in manager_idattribute.
19. Display the content of the employee from employees table whose first name end
with letter n.
20. Display the content of the employee from employees table whose first name start
with letter A.
21. Display the content of the employee from employees table whose first name
start with A end withletter r.
22. Display the content of the employee from employees table whose first name
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
2
CS3CO39: Database Management System Laboratory Experiment no- 3
Experiment Title: Apply Following Compound condition and Page 3 of 10
use relational operators (IN, BETWEEN, LIKE, NULL, NOT
NULL etc) in SQL statements on “Employees” and “Department”
table.
23. Display the content of the employee from employees table whose first name has
substring ‘ar’.
24. Display the content of the employee from employees table whose first name end
with letter ‘ara’.
25. Display the content of the employee from department table whose first name
has substring ‘tr’and manager id is either 200 or 1700.
27. Display the last name, first name, manager id and email of those employees
whose email containsexactly one character appears between E and S.
28. Display all employee last names in which the third letter of the name is a.
29. Display the last name of all employees who have both an a and an e in their last
name.
30. Write a query that displays the last name (with the first letter uppercase and all
otherletters lowercase) and the length of the last name for all employees whose
name starts with the letters J, A, or M.. Sort the results by the employees’ last
names.
2. Theory:
2.1 SPECIAL OPERATORS
In / not in – used to select a equi from a specific set of values
Any - used to compare with a specific set of values
Between / not between – used to find between the ranges
Like / not like – used to do the pattern matching
2.5 Using IN Function SQL> select * from Gaurav where marks in(729,760,782);
2.6 USING LIKE OPERATOR
1). percent:
COUNT FUNCTION
In order to count the number of rows, count function is used.
1. count(*) – It counts all, inclusive of duplicates and nulls.
Example: select count(*) from student;
2. count(col_name)– It avoids null value.
Example: select count(total) from order;
3. count (distinct col_name) – It avoids the repeated and null values.
Example: select count (distinct ordid) from order.
3. Software used:
1. Oracle Database (Recommended) or
2. MySQL
4. Solution:
String matching
1. select * from employees where first_name like'%n'
2. select * from employees where first_name like'A%'
3. select * from employees where first_name like'A%r'
4. select * from employees where first_name like'A_ '
5. select * from employees where first_name like'%ar%'
6. select * from employees where first_name like'%ara'
11. If you want to see a listing of all rows for which manager _id is not 200, the
query would look like:
12. select * from departments where not(manager_id=200)
aggregate functions
13. select count(manager_id) from employees
18. select
employee_id,length(last_name),manager_id,department_id,initcap(first_name),hire_dat
e from employees
20. To display the last name and salary for any employee whose salary is not in the
range of 5,000 to 1,000
select last_name,salary from employees
where salary not between 5000 and 10000
21. Display the last name and department number of all employees in departments
60 or 100 in ascending alphabetical order by name.
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
6
CS3CO39: Database Management System Laboratory Experiment no- 3
Experiment Title: Apply Following Compound condition and Page 7 of 10
use relational operators (IN, BETWEEN, LIKE, NULL, NOT
NULL etc) in SQL statements on “Employees” and “Department”
table.
22. To display the last name and salary of employees who earn between 5,000 and
12,000 and are in department 60 or 90. Label the columns Employee and Monthly
Salary
23. The employee department needs a report that displays the last name and hire
date for all employees who were hired in 1994.
24. Create a report to display the last name, salary, and commission of all
employees who earn commissions. Sort data in descending order of salary and
commissions.
25. Display all employee last names in which the third letter of the name is a.
26. Display the last name of all employees who have both an a and an e in their last
name. select last_name
from employees
where last_name like '%a%e%'
27. Display the last name, job id, and salary for all employees whose job is IT-
programmer or finance manager and whose salary is not equal to 2,500, 3,500, or 7,000.
28. display the last name, salary, and commission for all employees whose
commission amount is 20%.
29. display the employee number, last name, salary, and salary increased by 15.5%
(expressed as a whole number) for each employee. Label the column New Salary.
30. Modify above query to add a column that subtracts the old salary from the new
salary. Label the column Increase.
31. Write a query that displays the last name (with the first letter uppercase and all
other letters lowercase) and the length of the last name for all employees whose name
starts with the letters J, A, or M.. Sort the results by the employees’ last names.
34. Create a query that produces the following for each employee: employee last
name and salary is 3 times. Label the column Dream Salaries.
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
8
CS3CO39: Database Management System Laboratory Experiment no- 3
Experiment Title: Apply Following Compound condition and Page 9 of 10
use relational operators (IN, BETWEEN, LIKE, NULL, NOT
NULL etc) in SQL statements on “Employees” and “Department”
table.
Aggregate functions
SELECT sum(salary)
FROM employees where department_id=60;
37. how many different job id are stored in the relation employees.
38. How many tuples are stored in the relation employees. Also find the no. of
records in manager_id attribute.
39. display the last name and manager id of those employees whose manager id is
not 103. SELECT employee_id,last_name,manager_id
FROM employees
where not(manager_id=100)
1. Objective (s):
CREATING NEW TABLES, ADDING DATA, UPDATING DATA, ALTERING
TABLES, DELETING DATA.
2. Theory:
2.1 3.1 CREATING NEW TABLES
DDL COMMAND
It is used to communicate with database. DDL is used to: o Create an object o Alter the
structure of an object o To drop the object created.
The commands used are: Create, Alter, Drop, Truncate
SQL Commands:
CREATE TABLE
It is used to create a table
Syntax: Create table tablename (column_name1 data_ type constraints, column_name2
data_ type constraints …)
Example: Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10)
constraint un unique, DeptNo number(3) CONSTRAINT FKey2 REFERENCES
DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob date not
null);
Rules: 1. Oracle reserved words cannot be used.
3. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. 2 different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include “not null” condition when needed. By default it is „null‟.
DML COMMAND
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are Insert, Select,
Update, Delete
Insert Command: This is used to add one or more rows to a table. The values are
separated by commas and the data types char and date are enclosed in apostrophes. The
values must be entered in the same order as they are defined.
Update Command: It is used to alter the column values in a table. A single column may
be updated or more than one column could be updated.
Delete command: After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where clause.
DROP TABLE
It will delete the table structure provided the table should be empty.
TRUNCATE TABLE If there is no further use of records stored in a table and the
structure has to be retained then the records alone can be deleted.
Syntax: TRUNCATE TABLE <TABLE NAME>;
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into
the table. It has enforcing the rules for the columns in a table. The types of the integrity
constraints are: a)
Domain Integrity b) Entity Integrity c) Referential Integrity
a) Domain Integrity This constraint sets a range and any violations that take place
will prevent the user from performing the manipulation that caused the breach. It
includes:
Not Null constraint: While creating tables, by default the rows can have null value .the
enforcement of not null constraint in a table ensure that the table contains values.
Principle of null values: o Setting null value is appropriate when the actual value is
unknown, or when a value would not be meaningful. o A null value is not equivalent to
a value of zero. o A null value will always evaluate to null in any expression. o When a
column name is defined as not null, that column becomes a mandatory i.e., the user has
to enter data into it. o Not null Integrity constraint cannot be defined using the alter
table command when the table contain rows.
Check Constraint: Check constraint can be defined to allow only a particular range of
values .when the manipulation violates this constraint, the record will be rejected.
Check condition cannot contain sub queries.
DOMAIN INTEGRITY
Example: Create table cust(custid number(6) not null, name char(10)); Alter table cust
modify (name not null);
CHECK CONSTRAINT
Example: Create table student (regno number (6), mark number (3) constraint b check
(mark >=0 and mark <=100)); Alter table student add constraint b2 check
(length(regno<=4));
ENTITY INTEGRITY
a) Unique key constraint
Example: Create table cust(custid number(6) constraint uni unique, name char(10));
Alter table cust add(constraint c unique(custid));
b) Primary Key Constraint
Example: Create table stud(regno number(6) constraint primary key, name char(20));
Queries:
Q1. Create a table called EMP with the following structure.
Name Type
---------- ----------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
JOB VARCHAR2(10)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Allow NULL for all columns except ename and job. Solution:
1. Understand create table syntax.
2. Use the create table syntax to create the said tables.
3. Create primary key constraint for each table as understand from logical table
structure.
Q2: Add a column experience to the emp table. experience numeric null allowed.
Solution:
1. Learn alter table syntax.
2. Define the new column and its data type.
3. Use the alter table syntax.
Q3: Modify the column width of the job field of emp table.
Solution:
1. Use the alter table syntax.
2. Modify the column width and its data type.
Table created.
Q5: create the emp1 table with ename and empno, add constraints to check the empno
value while entering (i.e) empno > 100.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [columns name type]
3. Use the alter table syntax for adding constraints.
Q7: Truncate the emp table and drop the dept table
Solution: 1. Learn drop, truncate table syntax.
Ans: SQL> truncate table emp; Table truncated.
Thus the data definition language commands was performed and implemented
successfully
Table altered.
Table altered.
Table altered
Table altered.
Table altered
Table altered.
Table altered
Table altered.
Table altered.
Table altered.
Table altered.
1 row deleted.
rows deleted.
4. Solution:
1. Create statement CREATE TABLE products ( prod_id NUMBER(4),
prod_name VARCHAR2(30), stock_qty NUMBER(15,3)
);
2. Insert command
insert into products values(02,'keyboard',15);
Modifying tables
5. ALTER TABLE products ADD price NUMBER;
6. insert into products(price) values(1000);
1. Objective (s):
NUMERIC FUNCTIONS IN SQL
1. Find the absolute values of -52,52
2. Find the Smallest integer greater than, or equal to 9.8, -32.85, 0, 5 using
Ceiling function.
3. Find the trigonometric cosine -3.14159
4. Find the exponential of the 1.
5. Find the largest integer greater than, or equal to 9.8, -32.85, 137 using Floor
function.
6. Find the natural logarithm of the 2.7
7. Find the logarithm of the 8 of 64, 3 of 27,
2 of 1024, 2 of 88. Find Modulus of (14,5),
(8,2.5), (-64,7)
9. Find Power of power(2,10), power(3,3),power(5,3),power(2,-3)
10. Find the round off values of these numbers up to given precision value
round of 12345 up to -2 precision, round of 12345.54321 up to 2
precision value.
11. Find the sign values of -2.3, 0, 47
12. Find the sin value of 1.57079 where this number in radians.
13. Find the tangent of 1.57079633/2 where this number in radians.
14. Find the truncate value of 123.456 to 2 digits of precision.
15. Find the Square root of 64, 49, 5
Date format conversion
16. Find the current date and time using SQL function.
17. Add 3,-2 number of months to current date
18. Extract the year, month and day from the current date.
19. Find the last day of the month for the date.
20. Find the months between (1)'19-dec-2002' and '19-mar-2003'
(2) '19-dec-2002','19-mar-2002'
2. Theory:
ORACLE FUNCTION
Function is a group of code that accepts zero or more arguments and both return
one or more results. Both are used to manipulate individual data items.
Operators differ from functional in that they follow the format of function name
(arg..). An argument is a user defined variables or constants. Most operators
accept at most 2 arguments while the structure of functions permit to accept 3 or
more arguments. Function can be classifies into single row function and group
functions.
Single Row functions A single row function or scalar function returns only one
value for every row queries in table. Single row function can appear in a select
command and can also be included in a where clause. The single row function
can be broadly classified as, o Date Function o Numeric Function o Character
Function o Conversion Function o Miscellaneous Function The example that
follows mostly uses the symbol table “dual”. It is a table, which is automatically
created by oracle along with the data dictionary.
Date Function They operate on date values and produce outputs, which also
belong to date data type except for months, between, date function returns a
number.
SQL Commands:
Date function
1. Add_month
This function returns a date after adding a specified date with specified number
of months.
Syntax: Add_months(d,n); where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;
2. last_day
It displays the last date of that month.
Syntax: last_day (d); where d-date
Example: Select last_day („1-jun-2009‟) from dual;
3. Months_between
It gives the difference in number of months between d1 & d2.
Syntax: month_between (d1,d2); where d1 & d2 -dates
NUMERICAL
Command
FUNCTIONS
Query Output
CHARACTER FUNCTIONS
1. to_char()
Syntax: to_char(d,[format]);
This function converts date to a value of varchar type in a form specified by date
format. If format is negelected then it converts date to varchar2 in the default
date format.
Example: select to_char (sysdate, ‟dd-mm-yy‟) from dual;
2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form
character. Example: select to_date(„aug 15 2009‟,‟mm-dd-yy‟) from dual;
Miscellaneous Functions
1. uid – This function returns the integer value (id) corresponding to the
user currently logged in.
Example: select uid from dual;
2. user – This function returns the logins user name.
Example: select user from dual;
3. nvl – The null value function is mainly used in the case where we want
to consider null values as zero.
Syntax; nvl(exp1, exp2)
SYSDATE ADD_MONTH
08-APR-05 09-AUG-05
b). last_day:
SQL> select sysdate,last_day('9-april-2005') from dual;
SYSDATE LAST_DAY
08-APR-05 30-APR-05
c). months_between:
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
4
CS3CO39: Database Management System Laboratory Experiment no- 5
Experiment Title: Numeric Functions in SQL Page 5 of 8
SYSDATE MONTHS_BETWEEN(SYSDATE,'02-NOV-1985')
08-APR-05 233.22555
d). next_day:
SQL> select sysdate,next_day('9-april-2005','monday')from dual;
SYSDATE NEXT_DAY(
08-APR-05 11-APR-05
e) Ceil:
SQL> select ceil(months_between(sysdate,'02-nov-1985'))from dual;
CEIL(MONTHS_BETWEEN(SYSDATE,'02-NOV-1985'))
234
f) Floor:
SQL> select floor(months_between(sysdate,'02-nov-1985'))from dual;
g) Mod:
SQL> select mod(10,7) from dual;
h) Power:
SQL> select power(2,3) from dual;
i) Sqrt:
SQL> select sqrt(10) from dual;
j) Abs:
SQL> select abs(10)from dual;
a). ascending:
SQL> select * from Gaurav order by name asc;
b). descending:
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
5
CS3CO39: Database Management System Laboratory Experiment no- 5
Experiment Title: Numeric Functions in SQL Page 6 of 8
c). concat:
SQL> select name || ',' || branch from Gaurav;
d). initcap:
SQL> select initcap(name) from Gaurav;
e). lower:
SQL> select lower(name) from Gaurav;
f). upper:
SQL> select upper(name) from Gaurav;
3. Software used:
Oracle Database (Recommended) or
MySQL
4. Solution:
Numeric Functions
1. ABS
select abs(-52) negative,abs(52) positive from dual;
2. Ceil
select ceil(9.8),ceil(-32.85),ceil(0),ceil(5) from dual;
3. cos
select cos(-3.14159) from dual;
4. EXP
select exp(1) "e" from dual;
5. floor
select floor(9.8),floor(-32.85),floor(137) from dual;
6. LN
select ln(2.7) from dual;
7. LOG
select log(8,64),log(3,27),log(2,1024),log(2,8) from dual;
8. Mod
select mod(14,5),mod(8,2.5),mod(-64,7) from dual;
9. power
select power(2,10), power(3,3),power(5,3),power(2,-3) from dual;
10. round
select round(12345,-2) test1,round(12345.54321,2) test2 from dual;
11. sign
select sign(-2.3),sign(0),sign(47) from dual;
12. sin
1. ADD_months
select sysdate,ADD_months(sysdate,3) plus_3,ADD_months(sysdate,-2)
minus_2 from dual;
2. Current_date
select sysdate,current_date,sessiontimezone from dual;
3. Current_timestamp
select sysdate,current_timestamp,sessiontimezone from dual;
4. extract year,month and day from date
select sysdate,extract(year from sysdate) year,extract(month from
sysdate) month,extract(timezone_hour from systimestamp)
TZH,extract(day from sysdate) day
from dual;
5. last_day
select sysdate,last_day(sysdate) end_of_month,last_day(sysdate)+1 next_month
from dual;
6. months_between
select months_between('19-dec-2002','19-mar-2003')
test1,months_between('19-dec-2002','19- mar-2002') test2
from dual;
7. next_day
select next_day('01-jan-2014','monday') "1st monday",next_day('01-feb-
2014','tuesday')+7 "2nd tuesday"
from dual;
5. Some Sample questions:
1. What is the purpose of the SQL ABS() function, and how is it used? Provide
an example.
2. Explain the usage of the SQL ROUND() function. When would you use it,
and what does it do?
3. Explain the usage of the SQL ROUND() function. When would you use it,
and what does it do?
4. Explain the SQL SQRT() function. When would you use it, and what does it
return?
5. What is the purpose of the SQL POWER() function, and how is it used?
Provide an example.
1. Objective (s):
SUB-QUERIES
Single-Row Sub-queries
1. Find the last_ name, first _name, salary of the employee with the highest
salary from employeestable.
2. Find the names and salary of the employees who work in the Accounting
department from employees table.
Multiple row Sub-queries
3. Lists all of the employees who work for the same departments as John does from
employees table.
4. Find the highest - paid employee of each department from employees table.
5. Lists the names of employees who work with John (same department) using
EXISTS operator fromemployees table.
Scalar Sub-queries
6. List the city name, country code, and if the city is in India, use CASE
expression with a sub-query to return the country code for India from the
COUNTRIES table.
7. Find the employee name, department, and the highest salary in that
department whose last_name start with letter R.
8. Find the department names and their manager names for all departments that
are in United States or Canada from EMPLOYEES, DEPARTMENTS and
COUNTRIES table.
9. Find the country id, city, state province from location table also sorts the
city names by theircountry name order.
Sub queries in other DML statements
10. Update the salary of employees to the maximum salary in the corresponding
department of theEMPLOYEES table.
11. Delete the records of employees whose salary is below the average salary in
the department ofEMPLOYEES table.
12. Insert record to the table employee _archive using Subquery.
13. Specify a Subquery in the VALUES clause of the INSERT statement.
14. Delete records of those employees whose department_id is 10 from
employees and filter fromSubquery, whose department_id<20.
2. Theory:
NESTED QUERIES
Nested Queries: Nesting of queries one within another is known as a nested
query.
Sub Queries: The query within another is known as a sub query. A statement
containing sub query is called parent statement. The rows returned by sub query
are used by the parent statement.
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
1
CS3CO39: Database Management System Laboratory Experiment no- 6
Experiment Title: Sub-Queries Page 2 of 4
Types
1. Sub queries that return several values Sub queries can also return more
than one value. Such results should be made use along with the operators in and
any.
2. Multiple queries Here more than one sub query is used. These multiple
sub queries are combined by means of „and‟ & „or‟ keywords
3. Correlated sub query A sub query is evaluated once for the entire parent
statement whereas a correlated Sub query is evaluated once per row processed
by the parent statement.
Nested Queries:
Example: select ename, eno, address where salary >(select salary from employee
where ename
=‟jones‟);
1. Subqueries that return several values
Example: select ename, eno, from employee where salary <any (select salary
from employee where deptno =10‟);
2. Correlated subquery
Example: select * from emp x where x.salary > (select avg(salary) from emp
where deptno
=x.deptno);
Sample Queries:
Q1: Display all employee names and salary whose salary is greater than
minimum salary of the company and job title starts with ‗M‘.
Solution: 1. Use select from clause. 2. Use like operator to match job and in
select clause to get the result.
Ans: SQL> select ename,sal from emp where sal>(select min(sal) from emp
where job like 'A%');
Q2: Issue a query to display information about employees who earn more than
any employee in dept 1.
Ans: SQL> select * from emp where sal>(select max(sal) from emp where
empno=1);
3. Software used:
Oracle Database (Recommended) or
MySQL
4. Solution:
1. select last_name,first_name,salary from employees
where salary=(select max(salary) from employees);
6. select city,country_id,(case
when country_id IN(select country_id from countries
where country_name='India') Then 'Indian'
Else 'Non-Indian' END) "India?"
from locations where city like 'B%';
1. Objective (s):
RELATIONS.
The purpose of a join concept is to combine data spread across tables. A join is
actually performed by the „where‟ clause which combines specified rows of
tables.
1. Simple Join
a) Equi-join: A join, which is based on equalities, is called equi-join.
b) Non Equi-join: It specifies the relationship between
Self join: Joining of a table to itself is known as self-join. It joins one row in a
table to another. It can compare each row of the table to itself and also with
other rows of the same table
Outer Join: It extends the result of a simple join. An outer join returns all the
rows returned by simple join as well as those rows from one table that do not
match any row from the table. The symbol (+) represents outer join.
Inner join: Inner join returns the matching rows from the tables that are being
joined
Simple Join
Self join Example: select * from emp x ,emp y where x.salary >= (select
avg(salary) from x.emp where x. deptno =y.deptno);
Outer Join Example: select ename, job, dname from emp, dept where
emp.deptno (+) = dept.deptno;
PERFORMING JOINS
Tables used
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
EQUI-JOIN
Q1: Display the employee details, departments that the departments are same in
both the emp and dept.
Solution: 1. Use select from clause. 2. Use equi join in select clause to get the
result.
Ans: SQL> select * from emp,dept where emp.deptno=dept.deptno;
LEFTOUT-JOIN
Tables used
Ans: SQL> select stud1.name,grade from stud1 left outer join stud2 on
stud1.name=stud2.name;
RIGHTOUTER-JOIN
Q4: Display the Student name, register no, and result by implementing a right
outer join.
Ans: SQL> select stud1.name, regno, result from stud1 right outer join stud2 on
stud1.name = stud2.name;
Name Regno Result
John 101 pass
raj 102 pass
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
3
CS3CO39: Database Management System Laboratory Experiment no- 7
Experiment Title: Perform operations like Natural Join, equijoin, Page 4 of 8
left outer join, right outer join, full outer join, intersection, union,
union all and minus on given relations.
Name Regno
john 101
raj 102
sam 103
sharing 104
SELFJOIN
Q6: Write a query to display their employee names
Ans: SQL> select distinct ename from emp x, dept y where x.deptno=y.deptno;
ENAME
Q7: Display the details of those who draw the salary greater than the average
salary. Ans: SQL> select distinct * from emp x where x.sal >= (select avg(sal)
from emp);
Thus the nested Queries and join Queries was performed successfully and
executed.
Query: Display deptno from the table employee avoiding the duplicated values.
Select should include distinct clause for the deptno. Ans: SQL> select distinct
deptno from emp;
DEPTNO
12
Q.1)Write a query to display their employee names Ans: SQL> select distinct
ename from emp x, dept y where x.deptno=y.deptno;
ENAME
Q2: Display the details of those who draw the salary greater than the average
salary. Ans: SQL> select distinct * from emp x where x.sal >= (select avg(sal)
from emp);
GROUP BY clause:
SQL> select sum(marks) from Gaurav group by stdid;
SUM(MARKS)
2322
1511
HAVING clause:
SQL> select sum(marks) from Gaurav group by stdid
having sum(marks)>2000;
SUM(MARKS)
2322
3. Software used:
Oracle Database (Recommended) or
MySQL
4. Solution:
1. Natural join
Select * from employe
natural join
ftworks
2. equijoin
Select * from employe
join
ftworks using(employee_name);
6. Union All
Select employee_name from employe where employee_name like 'A%'
UNION all
select employee_name from ftworks where salary>=50000
7. union
Select employee_name from employe where employee_name like 'A%'
UNION
select employee_name from ftworks where salary>=50000
8. intersect
Select employee_name from employe where employee_name like 'A%'
intersect
select employee_name from ftworks where salary>=50000
9. minus
Select employee_name from employe
minus
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
7
CS3CO39: Database Management System Laboratory Experiment no- 7
Experiment Title: Perform operations like Natural Join, equijoin, Page 8 of 8
left outer join, right outer join, full outer join, intersection, union,
union all and minus on given relations.
1. Objective (s):
CREATING VIEWS, MODIFYING VIEWS, DROPPING VIEWS,
INSERTING AND UPDATING DATA USING VIEWS.
1. Create a view admin_employees with attribute like first_name and
last_name concatenated as name,email, job_id with alias name position of those
employee whose department_id is 10. Use the base table employees.
2. Create a view emp_hire using defined column names employee_id,
employee_name, department_name, hire_date, commission_amt. Use base tables
employees and departments.
3. create a read only views all_locations with attribute like country_id,
country_name, location_id, city. Use the base tables locations and countries
using natural join operation.
4. Modifying views.
5. Dropping an existing view.
6. Using views in queries
Find the total commission paid for each department from emp_hire view for all
commission above
$100.
7. Inserting data through views in base table.
2. Theory:
Views:
A view is the tailored presentation of data contained in one or more table and
can also be said as restricted view to the data‟s in the tables. A view is a “virtual
table” or a “stored query” which takes the output of a query and treats it as a
table. The table upon which a view is created is called as base table.
Types of view:
Horizontal -> enforced by where cause
Vertical -> enforced by selecting the required columns
SQL Commands
Creating and dropping view:
Syntax:
Create [or replace] view <view name> [column alias names] as <query> [with
<options> conditions]; Drop view <view name>;
Example: Create or replace view empview as select * from emp; Drop view
empview;
Queries:
Tables used: SQL> select * from emp;
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
Q1: The organization wants to display only the details of the employees those
who are ASP. (Horizontal portioning)
Solution:
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
2
CS3CO39: Database Management System Laboratory Experiment no- 8
Experiment Title: Creating views, modifying views, dropping Page 3 of 5
views, inserting and updating data using views.
View created.
SQL> select * from empview;
Q2: The organization wants to display only the details like empno, empname,
deptno, deptname of the employees. (Vertical portioning)
Solution:
1. Create a view on emp table named general
2. Use select from clause to do vertical partioning
Ans: SQL> create view empview1 as select ename,sal from emp; View created.
Q3: Execute the DML commands on the view created. Ans: SQL> select * from
empview;
Thus the creation and manipulation of various database objects of the Table
using views was successfully executed.
3. Software used:
Oracle Database (Recommended) or
MySQL
4. Solution:
Creating Views
Modifying views
To change the definition of the view,use the create view with the or replace
option. The alter view statement can be used to compile an invalid view or to
add and drop constraints.
create or replace view admin_employees AS
select first_name||' '||last_name Name,email,job_id POSITION from employees
where department_id=10;
1. Objective (s):
INTRODUCTION TO PL/SQL
2. Theory:
The objective of this lab practical is to provide students with hands-on
experience in writing and executing PL/SQL (Procedural Language/Structured
Query Language) code. Students will gain practical knowledge in creating and
managing PL/SQL programs, procedures, functions, and triggers.
Overview of PL/SQL:
PL/SQL (Procedural Language/Structured Query Language) is a powerful
programming language designed specifically for seamless integration with the
Oracle Database. It extends the capabilities of SQL by adding procedural
constructs found in procedural programming languages. PL/SQL allows
developers to create robust and efficient database applications.
Declaration Section:
DECLARE
v_employee_name VARCHAR2(50);
v_salary NUMBER;
Execution Section:
Contains the actual executable code.
Consists of SQL and PL/SQL statements.
Example:
BEGIN
SELECT employee_name, salary INTO v_employee_name, v_salary FROM
employees WHERE employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name || ',
Salary: ' || v_salary);
END;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
Control Structures:
Exception Handling:
Solution
DECLARE
l_emp_name VARCHAR2(250);
l_emp_no NUMBER;
l_salary NUMBER;
Department of Computer Science & Engineering
Faculty of Engineering
Medi-Caps University
3
CS3CO39: Database Management System Laboratory Experiment no- 9
Experiment Title: Introduction to PL/SQL Page 4 of 4
l_manager VARCHAR2(250);
BEGIN
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES('BBB',1000,25000,'AAA');
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES('XXX',1001,10000,'BBB');
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES('YYY',1002,10000,'BBB');
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES('ZZZ',1003,7500,'BBB');
COMMIT;
Dbms_output.put_line('Values Inserted');
UPDATE EMP
SET salary=15000
WHERE emp_name='XXX';
COMMIT;
Dbms_output.put_line('Values Updated');
DELETE emp WHERE emp_name='ZZZ';
COMMIT;
Dbms_output.put_line('Values Deleted');
SELECT emp_name,emp_no,salary,manager INTO
l_emp_name,l_emp_no,l_salary,l_manager FROM emp WHERE
emp_name='XXX';
Dbms_output.put_line('Employee Detail');
Dbms_output.put_line('Employee Name:'||l_emp_name);
Dbms_output.put_line('Employee Number:'||l_emp_no);
Dbms_output.put_line('Employee Salary:'||l_salary);
Dbms_output.put_line('Employee Manager Name:'||l_manager);
END;
1. Objective (s):
INTRODUCTION TO PL/SQL TRIGGERS AND CURSORS
2. Theory:
Introduction to TRIGGERS in DBMS:
:A trigger in PL/SQL is a set of instructions that are automatically executed
("triggered") in response to certain events on a particular table or view. These
events can include data manipulation language (DML) events such as INSERT,
UPDATE, DELETE, and database operation events like database startup or
shutdown. Triggers allow developers to enforce business rules, perform
auditing, and automate tasks within the database.
Types of Triggers:
DML Triggers:
Instead of Triggers:
System Triggers:
Trigger Name:
A unique identifier for the trigger within the database.
Trigger Timing:
Indicates when the trigger is fired in relation to the triggering event.
BEFORE - Triggered before the triggering event.
AFTER - Triggered after the triggering event.
Trigger Event:
Specifies the event that causes the trigger to fire (e.g., INSERT, UPDATE,
DELETE).
Trigger Body:
Contains the PL/SQL code to be executed when the trigger is fired.
Can include conditional statements, SQL queries, and procedure calls.
Types of Cursors:
There are two main types of cursors:
Implicit Cursor:
v_employee_name employees.employee_name%TYPE;
BEGIN
SELECT employee_name INTO v_employee_name FROM employees
WHERE employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name);
END;
/
Explicit Cursor:
Cursor Operations:
Declaration:
The cursor is opened using the OPEN statement, which associates it with
the result set.
Fetching:
Data is retrieved from the cursor using the FETCH statement. This
operation can be performed iteratively in a loop.
Closing:
Returns TRUE if the most recent FETCH statement did not retrieve a
row.
%ROWCOUNT:
Triggers are powerful tools, but they should be used judiciously as they
introduce automatic behavior that may impact performance and complexity.
Careful consideration of their purpose and potential impact is crucial when
implementing triggers in a database system.