Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
95 views

Oracle For Developers (DBMS SQL) - LabBook2

Uploaded by

Safiya Patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

Oracle For Developers (DBMS SQL) - LabBook2

Uploaded by

Safiya Patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Oracle for Developers

(DBMS SQL)
Lab Book

Copyright © 2019 Capegemini. All rights reserved.

Capgemini Public
Document Data DBMS SQL

Document Revision History

                                               
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.

Setup Checklist for DBMS SQL

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)

Please ensure that the following is done:


 Oracle Client installed.
 Connectivity to Oracle Server

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

Learning More (Bibliography if applicable)

NA

Page 4 of 30
LAB BOOK DBMS SQL

Problem Statement / Case Study

Table descriptions

Designation_Masters

Name Null? Type


Design_code Not Null Number(3)
Design_name Varchar2(50)

Department_Masters

Name Null? Type


Dept_Code Not Null Number(2)
Dept_name Varchar2(50)

Student_Masters Table

Name Null? Type


Student_Code Not Null Number(6)
Student_name Not Null Varchar2(50)
Dept_Code   Number(2)
Student_dob   Date
Student_Address   Varchar2(240)

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

Name Null? Type


Staff_code Not Null Number(8)
Staff_Name Not Null Varchar2(50)
Design_code Number
Dept_code Number

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

Name Null? Type


Book_Code Not Null Number(10)
Book_Name Not Null Varchar2(50)
Book_pub_year Number
Book_pub_author Not Null Varchar2(50)

Book_Transactions

Name Null? Type


Book_Code Number
Student_code Number
Staff_code Number
Book_Issue_date Not Null Date
Book_expected_return_date Not Null Date
Book_actual_return_date Date

Page 6 of 30
DBMS SQL

Lab 1. Data Query Language

 Query the database .


Goals  Usage of various operators in select statements.
 NVL Function.
Time 1 hr 30 min

1.1: Data Query Language

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

11. Display employees who do not have manager.

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

JOHN 10000 XXXXXXXXXX


ALLEN 12000 XXXXXXXXXXXX

Page 8 of 30
DBMS SQL

Lab 2. Single Row Functions

 Querying tables using single row functions


Goals  Querying tables using date functions
 Querying tables using number functions
 Querying tables using group functions
Time 1 hr 45 min

2.1: Single Row Functions:

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.

2.2: Group Functions:

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

Lab 3. JOINS AND SUBQUERIES

 Querying multiple tables using joins


Goals  Querying tables using subqueries
 Querying tables using set operators
Time 2 hr 30 min

3.1: Joins and Subqueries

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.

7. Generate a report which contains the following information.


Staff Code Staff Name Designation Department Name
Department Head
For all staff excluding HOD (List should not contain the details of Department head).

Page 12 of 30
DBMS SQL

8. Generate a report which contains the following information


Student Code Student Name Department Name Total Marks
HOD Name
Sort the output on Department Name and Total Marks.

9. Generate a report which contains the following information.


Staff Code, Staff Name, Designation, Department, Book Code, Book Name,
Author, Fine
For the staff who have not return the book. Fine will be calculated as Rs. 5 per day.
Fine = 5 * (No. of days = Current Date – Expected return date).

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.

3.2: Set Operators


Observe the following queries and do the given assignments.

create table previous_products (


pid int,
name varchar(40),
unit varchar(40),
price int,
stock int );

Example 1: Sample Code

create table current_products (


pid int,
name varchar(40),
unit varchar(40),
price int,
stock int );

Example 2: Sample Code

insert into previous_products values(7,'Uncle Bob''s Organic Dried Pears','12 - 1 lb


pkgs.',30.00,15);
insert into previous_products values(8,'Northwoods Cranberry Sauce','12 - 12 oz
jars',40.00,6);
insert into previous_products values(1,'Chang','24 - 12 oz bottles',19.00,17);
insert into previous_products values(3,'Aniseed Syrup','12 - 550 ml bottles',10.00,13);
insert into previous_products values(4,'Chef Anton''s Cajun Seasoning','48 - 6 oz
jars',22.00,53);
insert into previous_products values(5,'Chef Anton''s Gumbo Mix','36 boxes',21.35,0);
insert into previous_products values(6,'Grandma''s Boysenberry Spread','12 - 8 oz
jars',25.00,120);

Example 3: Sample Code


insert into current_products values(7,'Uncle Bob''s Organic Dried Pears','12 - 1 lb
pkgs.',30.00,15);

Page 14 of 30
DBMS SQL

insert into current_products values(8,'Northwoods Cranberry Sauce','12 - 12 oz


jars',40.00,6);
insert into current_products values(9,'Mishi Kobe Niku','18 - 500 g pkgs.',97.00,29);
insert into current_products values(10,'Ikura','12 - 200 ml jars',31.00,31);
insert into current_products values(11,'Queso Cabrales','1 kg pkg.',21.00,22);
insert into current_products values(5,'Chef Anton''s Gumbo Mix','36 boxes',21.35,0);
insert into current_products values(6,'Grandma''s Boysenberry Spread','12 - 8 oz
jars',25.00,120);

Example 4: Sample Code

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.

4. Get the details of all obsolete products (no longer continued).

Page 15 of 30
DBMS SQL

Lab 4. Database Objects

Following set of questions are designed to implement the following concepts


 Creating Database objects like tables, views , etc
Goals  Modifying Database objects
 Deleting Database objects
 Usage of Data Dictionary tables

Time 4 hr 30 min

4.1: Database Objects

1. Create the Customer table with the following columns.


Customerid Number(5)
CustomerName Number(10)
Address1 Varchar2(30)
Address2 Varchar2(30)

2. Modify the Customer table CustomerName column of datatype with Varchar2(30).


CustomerName should not accept Nulls.

3. Add the following Columns to the Customer table.


Gender Varchar2(1)
Age Number(3)
PhoneNo Number(10)
4. Insert rows with the following data in to the Customer table.
Insert into customer values: (1000, ‘Allen’, ‘#115 Chicago’, ‘#115 Chicago’, ‘M’, ‘25, 7878776’)
In similar manner, add the below records to the Customer table:
 1000, Allen, #115 Chicago, #115 Chicago, M, 25, 7878776
 1001, George, #116 France, #116 France, M, 25, 434524
 1002, Becker, #114 New York, #114 New York, M, 45, 431525

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

7. Disable the constraint on CustomerId, and insert the following data:


 1002, Becker, #114 New York, #114 New york , M, 45, 431525
 1003, Nanapatekar, #115 India, #115 India , M, 45, 431525

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.

11. In the Customer table, add a column E_mail.

12. Drop the E_mail column from Customer table.

13. Add a new column EmailId to Customer table.

14. Mark EmailId column as unused before dropping it.

15. Drop the unused EmailId column from the Customer table.

16. Define the COMMENT ‘Customers Details’ for Customer table.

17. Use Data Dictionary USER_TAB_COMMENTS to view the created comment.

18. Define the COMMENT ‘Personal Contact no’ for the phoneno column of the Customer
table.

Page 17 of 30
DBMS SQL

19. Use Data Dictionary USER_COL_COMMENTS to view the created comment.

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.

24. Insert the following rows to the CustomerMaster table:


 1000, Allen, #115 Chicago, #115 Chicago, M, 25, 7878776
 1001, George, #116 France, #116 France, M, 25, 434524
 1002, Becker, #114 New York, #114 New York, M, 45, 431525

25. Modify the AccountMaster table with the Check constraint to ensure AccountType
should be either NRI or IND.

Page 18 of 30
DBMS SQL

26. Insert 5 rows into the AccountsMaster table:

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

30. Change the name of the AccountDetails table to ‘BackUpTable’ table.

31. Create a view ‘Acc_view’ with columns Customerld, CustomerName, AccountNumber,


AccountType, and LedgerBalance from AccountsMaster. In the view Acc_view, the column
names should be CustomerCode, AccountHolderName, AccountNumber, Type, and
Balance for the respective columns from AccountsMaster table.

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.

Hint: Use the With Check Option constraint.

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

38. Alter the above specified sequence with an increment by 5.

39. Drop the Seq_Dept sequence.

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.

42. Create public synonym synEmp for the EMP table.

43. Get Information on synonym synEmp from the Data Dictionary.

Page 20 of 30
DBMS SQL

Lab 5. Data Manipulation Language

Creating table to do the following DML operations


Goals  Insert Records
 Delete Records
 Update Records
Time 1 hr

5.1: Data Manipulation Language

1. Create Employee table with same structure as EMP table.

SQL>Create table employee as select * from emp where 1=3


SQL>desc employee

Name Null? Type


NOT
EMPNO NUMBER(4)
NULL
ENAME   VARCHAR2(10)
JOB   VARCHAR2(50)
MGR   NUMBER(4)
HIREDATE   DATE
SAL   NUMBER(7,2)
COMM   NUMBER(7,2)
DEPTNO   NUMBER(2)

SQL>select * from employee

2. Write a query to populate Employee table using EMP table’s empno, ename, sal, deptno
columns.

SQL>select * from employee


EMPN HIREDAT COM DEPTN
ENAME JOB MGR SAL
O E M O
7369 SMITH       800   20
7499 ALLEN       1600   30
7521 WARD       1250   30
7566 JONES       2975   20

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.

4. Delete the details of department whose department name is ‘SALES’.

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

Lab 6. Transaction Control Language Statements

 Creating a transaction
Goals  Creating a savepoint
 Roll back and commit the transaction to the savepoint
Time 30 min

6.1: Transaction Control Language Statements

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 .

3. Insert the below row in the Customer table.


6003, John, #114 Chicago, #114 Chicago, M, 45, 439525, 19000.60

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

Appendix A: DBMS SQL Standards

Key points to keep in mind:

NA

How to follow DBMS SQL standards:

 Decide upon a database naming convention, standardize it across your


organization and be consistent in following it. It helps make your code more
readable and understandable.
 Tables:
o Tables represent the instances of an entity. For example, you store all
your customer information in a table. Here “customer” is an entity and all
the rows in the customers table represent the instances of the entity
“customer”. So name your table using the entity it represents, namely
“Customer”. Since the table is storing “multiple instances” of customers,
make your table name a plural word.
o Keeping this in mind:
 name your customer table as “Customers'”
 name your order storage table as “Orders”
 name your error messages table as “ErrorMessages”
o Suppose your database deals with different logical functions and you
want to group your tables according to the logical group they belong to.
It will help prefixing your table name with a two or three character prefix
that can identify the group.
For example: Your database has tables which store information about
Sales and Human resource departments, then you can name all your
tables related to Sales department as shown below:
 SL_NewLeads
 SL_Territories
 SL_TerritoriesManagers
You can name all your tables related to Human resources department as
shown below:
 HR_Candidates
 HR_PremierInstitutes
 HR_InterviewSchedules

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

Appendix B: Coding Best Practices

Given below are a few best practices in 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.

 Try to avoid wildcard characters at the beginning of a word while searching by


using the LIKE keyword. This is because this arrangement results in an index scan,
which is defeating the purpose of having an index. The following statement
results in an index scan, while the second statement results in an index seek:

1. SELECT LocationID FROM Locations WHERE Specialities LIKE '%pples'


2. SELECT LocationID FROM Locations WHERE Specialities LIKE 'A%s'

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:

SELECT OrderID, OrderDate


FROM Orders
ORDER BY 2

SELECT OrderID, OrderDate


FROM Orders
ORDER BY OrderDate

Page 29 of 30
DBMS SQL

Appendix C: Table of Examples


Example 1: Sample Code......................................................................................
Example 2: Sample Code.....................................................................................
Example 3: Sample Code.....................................................................................
Example 4: Sample Code.....................................................................................

Page 30 of 30

You might also like