Вы находитесь на странице: 1из 69

Patni Computer Systems Ltd.

DBMS/SQL+
Lab Guide

Copyright 2005 Patni Computer Systems., Akruti, MIDC Cross Road No. 21, Andheri
(E), Mumbai 400 093. All rights reserved. No part of this publication reproduced in
any way, including but not limited to photocopy, photographic, magnetic, or other
record, without the prior agreement and written permission of Patni Computer
Systems.
Patni Computer Systems, considers information included in this document to be
Confidential and Proprietary.

Patni Internal

DBMS/SQL+

DBMS / SQL+
Lab Guide
Version 1.0
24th June 2005

Page 2 of

69

Patni Confidential

DBMS/SQL+

INDEX
LAB EXERCISE 1 : CONNECTING TO THE ORACLE SERVER............................................ 5
LAB EXERCISE 2 : CREATING ORACLE TABLES ............................................................ 22
LAB EXERCISE 3 : SQL .................................................................................................... 23
LAB EXERCISE 4 : MANIPULATING DATA....................................................................... 24
LAB EXERCISE 5 : QUERYING DATA ............................................................................... 25
LAB EXERCISE 6 : USAGE OF JOINS .............................................................................. 38
LAB EX ERCISE 7 : SUB QUERI ES .................................................................................... 42
LAB EXERCISE 8 : VIEWS ................................................................................................ 46
LAB EXERCISE 9: PL/SQL BLOCKS ................................................................................. 47
LAB EXERCISE 10 : PL/SQL BLOCKS .............................................................................. 49
LAB EXERCISE 11 : PROCEDURES ................................................................................. 51
LAB EXERCISE 12 : FUNCTIONS AND PACKAGES ......................................................... 52
APPENDIX A : CODING STANDARDS ............................................................................ 53
APPENDIX B : TABLES .................................................................................................. 67

Page 3 of

69

Patni Confidential

DBMS/SQL+

Introduction
This Lab book is a guided tour for Learning DBMS/SQL. It contains solved
examples and To Do assignments. Follow the steps provided in the solved
examples and then work out the To Do Assignments given.
Create a directory by your name in drive <drive>. In this directory create a
subdirectory DBMS_Assign. For each lab create a directory as lab<lab
number>.
Minimum System Requirements

Note:

Hardware: Networked PCs with minimum 64 MB RAM and 60 MB HDD.


Software: Window based Operating System having Oracle client
installed.

For coding standards refer to Appendix - A


All Lab assignments should follow the coding standards
Download all the files required to complete the assignments from
http://pace.patni.com/TechRS/Download.asp?course=DBMS_SQL_PLUS

Page 4 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 1 : Connecting to the Oracle Server


Goals

v Learn to connect to the Oracle Server


v How to save the queries which we execute at the
prompt
v Learning how to Execute queries

Time

1 Hr

Connecting to the Oracle Server


Step : 1
Click on Programs Oracle for Windows NT SQL Plus

Page 5 of

69

Patni Confidential

DBMS/SQL+

Step 2:
The following screen will be displayed.

Page 6 of

69

Patni Confidential

DBMS/SQL+
Step 3:
Type in the User id and Password followed by the Host String.
Here, the
User id scott
Password tiger
Host String Oracle8i.patni.com

Page 7 of

69

Patni Confidential

DBMS/SQL+
Step 4:
Now, you will get logged on to the Oracle Server. Check out the Prompt.

This is the SQL prompt. Now, you can type in the queries here.
We shall see a very simple query as an example to start with.

Page 8 of

69

Patni Confidential

DBMS/SQL+
Problem 2:
Problem Statement :
How to execute a query at the SQL prompt.
Solution :
Step 1:
At the SQL prompt, type in the query followed by a semicolon (;).

Page 9 of

69

Patni Confidential

DBMS/SQL+
Step 2:
The output for this query is as follows :

Page 10 of

69

Patni Confidential

DBMS/SQL+

Problem 3:
Problem Statement :
How to Save the query which we have created at the SQL prompt.
Solution :
Now, if you need to save this query inside a file. Click on Save As, choose the
path and then you can do a Cancel. So, that the path is set and from now
onwards the files which you save will automatically will get into this folder.
Step 1:
After typing the query, click on File -> Save As.

Page 11 of

69

Patni Confidential

DBMS/SQL+

Page 12 of

69

Patni Confidential

DBMS/SQL+
Step 2:
Choose the directory to which the file should be copied.

Page 13 of

69

Patni Confidential

DBMS/SQL+
Step 3:
Choose Cancel

This will make the current directory as the chosen one.

Page 14 of

69

Patni Confidential

DBMS/SQL+
Step 4:
Now, type Save followed by the filename, in order to save the query.

Note : The query file will have an extension .sql and the file will be stored in
the directory you have chosen as directed in Step 3.

Page 15 of

69

Patni Confidential

DBMS/SQL+

Problem 4:
Problem Statement :
errors.

How to make the changes to the existing query, in case of syntax

Solution :
Step 1:
Type ed at the prompt, to invoke the editor.

Page 16 of

69

Patni Confidential

DBMS/SQL+

Step 2:
The file afiedt.buf is opened in Notepad. You can make the necessary changes
in the file.

Page 17 of

69

Patni Confidential

DBMS/SQL+

Step 3:
Now, after making the changes. Save the changes and exit to the prompt.

Step 4:
This code can be executed by typing / followed by the Enter key.

Page 18 of

69

Patni Confidential

DBMS/SQL+
Problem 4:
Problem Statement :
To execute a query which is already saved in a file in the default
directory.
Solution :
Step 1:
Get, followed by the file name will bring the contents of the file in the
buffer.

Page 19 of

69

Patni Confidential

DBMS/SQL+
Step 2:
Now, to execute the file we can type / and Enter.

Page 20 of

69

Patni Confidential

DBMS/SQL+

Alternate method
Type in Run to execute a query.

Page 21 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 2 : Creating Oracle Tables


Goals

v Learn to create Oracle tables


v Primary Keys
v Foreign Keys

Time

30 Minutes

Creating Oracle Tables


1. Copy the table_details file from
http://pace.patni.com/TechRS/Download.asp?course=DBMS_SQL_PLUS
to your directory

2. Prefix your name to the table names and the constraint names.
The structure of the table is given in the Appendix - A

Page 22 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 3 : SQL


Goals
Time

At the end of this lab session you will be able to


create the tables in the database.
1.5 hours

Creating Oracle Tables


1. Create the above mentioned tables.
2. Also, create the necessary Primary Keys, Foreign keys and Not Null
rules.
3. pubdate in TITLES table should be the current date as default.
4. Drop the column contract from AUTHORS table
5. Try adding a new column contract into AUTHORS table

Page 23 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 4 : Manipulating data


Goals

Learn to Manipulate data in Oracle

Time

40 Minutes

Manipulating data
1.
2.
3.
4.

Insert the following data into the tables


Decrease the cost of the books by the discount percentage.
Set the lorange of AUTHOR as zero whose au_id=486-29-1786.
For any title whose ord_num=P3087a set lowqty as zero and high_qty
as 100 and discount as 20%.
5. For any titles with the Publisher id as 0736, payterms should be Net
90.
6. update the ytd_sales column of the titles table to reflect the most
recent sales recorded in the sales table.
7. All the publishing houses want to move their head offices to Atlanta.
8. Display the names of all authors who have written a book published by
a publisher given as a parameter. If no publisher name is supplied,
the procedure by default lists the authors published by Algodata
systems.
9. delete from publishers the row for the publisher Jardin.
10. Display the records from the publishers table and verify for the
publisher Jardin.
11. Rollback the transaction
12. Display the records from the publishers table and verify for the
publisher Jardin.
13. Now, delete the publisher Jardin and make the transaction permanent.

Page 24 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 5 : Querying data


Goals

Learn to query data in Oracle

Time

30 Minutes

Querying data
1. Display the pub_name , city, state from the publishers table
Expected Output:
PUB_NAME
---------------------------------------Algodata Infosystems
New Age Books
Binnet and Hardley

CITY
----------------Berkeley
Boston
Washington

ST
--CA
MA
DC

2. Choose all the columns from the table authors

Page 25 of

69

Patni Confidential

DBMS/SQL+
Expected Output:
AU_ID
AU_LNAME
--------------------------------------ADDRESS
CITY
--------------------------------------409-56-7008 Bennet
6223 Bateman
Berkeley
213-46-8915 Green
309 63rd St.#411
Oakland
238-95-7766 Carson
589 Darwin Ln
Berkeley
998-72-3567 Ringer
67 Seventh Av.
Salt Lake City
899-46-2035 Ringer
67 Seventh Av.
Salt Lake City
722-51-5454 DeFrance
3 Balding Pl.
Gary
807-91-6654 Panteley
1956 Arlington Dr
Rockville
893-72-1158 McBadden
301 Putnam
Vacaville
724-08-9931 Stringer
5420 Telegraph Av Oakland
274-80-9391 Straight
5420 College Av,
Oakland
756-30-7391 Karsen
5720 McAuley St. Oakland
724-80-9391 MacFeather
44 Upland Hts.
Oakland
427-17-2319 Dull
3410 Blonde St.
Palo Alto
672-71-3249 Yokomoto
3 Silver Ct.
Walnut Creek
267-41-2394 O Leary
22 Cleveland Av #14 San Jose
472-27-2349 Ginnglesby
PO Box 792
Covelo
527-72-3246 Greene
22 Graybar House Rd. Nashville
172-32-1176 White
10932 Bigge Rd
Menlo Park
712-45-1867 del Castillo
2286 Cram Pl. #86 Ann Arbor
846-92-7186 Hunter
3410 Blonde St.
Palo Alto
486-29-1786 Locksley
18 Broadway Av.
San Francisco
648-92-1872 Blotchet-Halls
55 Hillsdals Bl.
Corvallis
341-22-1782 Smith
10 Mississippi Dr. Lawrence

AU_FNAME
---------------------------ST
ZIP
C
-----Abraham
CA
94705 1
Marjorie
CA
94618 1
Cheryl
CA
94705 1
Albert
UT
84152 1
Anne
UT
84152 1
Michel
IN
46403 1
Sylvia
MD
20853 1
Heather
CA
95688 0
Dirk
CA
94609 0
Dick
CA
94609 1
Livia
CA
94609 1
Stearms
CA
94612 1
Ann
CA
94301 1
Akiko
CA
94595 1
Micheal
CA
95128 1
Burt
CA
95428 1
Morningstar
TN
37215 0
Johnson
CA
94025 1
Innes
MI
48105 1
Sheryl
CA
94301 1
Chastity
CA
94301 1
Reginald
OR
97330 1
Meander
KS
66044 0

PHONE
---------------

41 5658-9932
415 986-7020
415 548-7723
801 826-0752
801 826-0752
219 547-9982
301 946-8854
707 448-4982
415 843-2991
415 834-2919
415 534-9219
415 354-7128
415 836-7128
415 935-4228
408 286-2428
707 938-6445
615 297-2723
408 496-7223
615 996-8275
415 836-7128
415 585-4620
503 745-6402
913 843-0462

23 rows selected.
Page 26 of

69

Patni Confidential

DBMS/SQL+
3. Try printing pub_name and then pub_id from the publishers table
Expected Output:

PUB_NAME
------------------------------Algodata Infosystems
New Age Books
Binnet and Hardley

PUB_
------1389
0736
0877

4. Display the pub_name and pub_id from publisher, but the column
pub_name should be renamed as publisher in the output
Expected Output:

PUBLISHER
--------------------------Algodata Infosystems
New Age Books
Binnet and Hardley

PUB_
-------1389
0736
0877

5. Write a query to get the following output.


Expected Output:
Publisher
-----------The
The
The
The

publishers
publishers
publishers
publishers

name
name
name
name

is
is
is
is

New Age Books


Binnet& Hardley
Algodata Info Systems

Page 27 of

69

Patni Confidential

DBMS/SQL+
6. Find the projected sales increase of 100% for all the books in the titles
table.
Expected Output:

TITLE_
-----BU1032
PC1035
BU2075
PS2091
PS2106
MC3021
TC3218
MC3026
PC8888
PS7777
PS3333
BU1111
MC2222
TC7777
TC4203
BU7832
PS1372
PC9999

YTD_SALES
--------4095
8780
18722
2045
111
22246
375

YTD_SALES*2
----------8190
17560
37444
4090
222
44492
750

4095
3336
4072
3876
2032
4095
15096
4095
375

8190
6672
8144
7752
4064
8190
30192
8190
750

18 rows selected.

7. Display the title_id for the books which has sold so far.
Expected Output:
TITLE_
-----BU1032
BU1111
BU2075
BU7832
MC2222
MC3021
PC1035
PC8888
PS1372
PS2091
PS2106
PS3333
PS7777
TC3218
TC4203
TC7777
16 rows selected.
Page 28 of

69

Patni Confidential

DBMS/SQL+
8. Display all the details from the sales table for the title_id PS2091
Expected Output:

STOR
---7066
7067
7131
6380

ORD_NUM
-------------------QA74423
D4482
N914008
722a

S_DATE
--------13-SEP-85
14-SEP-85
14-SEP-85
13-SEP-85

QTY
--------75
10
20
3

PAYTERMS
------------------On Invoice
Net 60
Net 30
Net 60

TITLE_
---------PS2091
PS2091
PS2091
PS2091

9. Display all the author_ids and their phone numbers, where the phone
number is not equal to 415 658-9932.
Expected Output:

AU_ID
----------409-56-7008
213-46-8915
238-95-7766
998-72-3567
899-46-2035
722-51-5454
807-91-6654
893-72-1158
724-08-9931
274-80-9391
756-30-7391
724-80-9391
427-17-2319
672-71-3249
267-41-2394
472-27-2349
527-72-3246
172-32-1176
712-45-1867
846-92-7186
486-29-1786
648-92-1872
341-22-1782

PHONE
-----------41 5658-9932
415 986-7020
415 548-7723
801 826-0752
801 826-0752
219 547-9982
301 946-8854
707 448-4982
415 843-2991
415 834-2919
415 534-9219
415 354-7128
415 836-7128
415 935-4228
408 286-2428
707 938-6445
615 297-2723
408 496-7223
615 996-8275
415 836-7128
415 585-4620
503 745-6402
913 843-0462

23 rows selected.

Page 29 of

69

Patni Confidential

DBMS/SQL+
10. Find all business and psychology books that do not have an advance
over 15,500
Expected Output:

TITLE_
-----BU1032
BU2075
BU1111
BU7832

TYPE
-----------business
business
business
business

ADVANCE
--------5000
10125
5000
5000

11. Find all books with sales between 4,095 and 13,000(Do it in two ways)
Expected Output:
TITLE_
-----BU1032
PC1035
PC8888
TC7777
BU7832

YTD_SALES
--------4095
8780
4095
4095
4095

Page 30 of

69

Patni Confidential

DBMS/SQL+

12. Get a list of the names and states of all the authors who live in
California, Indiana, or Maryland
Expected Output:
AU_LNAME
---------------------------------------Bennet
Green
Carson
DeFrance
Panteley
McBadden
Stringer
Straight
Karsen
MacFeather
Dull
Yokomoto
O Leary
Ginnglesby
White
Hunter
Locksley

ST
-CA
CA
CA
IN
MD
CA
CA
CA
CA
CA
CA
CA
CA
CA
CA
CA
CA

17 rows selected.

13. Get a list of authors who do not live in Indiana or Maryland.


Expected Output:
AU_LNAME
---------------------------------------Bennet
Green
Carson
Ringer
Ringer
McBadden
Stringer
Straight
Karsen
MacFeather
Dull
Yokomoto
O Leary
Ginnglesby
Greene
White

ST
-CA
CA
CA
UT
UT
CA
CA
CA
CA
CA
CA
CA
CA
CA
TN
CA
Page 31 of

69

Patni Confidential

DBMS/SQL+

del Castillo
Hunter
Locksley
Blotchet-Halls
Smith

MI
CA
CA
OR
KS

21 rows selected.

14. To find all the phone numbers in the authors table that do not have 415
as the area code
Expected Output:
PHONE
-----------41 5658-9932
801 826-0752
801 826-0752
219 547-9982
301 946-8854
707 448-4982
408 286-2428
707 938-6445
615 297-2723
408 496-7223
615 996-8275
503 745-6402
913 843-0462
13 rows selected.

15. To find the phone numbers of authors whose name ends with inger
and does not begin with L.
Expected Output:
no rows selected.

Page 32 of

69

Patni Confidential

DBMS/SQL+

16. To list books with an advance under $5000 or a null value.


Expected Output:

TITLE_
-----PS2091
MC3026
PS7777
PS3333
MC2222
TC4203
PC9999

ADVANCE
--------2275
4000
2000
0
4000

7 rows selected.

17. Display the phone list of authors in alphabetical order


Expected Output:
AU_FNAME
-------------------Abraham
Reginald
Cheryl
Michel
Ann
Burt
Marjorie
Morningstar
Sheryl
Livia
Chastity
Stearms
Heather
Micheal
Sylvia
Albert
Anne
Meander
Dick
Dirk
Johnson
Akiko
Innes

AU_LNAME
---------------------------------------Bennet
Blotchet-Halls
Carson
DeFrance
Dull
Ginnglesby
Green
Greene
Hunter
Karsen
Locksley
MacFeather
McBadden
O Leary
Panteley
Ringer
Ringer
Smith
Straight
Stringer
White
Yokomoto
del Castillo

PHONE
-----------41 5658-9932
503 745-6402
415 548-7723
219 547-9982
415 836-7128
707 938-6445
415 986-7020
615 297-2723
415 836-7128
415 534-9219
415 585-4620
415 354-7128
707 448-4982
408 286-2428
301 946-8854
801 826-0752
801 826-0752
913 843-0462
415 834-2919
415 843-2991
408 496-7223
415 935-4228
615 996-8275

23 rows selected.
Page 33 of

69

Patni Confidential

DBMS/SQL+
18. Find the title_id, pub_id and type of books which have an advance
greater than 5000 and sort them by type and pub_id in the descending
order.
Expected Output:

TYPE
PUB_ TITLE
---------------------------------------------------------------------------------------------trad_cook
0877 Onions, Leeks and Garlic, Cooking, Secrets of the Mediterranean
trad_cook
0877 Seshi Anyone?
psychology
0736 Life without Fear
popular_comp 1389 But is it User Friendly
popular_comp 1389 Secrets of Silicon Valley
mod_cook
0877 The Gourmet Microwave
business
0736 You can Combat Computer Stress!
Phobic beh
0877 Computer
8 rows selected.

19. Find the total number of books


Expected Output:
COUNT(*)
--------18

20. Find out how many shipments of books are going out, i.e., how many
different stores have placed orders.
Expected Output:

COUNT(DISTINCTSTOR_ID)
---------------------6

Page 34 of

69

Patni Confidential

DBMS/SQL+

21. Display the details of the book whose titles are MC3021, TC3218 and
PC8888.
Expected Output:
TITLE_ TITLE
TYPE
-----------------------------------------------------------------------------------------------PUB_ PRICE
ADVANCE
ROYALTY
YTD_SALES
-----------------------------------NOTES
---------------------------------------------------------------------------------------------------PUBDATE
--------PC8888 Secrets of Silicon Valley
popular_comp
1389
20
8000
10
4095
Muckraking reporting by two courageous women on the worlds largest computer hardware
and software manufactures
12-JUN-85
TC3218 Onions, Leeks and Garlic, Cooking, Secrets of the Mediterranean
trad_cook
0877
20.95
7000
10
375
Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend.
21-OCT-85
MC3021 The Gourmet Microwave
0877
2.99
15000
24
22246
Traditional French gourmet recipes adapted for modern microwave cooking
18-JUN-85

Page 35 of

69

mod_cook

Patni Confidential

DBMS/SQL+

22. Display all the details of psychology books in the order of its price in
Alphabetical order.
Expected Output:
TITLE_ TITLE
TYPE
-----------------------------------------------------------------------------------------------PUB_ PRICE
ADVANCE
ROYALTY
YTD_SALES
-----------------------------------NOTES
---------------------------------------------------------------------------------------------------PUBDATE
--------PS2106 Life without Fear
psychology
0736
7
6000
10
111
New exercise meditation and nutritional techniques that can reduce the shock of daily
interactions
05-OCT-85
PS7777 Emotional Security: A New Algorithm
psychology
0736
7.99
4000
10
3336
Protecting yourself and your loved ones from undue emotional stress in the modern world
12-JUN-85
PS2091 Is Anger the Enemy
psychology
0736
10.95
2275
12
2045
Carefully researched study of the effects of strong emotions on the body. Metabolic charts
included
15-JUN-85
PS3333 Prolonged Data Derivation Four Case Studies
psychology
0736
19.99
2000
10
4072
What happens when the program runs data? Searching evaluations of information.
Shortage effects on heavy users
12-JUN-85

23. Find the average advance paid for a psychology book.


Expected Output:

AVG_ADVANCE
----------3568.75

Page 36 of

69

Patni Confidential

DBMS/SQL+
24. Find the average advance and sum of year_to_date sales for each type
of book.
Expected Output:

TYPE
-----------Phobic beh
UNDECIDED
business
mod_cook
popular_comp
psychology
trad_cook

AVG(ADVANCE)
-----------7000

SUM(YTD_SALES)
-------------375

6281.25
7500
7500
3568.75
6333.3333

30788
24278
12875
9564
19566

7 rows selected.

25. Group the rows in the titles table by type, but eliminate the groups
that include only one book
Expected Output:

TYPE
-----------business
mod_cook
popular_comp
psychology
trad_cook

26. Calculate the sum of the prices of the different types of cooking books.
27. Find the grand total of the prices and advances of all types of books
whose price is over $20.

Page 37 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 6 : Usage of Joins


Goals

Learn to query data using Joins in Oracle

Time

30 Minutes

Usage of Joins
1. List the store_id, name, title_id and quantity ordered for each sale of
the book, IS Anger the Enemy, with title_id PS2091.
Expected Output:

STOR STOR_NAME
TITLE_
---- --------------------------------------------7066 Burnums
PS2091
7067 News and Brws
PS2091
7131 Doc-U-Mat:Quality Laundry and Books PS2091
6380 Eric the Read Books
PS2091

Page 38 of

69

QTY
--------75
10
20
3

Patni Confidential

DBMS/SQL+
2. Find the authors who do not live in the state that New Age Books
belongs to, in alphabetical order.
Expected Output:

PUB_NAME
---------------------------------------AU_FNAME
-------------------Algodata Infosystems
Abraham
Algodata Infosystems
Marjorie
Algodata Infosystems
Heather
Algodata Infosystems
Dirk
Algodata Infosystems
Cheryl
Algodata Infosystems
Dick
Algodata Infosystems
Stearms
Algodata Infosystems
Akiko
Algodata Infosystems
Burt
Algodata Infosystems
Chastity
Algodata Infosystems
Sheryl
Algodata Infosystems
Johnson
Algodata Infosystems
Micheal
Algodata Infosystems
Ann
Algodata Infosystems
Livia

ST
--

AU_LNAME
------------------------

CA

Bennet

CA

Green

CA

McBadden

CA

Stringer

CA

Carson

CA

Straight

CA

MacFeather

CA

Yokomoto

CA

Ginnglesby

CA

Locksley

CA

Hunter

CA

White

CA

O Leary

CA

Dull

CA

Karsen

15 rows selected.

Page 39 of

69

Patni Confidential

DBMS/SQL+
3. Find out which authors in Oakland(city), California(state) live in the
same zip code area.
Expected Output:
AU_FNAME
AU_LNAME
AU_FNAME
----------------------------------------------------------- -------------------AU_LNAME
---------------------------------------Dick
Straight
Dirk
Stringer
Dick
Karsen

Straight

Livia

Dirk
Karsen

Stringer

Livia

4. Find the titles of all the books of a particular type (trad_cook), and the
names of their authors.
Expected Output:
AU_LNAME
AU_FNAME
----------------------------------------------------------TITLE
------------------------------------------------------------------------Panteley
Sylvia
Onions, Leeks and Garlic, Cooking, Secrets of the Mediterranean
Yokomoto
Seshi Anyone?

Akiko

O Leary
Seshi Anyone?

Micheal

Ginnglesby
Seshi Anyone?

Burt

Blotchet-Halls
Reginald
Fifty Years in Buckingham Palace Kitchens

Page 40 of

69

Patni Confidential

DBMS/SQL+

5. Select all the non-matching rows from the authors table while joining
authors and publishers.
Expected Output:

AU_FNAME
AU_LNAME
--------------------------------------------PUB_NAME
---------------------------------------Abraham
Bennet
Algodata Infosystems
Cheryl
Algodata Infosystems

Carson

New Age Books


Binnet and Hardley

Page 41 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 7 : Sub Queries


Goals

Learn to query data using subqueries in Oracle

Time

30 Minutes

Usage of Sub Queries


1. Find all the books that have the same price as Straight Talk About
Computers.
Expected Output:
no rows selected
2. Find the publishes who have published business books, the following
command is used.
Expected Output:

PUB_NAME
---------------------------------------Algodata Infosystems
New Age Books

3. Find the names of the authors who have participated in writing at least
one popular computing book.
Expected Output:
AU_LNAME
---------------------------------------Carson
Dull
Locksley
Hunter

AU_FNAME
-------------------Cheryl
Ann
Chastity
Sheryl

Page 42 of

69

Patni Confidential

DBMS/SQL+
4. Find the names of authors who live in the city where the publisher
Algodata Infosystems is located.
Expected Output:
AU_LNAME
---------------------------Bennet
Carson

AU_FNAME
----------------Abraham
Cheryl

5. Find out which books commanded an advance greater than the largest
advance paid by Algodata Infosystems.
Expected Output:

TITLE
-------------------------------------------------------------------The Busy Executives Dtabase Guide
But is it User Friendly
You can Combat Computer Stress!
Is Anger the Enemy
Life without Fear
The Gourmet Microwave
Onions, Leeks and Garlic, Cooking, Secrets of the Mediterranean
The Psychology of Computer Cooking
Secrets of Silicon Valley
Emotional Security: A New Algorithm
Prolonged Data Derivation Four Case Studies
Cooking with Computers: surreptitious Balance Sheets
Silicon Valley Gastronomic Treats
Seshi Anyone?
Fifty Years in Buckingham Palace Kitchens
Straight Talk about Computers
Computer
Net Etiquette
18 rows selected.

Page 43 of

69

Patni Confidential

DBMS/SQL+
6. Find the titles that got an advance larger than the minimum advance
amount paid by Algodata Infosystems.
Expected Output:
TITLE
---------------------------------------------------------------------But is it User Friendly
Computer
Life without Fear
Onions, Leeks and Garlic, Cooking, Secrets of the Mediterranean
Secrets of Silicon Valley
Seshi Anyone?
The Gourmet Microwave
You can Combat Computer Stress!
8 rows selected.

Correlated sub Query


7. Find the names of all authors who earn 100% royalty on a book.
Expected Output:
AU_LNAME
---------------------------------------Blotchet-Halls
Carson
Green
Locksley
Panteley
Ringer
Straight
White
del Castillo

AU_FNAME
---------------Reginald
Cheryl
Marjorie
Chastity
Sylvia
Albert
Dick
Johnson
Innes

9 rows selected.

8. To find the books published by more than one publisher.


Expected Output:

TYPE
-----------business

Page 44 of

69

Patni Confidential

DBMS/SQL+

9. Find the types of books in which the maximum advance is more than
twice the average within a given group, the command used is.
Expected Output:

TYPE
-----------mod_cook

10. Find the names of all the publishers who publish business books.
Expected Output:
PUB_NAME
-------------------------------------Algodata Infosystems
New Age Books

Page 45 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 8 : Views


Goals

Learn to create views in Oracle

Time

30 Minutes

Usage of Views
1. Create a view which will display all the records from titles whose price
is greater than 15 and advance is greater than 5000.
2. Create index on Royaltyper in the Title author table.
3. Would like to search the titles table with the publishers date. So,
create an index on that.
4. Create a view called cats which shows the average price for each type
of book.
5. Create a view called cities which lists the names of authors and
publishers that live in the same city.
6. Create a new table called sales_table containing the Author ID, title ID
and sales quantity.

Page 46 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 9: PL/SQL Blocks


Goals

Learn to create PL/SQL Blocks in Oracle

Time

30 Minutes

Usage of PL/SQL Blocks


1. Create a Block that declares two variables. Assign the values of these
PL/SQL variables to host variables and prints the results.
2. Create a block that selects the maximum publisher id in the titles table
and prints it.
3. Create a block that updates the price for an existing publisher by 10%.
Display the titles details which are updated.
4. Create a block that computes the discount amount for a given title
based on the title price.
Price
Discount Rate
a.
<10
10%
b.
<15 & >10
15%
c.
>15
20%
d.
NULL
0
5. Create a messages table. Write a Block that will accept two numbers
and insert data into messages whether number is ODD or EVEN.
6. Create a PL/SQL block to retrieve the name of each book from the
titles table and print each book name to the screen , incorporating a
PL/SQL tables.
7. Create a block that determines the top title_id with respect to their
price. Insert this data into the TOP_PRICED table.

8. Write a PL/SQL block to select the name of the title with a given price
value. If the price entered returns more than one row handle the
Page 47 of

69

Patni Confidential

DBMS/SQL+
exception with an appropriate exception handler and insert into the
Messages table . If the price value does not return any title name ,
handle the exception and insert into the Messages table. Handle any
other exception and insert data into Messages table.
9. Write a block which displays author details after accepting au_id,
handle all possible exceptions.

Page 48 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 10 : PL/SQL Blocks


Goals

Learn to create PL/SQL blocks in Oracle

Time

1 Hour

Usage of PL/SQL Blocks


1. Write a PL/SQL block to print all even nos from 2 to n where n is
accepted from the user.
2. Write a block to print factorial of a number
3. Write a Block to update price of the title. If price is greater then 20$
update it by 10% else update it by 5%.
4. Write a block to accept title_id & update price. Update price as price discount. But if discount=0 or null update price by 5% of price and then
update price. Use exceptions.
5. The Publishers have decided to raise the cost of the books by 0.15.
Write a PL/SQL block to accept the title_id & update the price of that
title. Display appropriate based on existence of the record in the titles
table.
6. Raise price of all the psychology books by 12% and display how many
rows were affected.
7. Write a block to count number of books in a particular type & displaly
their names and cost. Use explicit cursor.
8.

Write a block to delete details of those books whose cost is between


20 and 30.

9. Write a procedure to accept two numbers and the operator . Perform


operation on the numbers & print the result.
10. Modify assignment 4 to write a procedure.
Page 49 of

69

Patni Confidential

DBMS/SQL+
11. Create a Package which has procedure/function to find prime number,
even/odd number.
12. Write a trigger which maintains audit of records which are updated or
deleted from the titles table. The audit table should store the old
values and username, operation, date of operation.
13. Write a function which calculates area of a circle. The calculated value
should be returned by the function, and inserted into a table
CIRCLE_AREA.

Page 50 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 11 : Procedures


Goals

Learn to create procedures in Oracle

Time

2 Hrs

Usage of Procedures
1. To display the names of all authors who have written a book
published by a publisher given as a parameter. If no publisher name
is supplied, the procedure by default lists the authors published by
Algodata Infosystems.
2. Find out if there is an author with the surname Smith and print a
message
3. Check that both the title and the store exist before creating a sales
record. Assume that the variables inp_title and inp_store contain
the required title and stor_id.
4. Write a procedure that reports the total year to date sales, for each
type o book.
5. Write a procedure that shows the average advance paid by each
publisher.
6. Write a procedure to return the number of sales for a title
(PS2091).
7. Write a procedure to return the contract status for an autho5r.
Return 900 if the author does not exist. Take (@name) as a
parameter to accept user input.
8. Write a delete trigger on the publishers table. When a publisher is
deleted, the corresponding titles also have to be deleted. (Assume
nested triggers, and let the titles delete trigger deal with the
consequences of deleting a title)

Page 51 of

69

Patni Confidential

DBMS/SQL+

Lab Exercise 12 : Functions and Packages


Goals

Learn to create Functions and Packages in Oracle

Time

2 Hrs

Usage of Functions & Packages


1. Convert the procedures mentioned in Lab Exercise 10 (5 onwards) to
Functions.
2. Create a package which will comprise of the procedures mentioned in
Lab Exercise 10 (1 to 4).

Page 52 of

69

Patni Confidential

DBMS/SQL+

Appendix A : Coding Standards


File naming conventions

All PL/SQL program units are stored in the database. Before they are
compiled into the database, they are usually created as a text file. Use the
following extensions for naming these text files
File Type
Stored Package Body
Stored Package
Specification
Stored Procedure
Stored Function
Trigger
Anonymous block
Table creation
statement
Test script
Multiple DDL
statements

Extension
pkb
pks

Example
Dbmsout.pkb
Dbmsout.pks

spr
trg
sql
Sql

UpdCust.spr
GetCust.sfn
cascade.trg
testtrg.sql
emp.sql

tst
Sql

dbmssql.tst
setup.sql

sfn

Identifier naming conventions

Think of all identifiers as consisting of 4 parts.


<Scope><Data Type><Primary Identifier><Modifier>. Of the 4 elements .
All the elements constitute the variable name.

Local variables names have prefix 'lv_ for varchar or 'ln_ for
number or 'lb_' for boolean

Global variables names have prefix 'gv_ for varchar or 'gn_ for
number or 'gb_' for boolean

Reserved words should not be used as user-defined variables.

All variable should be in lower case

Database user defined exception names should have prefix exp_


For e.g. exp_High_Salary

Page 53 of

69

Patni Confidential

DBMS/SQL+
Examples
Data
type
V

Description

Scope

Example

Varchar

Global

gv_loop_
count

Char

Local

Number

Parameter

Date

Global

Cur

Cursor

Local

Variable

parameter

Rec

Record

Local

Tab

PL/SQL
Table

Local

Exp

Exception

Local

Vrr

Varray

Local

tt

Collection
type

Local

Comment

Global
varchar
variable
lc_emp_ Local
name
character
Pn_loop_ Parameter
count
number
variable
gd_loop_ Global date
count
Variable
lcur_loo
Local cursor
p_count
Variable
Pv_loop_ Parameter
count
varchar
variable
lrec_em Local emp
p
record
Ltab_dep Local table
t
of
departments
Lexp_hig High salary
salary
exception
Lvrr_em Local Varray
ail_Addr of email
ess
address
L_numbe Local
r_tt
number
collection

Parameter naming conventions

Think of all parameters as consisting of 5 parts.


<P><Scope (In /Out/Inout ><Data Type><Primary Identifier><Modifier>.
Of the 5 elements. All the elements constitute the variable name.

The parameter name should be in lower case and should begin


with p

Page 54 of

69

Patni Confidential

DBMS/SQL+

Data
type
V

Descriptio
n
Varchar

Scope

Example

Comment

In

Cur

Cursor

Out

Cur

Cursor

InOut

P_v_in_loop In
_count
Parameter
of varchar
data type
p_cur_out_ Out
emp
Parameter
of cursor
data type
p_cur_inout In Out
_emp
Parameter
of cursor
data type

Indentation Recommendations

The following indentation conventions are recommended. Note


that the minimum indentation is described. More spaces may be
required for the vertical alignment recommended in subsequent
guidelines.
Use three spaces as the basic unit of indentation for nesting.
Use three spaces as the basic unit of indentation for
continuation lines.

Alignment

As mentioned above trying to keep programs pretty is a lot of work.


Hence the following recommendations.

Do not try to align statements, operators etc. vertically. This not


only takes up time, but also leads to realigning text
continuously.

Indent continuation lines the same three spaces.

Provide one declaration per line (at most).

Place the first parameter specification on a separate line from


the function or procedure declaration. If any of the parameter
types are forced beyond the line length limit, place the first
parameter specification on a new line indented as for
continuation lines.

Page 55 of

69

Patni Confidential

DBMS/SQL+
Conditional Statements

If...Then...Else
Conditional statements either skip or execute statements based on a
conditional expression which must evaluate to True or False. There are
three variations of syntax for this statement.
Keywords on Separate Lines
Place the keywords(IF, THEN, ELSE, ELSIF, ENDIF) on separate lines. We
prefer this format for two reasons. Firstly, it places all the keywords in
the same column making it easier to eyeball the logical structure.
Secondly it creates white space around the keywords.
Indent statements from the keywords by the customary 3 spaces. The
key words should be in Capitols ( IF, THEN, ELSE , ELSEIF , END IF) . All
the Key words should be in Capital letters

Stored Procedures

The following guidelines should be used while coding stored


procedures.

Database
Procedure
names
should
name>>_<<Procedure name>>_prc
For e.g. PCS_UPDATE_CUST_Prc

Procedure code should contain a Identification header (Module


Log) Please see ANNEXURE I

Whenever possible stored procedures should be used for the


following as they can improve database performance, enforce
data security, result in substantial reduction in memory
requirement for the application and avoid redundant coding.

be

<<Schema

Common global enforcement of business rules and


functionality
Large complex update routines

Do not define long procedures with several distinct sub-tasks;


otherwise, sub-tasks common to many procedures may be
unnecessarily duplicated in the code of several procedures.

Page 56 of

69

Patni Confidential

DBMS/SQL+

Procedures should not be defined to enforce simple data


integrity rules that can be easily enforced using declarative
integrity constraints.

All Stored Procedures must contain an 'EXCEPTION' handling


section.

Packages

The following guidelines should be used while creating packages.

Database
package
names
name>>_<<Package name>>_pkg
For e.g. PCS_UPDATE_CUST_Pkg

Package code should contain a Identification header (Module


Log) Please see ANNEXURE I

Packages should be kept as general as possible so that they can


be reused in future applications.

Package specifications reflect the design of your application. So


they should be defined before the package bodies. Place only
the types, objects and subprograms that must be visible to the
users of the package in a specification. That way, other
developers cannot misuse the package by basing their code on
irrelevant implementation details.

An application should always initialize all package variables,


either declaratively or using an initialization procedure.
Automatic First-Time-Only Code should be used to initialize
package variables. This code should be defined in a BEGIN ....
END block of the package body.

Use packages containing private procedures and functions for


hiding certain sections of code.
e.g. You might include sensitive procedures as password
generators or auditing check-digit calculators in a package. That
way, it is possible to allow limited, controlled access to them.
The package handles the logic of allowing this code to be
referenced only by those privileged to use them.

Consider creating Package specification and package body to


avoid the sequential creation of packages. Compile Package
Page 57 of

69

should

be

<<Schema

Patni Confidential

DBMS/SQL+
Specification first then package body this will break the
dependencies between the procedures.

Consider using NOCOPY option while passing out parameter


which will improve the performance. With the new NOCOPY
option, OUT and IN OUT parameters are passed by reference,
which avoids copy overhead. However, parameter set copy is not
created and, in case of an exception rollback, cannot be
performed and the original values of parameters cannot be
restored.

SQL Guidelines

The following standards identify 'SQL Coding' standards that should be


used in the development of application software in an ORACLE
environment.

Each main clause of a SQL statement should start on a new line.


The keywords for these clauses include SELECT, INSERT,
UPDATE, DELETE, CREATE, FROM, WHERE, ORDER BY, GROUP BY,
HAVING, and INTO.

Use separate line for each expression in a SELECT list

Place each table in a FROM clause on its own line

Place each expression in WHERE clause on its own line

Each column name should be prefixed with the table name (or
an alias) to which it belongs. The exception to this rule is single
table access.
e.g.
SELECT emp_name
INTO :ho_emp_name
FROM emp
WHERE salary > 10000

Use sensible abbreviations for table and column aliases


Instead of a code segment such as,
SELECT select list
FROM employee A
Company B
History C
Bonus D
Profile E
Sales F
WHERE A.company_id = B.company_id
Page 58 of

69

Patni Confidential

DBMS/SQL+
AND A.employee_id = C.employee_id
AND B.company_id = F.company_id
AND A.employee_id = D.employee_id
AND B.company_id = E.company_id;
Use a code segment such as,
SELECT select list
FROM employee EMP
Company CO
History HIST
Bonus
Profile PROF
Sales
WHERE EMP.company_id = CO.company_id
AND EMP.employee_id = HIST.employee_id
AND CO.company_id = SALES.company_id
AND EMP.employee_id = BONUS.employee_id
AND CO.company_id = PROF.company_id;

An asterisk ('*') should not be used as a reference for all columns


in a table in source code (i.e., 'SELECT * FROM...', etc.). If the
definition of a table changes, the statement may become invalid
when an asterisk is used.

INSERT statements must list every column in the target table, as


well as the value (or column name) to be inserted.

Each SQL statement should be reviewed for performance


considerations (i.e., index utilization, table order, views, and
sub-queries versus outer joins).

To state 'not equal', the operands '<>' should be used instead of


'!=' or '^='.

If a SQL statement contains a WHERE clause or a sub query,


ensure that the sub query or WHERE clause is optimized using
the standard query optimization principles.

Page 59 of

69

Patni Confidential

DBMS/SQL+
General Coding Standards

The following standards identify 'General Coding' standards that should


be used in the development of application software in an ORACLE
environment.

Database
function
names
name>>_<<Function name>>_fnc
For e.g. PCS_UPDATE_CUST_FNC

Arithmetic symbols should be preceded and followed by a space


(' '), except when at the end of a line.

Source code lines should be less than eighty (80) characters.

Source code should not have any blank lines

All INSERT, UPDATE, and DELETE statements must access tables


in the proper order

COMMIT, ROLLBACK points should be properly chosen based on


business requirement

If exception occurs should rollback the transaction

Use anonymous transaction to insert the errors into error table

Always use the %TYPE attribute to declare variables, which are


actually PL/SQL representations of database values. This
includes a lot of your variables. Using %TYPE sometimes takes
lots more typing, but it improves your code substantially.

should

be

<<Schema

e.g. lv_first_name customer.cust_fname%TYPE;


While many (perhaps even most) of your local PL/SQL variables
are directly related to database columns, at least some of your
variables are local-only, perhaps calculated values based on
database columns. Use the %TYPE attribute to infer a variable's
data type from another, previously defined PL/SQL variable.

Page 60 of

69

Patni Confidential

DBMS/SQL+
The following declarations use this alternative source:
DECLARE
revenue_data NUMBER(20,2);
total_revenue revenue_data%TYPE

Consider not using Gotos in the programs. Gotos make for


unreadable, and high maintenance code. There is only one
instance where a Go to should be used in PL/SQL. That is for
exiting a procedure. In addition to this If you must use Gotos,
then make them forward only. Typical use for a forward only
Goto is to jump to an exit point so that any clean up code can be
executed before exiting.

Do not recycle the variables


Each variable and constant you declare should have one purpose
and one purpose only. The name for that variable or constant
should describe, as clearly as possible, that single-minded
purpose. You should go through your programs and remove any
part of your code that is no longer used. This is a relatively
straightforward process for variables and named constants.

Take advantage of PL/SQL packages to reduce dynamic


recompilation of sorted procedures. Consider pinning large or
performance critical packages in the shared pool.

Using tables to cache frequently accessed values can improve


performance remarkably.

External tables allow Oracle to query data that is stored outside


the database in flat files. The ORACLE_LOADER driver can be
used to access any data stored in any format that can be loaded
by SQL*Loader. No DML can be performed on external tables but
they can be used for query, join and sort operations. Views and
synonyms can be created against external tables. They are
useful in the ETL process of data warehouses since the data
doesn't need to be staged and can be queried in parallel. They
should not be used for frequently queried tables.

Consider using package instead of using stand alone Stored


procedures and functions since Packages breaks the dependency
chain (If Procedure A calls procedure B Its has to be created in
the correct order Packages breaks this dependency) and
packages has better code security
Page 61 of

69

Patni Confidential

DBMS/SQL+

Stored procedures/ Programs that might be called from other


procedures or programs should never do a commit or a full
rollback. If you call a procedure from your program, and this
procedure does a commit, the commit implies that all changes
made since the transaction begun, even the changes made in
other procedures or in your program code, should be stored. If
this is done, you are not able to roll back the transaction from
your program, when the control returns to it, if required.

Avoid Unnecessary Nested IFs


The following statements are equivalent. The flat structure
expresses the logic more clearly and with less code.
Nested
IF <condition1>
THEN
...
ELSE
IF <Condition2>
THEN

ELSE
IF <Condition3>
THEN

ELSE
IF <Condition4>
THEN

END IF;
END IF;
END IF;
END IF;

Flat
IF <condition1>
THEN

ELSIF <Condition2>
THEN

ELSIF <Condition3>
THEN

ELSIF <Condition4>
THEN

END IF;

Ensure Conditions in ELSIF Clauses are Exclusive

The implication of ELSIF clauses is that if one condition is fulfilled, all


others would fail -- they are mutually exclusive. The following IF
statement is a classic misuse of ELSIF clauses. It might not cause any
errors, but that would just be a matter of luck. In many cases, the
issue of exclusivity is less obviously determined.

Continuation lines should be indented.


Page 62 of

69

Patni Confidential

DBMS/SQL+
PL/SQL Standards

The following standards are to be followed when coding in PL/SQL.


They include guidelines, performance efficiency, modular organization,
control constructs, exception control - error handling, and interface input/output standards.

Each PL/SQL code should contain a Identification header (Module


Log) Please see ANNEXURE I

Declaration section is used to declare local variables and other


structures uses in the PL/SQL block.

PL/SQL code should be developed when processing with SQL


code is not possible.

For each block provides comments to explain action carried out.

For batch jobs, avoid frequent or too delayed commits.

Avoid use of unconditional branching.

Use error routines to capture runtime errors.

Each SQL statement should be enclosed in a separate PL/SQL


block so that exceptions can be trapped separately.

Use status codes whenever available in SQL statements.

e.g.
FOR EMPREC IN EMP_CURSOR
LOOP .....
(process)
END LOOP
should be used instead of
WHILE (sqlcode <> 1403)
LOOP
FETCH .....
(process)
END LOOP .

When possible, reduce the number of iterations of a PL/SQL


loop. Each loop consumes CPU, so EXIT the loop if there is no
need to continue. Also reduce processing within the loop by
Page 63 of

69

Patni Confidential

DBMS/SQL+
moving loop invariant statements outside of the loop if
possible.

If an IF statement is to be executed repeatedly, placing the most


commonly satisfied condition earlier in the IF structure may
optimize performance.

Avoid recursive programming; Iterative solutions will almost


always outperform recursive solutions.

Each function should have a single entry point and a single exit
point.

Each function should perform a single operation.

Control Constructs

The highest level control structures available in the


programming language should be used (i.e., 'While' should be
used instead of 'Go-to').

The use of the 'Go-to' statement should be avoided whenever


possible. When the 'Go-to' statement is used, it should transfer
control forward (down) in the code to a clearly marked label,
and never outside of the function in which it is used.

In condition tests, avoid testing on negative conditions,


whenever possible.

Parentheses should be used to clarify logical or arithmetic


expressions.

White space and consistent nesting should be used to increase


readability of statement content.

Nesting should be limited to three levels, whenever possible.

Exception Control - Error Handling

Exception routines should be included to identify the location


and cause of processing errors, as well as corrective action
necessary to recover from the errors.

All data elements input by the user should be verified upon input
for correct type and domain.
Page 64 of

69

Patni Confidential

DBMS/SQL+

When an interactive error is encountered, the user should be


notified of the cause of the error and the corrective action to be
taken.

The operations a user must perform to recover from an error and


return to normal processing should be kept to a minimal.

ORACLE error checking should be used, whenever possible.

Never avoid handling exception. Exceptions are considered as


abnormal and the error condition should ripple out to the driving
program. The driving or controlling program should then take
actions or report the problem to the user, the user program or to
a log. Program should never contain code like
WHEN OTHERS THEN null

General SQL Performance Tuning Guidelines

If we dont need to eliminate duplicate rows in a UNION


operation, use UNION ALL instead of UNION. This will avoid a
potentially expensive sort.

Dont use the DISTINCT operator unless we are sure that we


need it. DISTINCT will usually perform a sort.

The most important consideration in determining the join order


is to eliminate unwanted rows as early as possible. Beyond this,
both hash join and nested loops work best when joining a larger
table to a smaller table. The sort-merge join is not affected by
the order in which a larger and smaller table are joined.

Oracle will not use an index if the query condition is not


equals (!=). We need to reword the query using IN, OR, or >
to get benefit of the index. We may still need to use hints or a
column histogram to encourage Oracle to use the appropriate
index.

Avoid searching for NULL values in an indexed column. Instead,


define the column as NOT NULL with a default value.

Oracle can use indexes to resolve queries involving the LIKE


operator only if there is not a leading wildcard (%, -) in the
search string.
Page 65 of

69

Patni Confidential

DBMS/SQL+

Creating a view of a table join at a remote node can cause the


join to be executed at the remote node rather than at the
driving site. This may improve performance if conditions are
suitable.

SQL statement uses HAVING clause? Consider replacing with


WHERE clause if possible. (HAVING filters only after all the rows
have been retrieved.)

SQL Statements use NOT IN? Consider replacing with NOT EXISTS.

SQL Statement uses EXIST? Consider replacing with joins.

SQL Statement uses DISTINCT? Consider replacing with EXISTS.

Any function applied on WHERE column that is indexed? Try to


avoid, since it will cause full table scan.

Avoid using NOT on indexed columns (prevents usage of the


index by the optimizer).

SQL Statement uses ORDER BY? Check if the column is indexed


and replace with WHERE clause.

Message Handling

Error messages should be standardized. The following guidelines should


be used when writing the message:

All messages should be generated through a common procedure,


which will read a standard message table. This table should
contain all errors, warnings, and informational messages used in
the system. The type of message (error, warning, informational:
E, W, I) and the unique message number should precede each
message in the display of it on the screen or on reports.

Page 66 of

69

Patni Confidential

DBMS/SQL+

Appendix B : Tables
TITLEAUTHOR
Name
---------------------------AU_ID
TITLE_ID
AU_ORD
ROYALTYPER

Null?
-------NOT NULL

Type
--- ---CHAR(11)
CHAR(6)
NUMBER
NUMBER

Key
-----Foreign Key
Foreign Key

Type
---------CHAR(6)
VARCHAR2(80)
CHAR(12)
CHAR(4)
NUMBER
NUMBER
NUMBER
NUMBER
VARCHAR2(200)
DATE

Key
----Primary Key

Constraint names:
FK_TITLEAUTHOR_AU_ID
FK_TITLEAUTHOR_TITLE_ID
TITLES
Name
-------------------TITLE_ID
TITLE
TYPE
PUB_ID
PRICE
ADVANCE
ROYALTY
YTD_SALES
NOTES
PUBDATE

Null?
------NOT NULL
NOT NULL
NOT NULL
NOT NULL

Foreign Key

Constraint names:
PK_TITLES_TITLE_ID
FK_TITLES_PUB_ID

Page 67 of

69

Patni Confidential

DBMS/SQL+

ROYSCHED
Name
-----------------TITLE_ID
LORANGE
HIRANGE
ROYALTY

Null?
-------NOT NULL

Type
-------CHAR(6)
NUMBER
NUMBER
NUMBER

Key
---Foreign Key

Constraint names:
FK_ROYSCHED_TITLE_ID
SALES
Name
-------------------STOR_ID
ORD_NUM
S_DATE
QTY
PAYTERMS
TITLE_ID

Null?
----------NOT NULL
NOT NULL
NOT NULL
NOT NULL
NOT NULL
NOT NULL

Type
-------CHAR(4)
VARCHAR2(20)
DATE
NUMBER
VARCHAR2(12)
CHAR(6)

Key
---Foreign Key

Type
-------CHAR(4)
VARCHAR2(40)
VARCHAR2(40)
VARCHAR2(20)
CHAR(2)
CHAR(5)

Key
---Primary Key

Foreign key

Constraint names:
FK_SALES_STOR_ID
FK_SALES_TITLE_ID
STORES
Name
------------------------STOR_ID
STOR_NAME
STOR_ADDRESS
CITY
STATE
ZIP

Null?
-------NOT NULL

Constraint names:
PK_STORES_STOR_ID

Page 68 of

69

Patni Confidential

DBMS/SQL+
DISCOUNTS
Name
---------------------DISCOUNTTYPE
STOR_ID
LOWQTY
HIGHQTY
DISCOUNT

Null?
--------NOT NULL

Type
-------VARCHAR2(40)
CHAR(4)
NUMBER
NUMBER
NUMBER

Key
---Foreign Key

Constraint names:
FK_DISCOUNTS_STOR_ID
PUBLISHERS
Name
------------------PUB_ID
PUB_NAME
CITY
STATE

Null?
-------NOT NULL
NOT NULL

Type
------- ----CHAR(4)
VARCHAR2(40)
VARCHAR2(20)
CHAR(2)

Key
---Primary Key

Constraint names:
PK_PUB_PUB_ID
AUTHORS

Name
------------------AU_ID
AU_LNAME
AU_FNAME
PHONE
ADDRESS
CITY
STATE
ZIP
CONTRACT

Null?
--------NOT NULL
NOT NULL
NOT NULL
NOT NULL

Type
--- -------CHAR(11)
VARCHAR2(40)
VARCHAR2(20)
CHAR(12)
VARCHAR2(20)
VARCHAR2(20)
CHAR(2)
CHAR(5)
CHAR(1)

NOT NULL

Key
---Primary Key

Constraint names:
PK_AUTHORS_AU_ID

Page 69 of

69

Patni Confidential

Вам также может понравиться