Oracle For Developers (DBMS SQL) - LabBook2
Oracle For Developers (DBMS SQL) - LabBook2
(DBMS SQL)
Lab Book
Capgemini Public
Document Data DBMS SQL
Date Revision No. Author Summary of Changes
05-Feb-2009 0.1D Rajita Dhumal Content Creation
09-Feb-2009 CLS team Review
20-May-2011 2.0 Sathiabama R Integration Refinements
23-May-2011 2.0 Anu Mitra Review
Page 2 of 30
Table of Contents DBMS SQL
Table of Contents
Getting Started..................................................................................................................................
Overview.......................................................................................................................4
Setup Checklist for DBMS SQL......................................................................................4
Instructions...................................................................................................................4
Learning More (Bibliography if applicable)..................................................................4
Problem Statement / Case Study.......................................................................................................
Lab 1. Data Query Language..............................................................................................................
1.1: Data Query Language..............................................................................................7
Lab 2. Single Row Functions..............................................................................................................
2.1: Single Row Functions:.............................................................................................9
2.2: Group Functions:...................................................................................................10
Lab 3. JOINS AND SUBQUERIES........................................................................................................
3.1: Joins and Subqueries.............................................................................................12
3.2: Set Operators........................................................................................................14
Lab 4. Database Objects...................................................................................................................
4.1: Database Objects..................................................................................................16
Lab 5. Data Manipulation Language.................................................................................................
5.1: Data Manipulation Language................................................................................21
Lab 6. Transaction Control Language Statements..........................................................................
6.1: Transaction Control Language Statements..........................................................23
Appendices.......................................................................................................................................
Appendix A: DBMS SQL Standards.............................................................................24
Appendix B: Coding Best Practices.............................................................................28
Appendix C: Table of Examples..................................................................................30
Page 3 of 30
Capgemini Public
LAB BOOK DBMS SQL
Getting Started
Overview
This lab book is a guided tour for learning DBMS SQL. It comprises ‘To Do’ assignments.
Follow the steps provided and work out the ‘To Do’ assignments.
Here is what is expected on your machine in order for the lab to work.
Minimum System Requirements
Intel Pentium 90 or higher (P166 recommended)
Microsoft Windows 95, 98, or NT 4.0, 2k, XP.
Memory: 32MB of RAM (64MB or more recommended)
Instructions
For all coding standards refer Appendix A. All lab assignments should refer
coding standards.
Create a directory by your name in drive <drive>. In this directory, create a
subdirectory <DBMS SQL>_assgn. For each lab exercise create a directory as
lab <lab number>.
NA
Page 4 of 30
LAB BOOK DBMS SQL
Table descriptions
Designation_Masters
Department_Masters
Student_Masters Table
Student_Marks
Name Null? Type
Student_Code Number(6)
Student_Year Not Null Number
Subject1 Number(3)
Subject2 Number(3)
Subject3 Number(3)
Staff_Masters
Page 5 of 30
LAB BOOK DBMS SQL
HireDate Date
Staff_dob Date
Staff_address Varchar2(240)
Mgr_code Number(8)
Staff_sal Number (10,2)
Book_Masters
Book_Transactions
Page 6 of 30
DBMS SQL
1. Retrieve the details (Name, Salary and dept code) of the employees who are working in
department 20, 30 and 40.
2. List the details of the employees with user defined Column headers.
3. Display the code, subjects and total marks for every student. Total Marks will be
calculated as Subject1+Subject2+Subject3. (Refer Student_Marks table)
4. List the details of the staff whose designations are either PROFESSOR or LECTURER.
5. List the code, name, and department number of the employees who have experience of
more than 18 years.
6. List the name and Designations of the staff who have joined before Jan 2003.
7. List the name, designation, and income for 10 years of the employees who are working
in departments 10 and 30.
8. List the name and experience (in years) of employees who are working as LECTURER.
9. Display name concatenated with dept code separated by comma and space. Name the
column as ‘Student Info’.
10. List the Name and Salary of the staff who are earning between 12000 and 25000. Sort
them based on their salaries and name.
Page 7 of 30
DBMS SQL
12. Write a query which will display name, department code and date of birth of all
students who were born between January 1, 1981 and March 31, 1983. Sort it based on date
of birth (ascending).
13. Get the Department number, and sum of Salary of all non managers where the sum is
greater than 20000.
14. Display the details of books that have not been returned and expected return date was
last Monday.
15. Display the name and department code of students. If student does not belong to any
department, display “No Department”. Label the column as “Department”. (Hint: Use NVL
function)
16. Display the name and salary of the staff. Salary should be represented as X. Each X
represents a 1000 in salary.
Sample Output
Page 8 of 30
DBMS SQL
1. Display name and date of birth of students where date of birth must be displayed in the
format similar to “January, 12 1981” for those who were born on Saturday or Sunday.
2. Display each staff name and number of months they worked for the organization. Label
the column as ‘Months Worked’. Order your result by number of months employed. Round
the number of months to closest whole number.
3. List the details of the employees, whose names start with ‘A’ and end with ‘S’.
4. List the name and job of the employees whose names should contain N as the second or
third character, and ending with either ‘N’ or ‘S’.
5. Create a query which will display Staff Name, Salary of each staff. Format the salary to be
15 character long and left padded with ‘$’.
6. List the names of the Employees having ‘_’ character in their name.
7. List the details of the employees who have joined in December (irrespective of the year).
8. Write a query that displays Staff Name, Salary, and Grade of all staff. Grade depends on
the following table.
Salary Grade
Salary >=50000 A
Salary >= 25000 < 50000 B
Salary>=10000 < 25000 C
Page 9 of 30
DBMS SQL
OTHERS D
9. Display the Staff Name, Hire date and day of the week on which staff was hired. Label
the column as DAY. Order the result by the day of the week starting with Monday.
10. Show staff names with the respective numbers of asterisk from Staff table.
11. Show staff names with the respective numbers of asterisk from Staff table except first
and last characters. For example: KING will be replaced with K**G.
12. Show all staffs who were hired in the first half of the month.
13. Display the staff name, hire date and day of the week on which the staff joined. Order
the results by the day of the week starting with Monday.
14. Write a query to find the position of third occurrence of ‘i’ in the given word
‘Mississippi’.
15. Write a query to find the pay date for the month. Pay date is the last Friday of the
month. Display the date in the format “Twenty Eighth of January, 2002”. Label the heading
as PAY DATE.
16. Display the Highest, Lowest, Total & Average salary of all staff. Label the columns
Maximum, Minimum, Total and Average respectively. Round the result to nearest whole
number.
17. Edit the above query and display the same for each Department Name.
18. Write a query to display number of people in each Department. Output should display
Department Code, Department Name and Number of People.
Page 10 of 30
DBMS SQL
19. Determine the number of managers without listing them. Label the column as ‘Total
Number of Managers’.
20. Display Manager Code, Manager Name and salary of lowest paid staff in that manager’s
team. Exclude any group where minimum salary is less than 10000. Order the result on
descending order of salary.
Page 11 of 30
DBMS SQL
1. Write a query which displays Staff Name, Department Code, Department Name, and
Salary for all staff who earns more than 20000.
2. Write a query to display Staff Name, Department Code, and Department Name for all
staff who do not work in Department code 10 and have ‘A’ in their name.
3. Display Staff Code, Staff Name, Department Name, and his manager’s number and
name. Label the columns Staff#, Staff, Mgr#, Manager.
4. Create a query that will display Student Code, Student Name, Department Name,
Subjec1, Subject2, and Subject3 for all students who are getting 60 and above in each
subject from department 10 and 20.
5. Create a query that will display Student Code, Student Name, Book Code, and Book
Name for all students whose expected book return date is today.
6. Create a query that will display Staff Code, Staff Name, Department Name, Designation,
Book Code, Book Name, and Issue Date. For only those staff who have taken any book in
last 30 days.
Page 12 of 30
DBMS SQL
10. List Staff Code, Staff Name, and Salary for those who are getting less than the average
salary of organization.
11. List the Staff Code, Staff Name who are not Manager.
12. Display Author Name, Book Name for those authors who wrote more than one book.
13. Display Staff Code, Staff Name, and Department Name for those who have taken more
than one book.
14. Display top ten students for a specified department. Details are:
Student Code, Student Name, Department Name, Subject1, Subject2,
Subject3, Total.
15. Display the Staff Name, Department Name, and Salary for those staff who are getting
less than average salary in their own department
16. Create a query that will display the Staff Name, Department Name, and all the staff that
work in the same department as a given staff. Give the column as appropriate label.
17. List the Student Code, Student Name for that student who got highest marks in all
three subjects in Computer Science department for current year.
18. Display the Student Code, Student Name, and Department Name for that department
in which there are maximum number of student are studying.
Page 13 of 30
DBMS SQL
19. Display Staff Code, Staff Name, Department Name, and Designation for those who have
joined most recently.
20. Display the Manager Name and the total strength of his/her team.
Page 14 of 30
DBMS SQL
1. Get the details of all products irrespective of the fact whether they are in previous set or
current set.
2. Get the details of all products along with the repetition of those that were present both
in the previous and current sets.
3. Get the details of only those products which were present in the previous set and are
still continuing.
Page 15 of 30
DBMS SQL
Time 4 hr 30 min
5. Add the Primary key constraint for Customerld with the name Custld_Prim.
Page 16 of 30
DBMS SQL
6. Insert the row given below in the Customer table and see the message generated by the
Oracle server.
1002, John, #114 Chicago, #114 Chicago, M, 45, 439525
8. Enable the constraint on CustomerId of the Customer table, and see the message
generated by the Oracle server.
9. Drop the constraint Custld_Prim on CustomerId and insert the following Data. Alter
Customer table, drop constraint Custid_Prim.
1002, Becker, #114 New York, #114 New york , M, 45, 431525, 15000.50
1003, Nanapatekar, #115 India, #115 India , M, 45, 431525, 20000.50
10. Delete all the existing rows from Customer table, and let the structure remain itself
using TRUNCATE statement.
15. Drop the unused EmailId column from the Customer table.
18. Define the COMMENT ‘Personal Contact no’ for the phoneno column of the Customer
table.
Page 17 of 30
DBMS SQL
20. Create the Suppliers table based on the structure of the Customer table. Include only
the CustomerId, CustomerName, Address1, Address2, and phoneno columns.
Name the columns in the new table as SuppID, SName, Addr1, Addr2, and Contactno
respectively.
21. Drop the above table and recreate the following table with the name CustomerMaster.
CustomerId Number(5) Primary key(Name of constraint is CustId_PK)
CustomerName Varchar2(30) Not Null
Addressl Varchar2(30) Not Null
Address2 Varchar2(30)
Gender Varchar2(l)
Age Number(3)
PhoneNo Number(10)
22. Create the AccountsMaster table with the following Columns. Use sequence to
generate Account number
Customerld Number(5)
AccountNumber Number(10,2) Primary key(Name of constraint is
Acc_PK)
AccountType Char(3)
LedgerBalance Number(10,2) Not Null
23. Relate AccountsMaster table and CustomerMaster table through Customerld column
with the constraint name Cust_acc.
25. Modify the AccountMaster table with the Check constraint to ensure AccountType
should be either NRI or IND.
Page 18 of 30
DBMS SQL
27. Modify the AccountsMaster table keeping a Check constraint with the name
Balance_Check for the Minimum Balance which should be greater than 5000.
28. Modify the AccountsMaster table such that if Customer is deleted from Customer table
then all his details should be deleted from AccountsMaster table.
29. Create Backup copy for the AccountsMaster table with the name ‘AccountDetails’.
32. Create a view on AccountsMaster table with name vAccs_Dtls. This view should list all
customers whose AccountType is ‘IND’ and their balance amount should not be less than
10000. Using this view any DML operation should not violate the view conditions.
33. Create a view accsvw10 which will not allow DML statement against it.
34. Display the department from Staff table which has the highest salary by using Inline
View.
35. List the top two highest earning employees in each department.
36. Create a Sequence with the name Seq_Dept on Deptno column of Dept table. It should
start from 40 and stop at 200. Increment parameter for the sequence Seq_Dept should be
in step of 10.
37. Insert three sample rows by using the above sequence in Dept table.
Page 19 of 30
DBMS SQL
40. Create a Unique index with the name No_Name on DeptNo and Dname of Dept table.
41. Get information on the index No_Name from the Data Dictionary.
Page 20 of 30
DBMS SQL
2. Write a query to populate Employee table using EMP table’s empno, ename, sal, deptno
columns.
Page 21 of 30
DBMS SQL
MARTI
7654 1250 30
N
7698 BLAKE 2850 30
7782 CLARK 2450 10
7788 SCOTT 3000 20
7839 KING 5000 10
TURNE
7844 1500 30
R
7876 ADAMS 1100 20
7900 JAMES 950 30
7902 FORD 3000 20
7934 MILLER 1300 10
14 rows selected.
3. Write a query to change the job and deptno of employee whose empno is 7698 to the
job and deptno of employee having empno 7788.
5. Write a query to change the deptno of employee with empno 7788 to that of employee
having empno 7698.
6. Insert the following rows to the Employee table through parameter substitution.
1000,Allen, Clerk,1001,12-jan-01, 3000, 2,10
1001,George, analyst, null, 08 Sep 92, 5000,0, 10
1002, Becker, Manager, 1000, 4 Nov 92, 2800,4, 20
1003, 'Bill', Clerk, 1002, 4 Nov 92,3000, 0, 20
Page 22 of 30
DBMS SQL
Creating a transaction
Goals Creating a savepoint
Roll back and commit the transaction to the savepoint
Time 30 min
1. Insert rows with the following data into the Customer table. 6000, John, #115 Chicago,
#115 Chicago, M, 25, 7878776, 10000
6001, Jack, #116 France, #116 France, M, 25, 434524, 20000
6002, James, #114 New York, #114 New York, M, 45, 431525, 15000.50
Use parameter substitution.
2. Create a Savepoint named ‘SP1’ after third record in the Customer table .
4. Execute rollback statement in such a way that whatever manipulations done before
Savepoint sp1 are permanently implemented, and the ones after Savepoint SP1 are not
stored as a part of the Customer table.
Page 23 of 30
DBMS SQL
Appendices
NA
Page 24 of 30
DBMS SQL
o Prefix the table names with owner names, as this improves readability,
and avoids any unnecessary confusion.
Page 25 of 30
DBMS SQL
Primary keys:
o Primary key is the column(s) that can uniquely identify each row in a
table. So just use the column name prefixed with “pk_” + “Table name”
for naming primary keys.
o Given below is an example of how we can name the primary key on the
CustomerID column of Customers table:
pk_Customers_CustomerID
o Consider concatenating the column names in case of composite primary
keys.
Foreign keys:
o Foreign keys are used to represent the relationships between tables
which are related. So a foreign key can be considered as a link between
the “column of a referencing table” and the “primary key column of the
referenced table”.
o We can use the following naming convention for foreign keys:
fk_referencing table + referencing column_referenced table +
referenced column
o Based on the above convention, we can name the foreign key, which
references the CustomerID column of the Customers table from the
Order’s tables CustomerID column as shown below:
fk_OrdersCustomerID_CustomersCustomerID
o Foreign key can be composite too. In that case, consider concatenating
the column names of referencing and referenced tables while naming the
foreign key. This might make the name of the foreign key lengthy.
However, you should not be worried about it, as you will never reference
this name from your code, except while creating/dropping these
constraints.
Default and Check constraints:
o Use the column name to which the defaults /check constraints are bound
to. Prefix it with “def” and “chk” prefixes respectively for Default and
Check constraints.
o We can name the default constraint for OrderDate Column as
def_OrderDate, and the check constraint for OrderDate column as
chk_OrderDate.
Do not use any reserved words for naming my database objects, as that can lead
to some unpredictable situations.
Do not depend on undocumented functionality. The reasons are:
o you will not get support, when something goes wrong with your
undocumented code
o undocumented functionality is not guaranteed to exist (or behave the
same) in a future release or service pack, thereby breaking your code
Page 26 of 30
DBMS SQL
Make sure you normalize your data at least till third normal form. At the same
time, do not compromise on query performance. A little de-normalization helps
queries perform faster.
Page 27 of 30
DBMS SQL
Do not use SELECT * in your queries. Always write the required column names
after the SELECT statement, as shown below:
SELECT CustomerID, CustomerFirstName, City
This technique results in less disk IO, less network traffic, and hence better
performance.
Also avoid searching with not equals operators (<> and NOT) as they result in
table and index scans. If you must do heavy text-based searches, consider using
the Full-Text search feature of SQL Server for better performance.
Use “Derived tables” wherever possible, as they perform better. Consider the
following query to find the second highest salary from Employees table:
SELECT MIN(Salary)
FROM Employees
WHERE EmpID IN
(
SELECT TOP 2 EmpID
FROM Employees
ORDER BY Salary Desc
)
The same query can be re-written by using a derived table as shown below, and it
performs twice as fast as the above query:
SELECT MIN(Salary)
FROM
(
SELECT TOP 2 Salary
FROM Employees
ORDER BY Salary Desc
) AS A
This is just an example. The results might differ in different scenarios depending
upon the database design, indexes, volume of data, etc. So test all the possible
ways a query can be written and go with the efficient one.
Page 28 of 30
DBMS SQL
Use char data type for a column, only when the column is non-nullable. If a char
column is nullable, it is treated as a fixed length column in SQL Server 7.0+. So a
char(100), when NULL, will eat up 100 bytes, resulting in space wastage. So use
varchar(100) in this situation. Of course, variable length columns do have a very
little processing overhead over fixed length columns. Carefully choose between
char and varchar depending upon the length of the data you are going to store.
Always use a column list in your INSERT statements. This helps in avoiding
problems when the table structure changes (like adding a column).
Do not use the column numbers in the ORDER BY clause as it impairs the
readability of the SQL statement. Further, changing the order of columns in the
SELECT list has no impact on the ORDER BY when the columns are referred by
names instead of numbers. Consider the following example, in which the second
query is more readable than the first one:
Page 29 of 30
DBMS SQL
Page 30 of 30