Sunteți pe pagina 1din 23

Database Coding Guidelines V1.

Table of Contents
Introduction of database coding standards .................................................................................................. 3
Implementing formatting and coding standards has the following advantages for database SQL
development ................................................................................................................................................. 3
Critical elements of PL/SQL - Best Practices ................................................................................................. 3
Naming Conventions ..................................................................................................................................... 4
General Guidelines .................................................................................................................................... 4
Naming Conventions for variables ............................................................................................................ 6
Database Object Naming Conventions ..................................................................................................... 8
Best practices for database object naming conventions. ...................................................................... 9
Defining data type and length .................................................................................................................... 13
Procedure Best Practice ........................................................................................................................... 14
Functions Best Practice ............................................................................................................................... 16
Exception Handling ..................................................................................................................................... 17
Tag module END statements with module names ..................................................................................... 19
Coding Style ................................................................................................................................................ 20
Coding Formation Rules .......................................................................................................................... 20
Bulk Operations........................................................................................................................................... 21
Stop guessing and start testing. .................................................................................................................. 23

Introduction of database coding standards


This document defines the database coding standards and guidelines that will be used by
developers.

Implementing formatting and coding standards has the following


advantages for database SQL development
1. Well formatted code is easier to read, analyze and maintain.
2. Developers do not have to think about where to search for something - it is already
defined.
3. The developers do not have to think about how to name something - it is already
defined.
4. The code has a structure that makes it easier to avoid making errors.
5. The code is more efficient with regards to performance and organization of the whole
application
6. The code is more modular and thus easier to use for other applications.

Critical elements of PL/SQL - Best Practices


1.
2.
3.
4.
5.
6.
7.
8.

Consistent naming conventions for objects and variables


Unit test PL/SQL programs
Optimize SQL in PL/SQL programs
Write readable, maintainable code
Use of reserved keywords
Defining proper data type and length to a variable and column
Aim for a single point of definition (a SPOD).
Packages specification and body

Naming Conventions
General Guidelines
1.
2.
3.
4.
5.
6.
7.

Do not use names with a leading numeric character.


Always choose meaningful and specific names.
Avoid using abbreviations unless the full name is excessively long.
Avoid long abbreviations. Abbreviations should be shorter than 5 characters.
Avoid adding redundant or meaningless prefixes and suffixes to identifiers.
Always use the same names for elements with the same meaning.
Do not use reserved words as names.
List of reserved keywords
ACCESS

ELSE

MODIFY

START

ADD

EXCLUSIVE NOAUDIT

ALL

EXISTS

NOCOMPRESS SESSION

ALTER

FILE

NOT

SET

AND

FLOAT

NOTFOUND

SHARE

ANY

FOR

NOWAIT

SIZE

ARRAYLEN FROM

NULL

SMALLINT

AS

GRANT

NUMBER

SQLBUF

ASC

GROUP

OF

SUCCESSFUL

AUDIT

HAVING

OFFLINE

SYNONYM

SELECT

BETWEEN IDENTIFIED ON

SYSDATE

BY

IMMEDIATE ONLINE

TABLE

CHAR

IN

THEN

CHECK

INCREMENT OR

TO

CLUSTER

INDEX

ORDER

TRIGGER

COLUMN

INITIAL

PCTFREE

UID

COMMENT INSERT

PRIOR

UNION

COMPRESS INTEGER

PRIVILEGES

UNIQUE

OPTION

CONNECT INTERSECT PUBLIC

UPDATE

CREATE

INTO

RAW

USER

CURRENT

IS

RENAME

VALIDATE

DATE

LEVEL

RESOURCE

VALUES

ADMIN

CURSOR

FOUND

MOUNT

AFTER

CYCLE

FUNCTION

NEXT

ALLOCATE

DATABASE

GO

NEW

ANALYZE

DATAFILE

GOTO

NOARCHIVELOG

ARCHIVE

DBA

GROUPS

NOCACHE

ARCHIVELOG

DEC

INCLUDING

NOCYCLE

AUTHORIZATION DECLARE

INDICATOR

NOMAXVALUE

AVG

DISABLE

INITRANS

NOMINVALUE

BACKUP

DISMOUNT INSTANCE

NONE

BEGIN

DOUBLE

INT

NOORDER

BECOME

DUMP

KEY

NORESETLOGS

BEFORE

EACH

LANGUAGE

NORMAL

BLOCK

ENABLE

LAYER

NOSORT

BODY

END

LINK

NUMERIC

CACHE

ESCAPE

LISTS

OFF

CANCEL

EVENTS

LOGFILE

OLD

CASCADE

EXCEPT

MANAGE

ONLY

CHANGE

EXCEPTIONS MANUAL

OPEN

CHARACTER

EXEC

MAX

OPTIMAL

CHECKPOINT

EXPLAIN

MAXDATAFILES OWN

CLOSE

EXECUTE

MAXINSTANCES PACKAGE

COBOL

EXTENT

MAXLOGFILES

PARALLEL

For more information please follow


https://docs.oracle.com/cd/B10501_01/appdev.920/a42525/apb.htm

Naming Conventions for variables


It is highly recommended that we should follow the naming conventions listed in the following
table to make the variables obvious in PL/SQL programs:
1. Variable name should start with prefix as below mention table
PREFIX
v_
n_
t_
r_
d_
b_

DATA TYPE
VARCHAR2
NUMBER
TABLE
ROW
DATE
BOOLEAN

Example
DECLARE v_str varchar2 (20);
DECLARE n_cnt number (20);
DECLARE d_crdt date;
DECLARE b_val boolean;
DECLARE TYPE T_EMPLOYEE_TYPE IS TABLE OF emp.empno%TYPE;
t_employees t_employee_type:= t_employee_type (7369, 7698);
2. Cursor variable start with cur_
Example
DECLARE cursor cur_<name> is <sql>;
3. Dont start variables name with number or special char
Example
-

Bad code
DECLARE 123_str varchar2 (30);
Variable
Starting with Number

Good code
DECLARE v_str varchar2 (30);
Variable

4. Never use quoted identifiers


Starting with v_
Reason:
Quoted identifiers make your code hard to read and maintain.

Example:
-

Bad code
DECLARE sal+comm NUMBER (10);
BEGIN
<SQL>;
END;
Good code
DECLARE n_sal_comm NUMBER (10);
BEGIN
<SQL>;
END;

Variable
quoted identifier

Variable
without quoted_

5. Never initialize variables with NULL.


Reason:
Variables are initialized to NULL by default
6. Use %TYPE when a variable represents a column
Reason
Changing the size of the database column ENAME in the EMP table from
VARCHAR2 (10) to VARCHAR2 (20) will result in an error within your code whenever a
value larger than 10 bytes is read. This can be avoided using anchored declarations
Example:
Variable
Bad Code
not representing column
DECLARE v_ename VARCHAR2 (10);
BEGIN
SELECT e.ename INTO v_ename
Variable
FROM EMP E
represent column
WHERE
END;
Good code
DECLARE v_ename emp.ename%TYPE;
BEGIN
SELECT e.ename INTO v_ename
FROM EMP E
WHERE
END;

Note:
This approach strongly reinforces the fact that this variable "represents" a column in this
program.

Database Object Naming Conventions


1. Do not use names with a leading numeric character
2. Object length should be less than 28 character.
3. Object name should not be reserve keywords (SELECT, INSERT, PACKAGE, FUNCTION,
etc.)
4. Add a comment to the database dictionary for every column
5. Define proper length of object or field (If we don't specify a precision, as in number (18,
0), Oracle supports up to 38 digits of precision. If we don't need this precision, we are
wasting memory)
Missing Length

Example
-

Bad code:
CREATE TABLE ORDER (NAME VARCHAR2(20), VALUE NUMBER);

Good code:

Reserved keyword

CREATE TABLE ORDER (EMP_NAME VARCHAR2(20), VALUE


NUMBER(18));

Best practices for database object naming conventions.


Prefix with object name .
P_

: Procedure name

F_

: Function name:

T_

: Type name

SQ_ : Sequence name


TR_ : Trigger name
V_

: View name

IX_ : Index name


PK_ : Primary key
UK_ : unique Key,
_FK : Foreign Key(Suffix)
AK_: Alternate Key
CK_: Check Constraint
_GN : Generated Objects (Suffix)
GT_ : Global Temp Table
LT_ : Local Temp Table

P_

: Procedure name

Example:

CREATE PROCEDURE P_CURRENCY_CONVERSION


AS
BEGIN
<SQL>;
END proc_currency;

F_

: Function name:

Example:

CREATE FUNCTION F_CURRENCY_CONVERSION (n_amount IN NUMBER)


RETURN NUMBER
AS
BEGIN
<SQL>;
END currency_conversion;
T_

: Type name

Example:

CREATE TYPE T_INVOICE_HEADER AS OBJECT


(
ID NUMBER (18, 0),
INVOICE_NAME VARCHAR2 (20)
);
SQ_ : Sequence name
Example:

CREATE SEQUENCE SQ_INVOICE_HEADER


START WITH 1
INCREMENT BY 1
-----;
V_

: View name

Example:

CREATE VIEW V_INVOICE_HEADER


AS
<SQL>;

IX_

: Index name

Example:

CREATE INDEX IX_TENANT_EPTNT ON EP_TENANT (GUID, ID);


PK_

: Primary key

Example:

ALTER TABLE EP_TENANT ADD CONSTRAINT PK_TENANT_GUID PRIMARY KEY (GUID);

UK_ : unique Key


Example:

CREATE UNIQUE INDEX UK_TENANT_ID ON EP_TENANT (ID);

FK_

: Foreign Key

Example:
ALTER TABLE INVOICE_HEADER ADD CONSTRAINT TENANTFK_EPTNT_FK FOREIGN KEY
(TENANT_FK) REFERENCES EP_TENANT (GUID);

CK_: Check Constraint


Example:
ALTER TABLE COUNTRY_CODE ADD CONSTRAINT CK_COUNTRY_CD CHECK
(COUNTRY_CODE IN (USA,AUS,IND));

_GN : Generated Objects (Suffix)


Example:

CREATE PROCEDURE P_EP_TENANT_GN


AS
BEGIN
<SQL>;
END generated_tenant_proc;

GT_: Global Temp Table


Example:

CREATE GLOBAL TEMPORARY TABLE GT_INVOICE_HEADER (


ID
NUMBER (18, 0),
INVOICE_NAME VARCHAR2 (20)
)
ON COMMIT PRESERVE ROWS;

LT_ : Local Temp Table


Example:

CREATE GLOBAL TEMPORARY TABLE LT_INVOICE_HEADER (


ID
NUMBER (18, 0),
INVOICE_NAME VARCHAR2 (20)
)
ON COMMIT DELETE ROWS;

TR_

: Trigger name

Example:

CREATE TRIGGER TR_INVOICE_HEADER_DEL


AFTER DELETE ON INVOICE_HEADER
AS
BEGIN
<SQL>;
END invoice_rec_del_trg;

Defining data type and length


1. Define proper length of variable or column (If we don't specify a precision, as in number
(18, 0), Oracle supports up to 38 digits of precision. If we don't need this precision, we
are wasting memory)
Example.
DECLARE n_str NUMBER (18, 0);
2. Avoid implicit datatype conversions
3. Avoid using CHAR data type
Reason:
CHAR is a fixed length data type which should only be used when appropriate.
CHAR columns/variables are always filled to the specified length, this may lead to sideeffects.
4. Match datatypes to computational usage
5. Avoid using the LONG and LONG RAW data types(Use LOB,BFILE datatype)
Reason:
LONG and LONG RAW data type may not support some database or release.
6. Try to use boolean data type for values with dual meaning.
Reason:
The use of TRUE and FALSE clarifies that this is a Boolean value and makes the code
easier to read.
-

Bad code
DECLARE n_bigger NUMBER (1);
BEGIN
IF v_nefwile < v_oldFile
THEN
n_bigger := 1;
ELSE
n_bigger:= 0;
END IF;
END;

Variable
numeric datatype _

Good code
DECLARE n_bigger BOOLEAN;
BEGIN
IF n_newFIle < n_oldFile
THEN
n_bigger:= TRUE;
ELSE
n_bigger:= FALSE;
END IF;
END;

Variable
boolean datatype

Procedure Best Practice


1. Avoid using RETURN statements in a PROCEDURE.
Reason:
Use of the RETURN statement is legal within a procedure in PL/SQL, but it is very
similar to a GOTO, which means you end up with poorly-structured code that is hard to
debug and maintain.
A good general rule to follow as you write your PL/SQL programs is: "one way in and one
way out". In other words, there should be just one way to enter or call a program, and
there should be one way out, one exit path from a program (or loop) on successful
termination. By following this rule, you end up with code that is much easier to trace,
debug, and maintain
2. Try to remove unused parameters or modify code to use the parameter.
Reason:
This can occur as the result of changes to code over time, but we should make
sure that this situation does not reflect a problem in your code. We should go through
your programs and remove any part of your code that is no longer used.
3. Avoid unhandled exceptions in procedure.
Reason:
We should review the code to confirm this behavior. If we are raising an error in
a program, then we are clearly predicting a situation in which that error will occur. We
should consider including a handler in our code for predictable errors, allowing for a
graceful and informative failure. After all, it is much more difficult for an enclosing block
to be aware of the various errors you might raise and more importantly, what should be
done in response to the error. The form that this failure takes does not necessarily need
to be an exception. When writing functions, we may well decide that in the case of

certain exceptions, you will want to return a value such as NULL, rather than allow an
exception to propagate out of the procedure.
4. Use named notation to clarify, self-document, and simplify module calls.
Example
CREATE PROCEDURE P_CURRENCY_CONVERSION (n_invoice_id NUMBER,
d_invoice_dt date)
AS
BEGIN
<SQL>;
END proc_currency;
Calling procedure
Bad Code calling
BEGIN
P_CURRENCY_CONVERSION (1, sysdate);
END
Calling procedure
Good code calling
without named notation
BEGIN
P_CURRENCY_CONVERSION (n_invoice_id => 1, d_invoice_dt =>
sysdate);
END;
5. Always add the name of the program unit to its end keyword
Example
CREATE PROCEDURE P_CURRENCY_CONVERSION
AS
BEGIN
<SQL>;
END proc_currency;

Calling procedure
with named notation

Adding a tag
procedure

Functions Best Practice


1.
2.
3.
4.
5.

Always make the RETURN statement the last statement of our function.
Avoid unhandled exceptions in functions.
Never return NULL from Boolean functions.
Avoid defining variables that are not used.
Try to remove unused parameters or modify code to use the parameter.
Reason:
This can occur as the result of changes to code over time, but we should make
sure that this situation does not reflect a problem in your code. We should go through
your programs and remove any part of your code that is no longer used.

6. Limit functions to a single RETURN statement in the execution section.

Reason:
A good general rule to follow as you write your PL/SQL programs is: "one way in
and one way out." In other words, there should be just one way to enter or call a
program (there is; you don't have any choice in this matter). And there should be one
way out, one exit path from a program (or loop) on successful termination. By following
this rule, we end up with code that is much easier to trace, debug, and maintain.
For a function, this means you should think of the executable section as a funnel; all the
lines of code narrow down to the last executable statement:
7. Never use OUT parameters to return values from a function.
Reason:
A function should return all its data through the RETURN clause. Having an OUT
parameter prohibits usage of a function within SQL statements.
Example:
CREATE FUNCTION F_GET_CUSRRENCY (n_acc_no IN NUMBER)
RETURN NUMBER
IS
n_acc_bal NUMBER (11, 2);
BEGIN
SELECT balance INTO n_acc_bal
FROM accounts
WHERE account_id = n_acc_no;
RETURN (n_acc_bal);
END fun_get_currency;

Exception Handling
1. Never assign predefined exception names to user defined exceptions.
Examples: Predefine exceptions
Exception

Oracle Error

SQLCODE Value

ACCESS_INTO_NULL

ORA-06530

-6530

CASE_NOT_FOUND

ORA-06592

-6592

COLLECTION_IS_NULL

ORA-06531

-6531

CURSOR_ALREADY_OPEN

ORA-06511

-6511

DUP_VAL_ON_INDEX

ORA-00001

-1

INVALID_CURSOR

ORA-01001

-1001

INVALID_NUMBER

ORA-01722

-1722

LOGIN_DENIED

ORA-01017

-1017

NO_DATA_FOUND

ORA-01403

+100

NOT_LOGGED_ON

ORA-01012

-1012

PROGRAM_ERROR

ORA-06501

-6501

ROWTYPE_MISMATCH

ORA-06504

-6504

SELF_IS_NULL

ORA-30625

-30625

STORAGE_ERROR

ORA-06500

-6500

SUBSCRIPT_BEYOND_COUNT ORA-06533

-6533

SUBSCRIPT_OUTSIDE_LIMIT

ORA-06532

-6532

SYS_INVALID_ROWID

ORA-01410

-1410

TIMEOUT_ON_RESOURCE

ORA-00051

-51

TOO_MANY_ROWS

ORA-01422

-1422

VALUE_ERROR

ORA-06502

-6502

ZERO_DIVIDE

ORA-01476

-1476

2. Avoid dead code in our programs.


3. Avoid unhandled exceptions
4. Never handle unnamed exceptions using the error number.

Example:
- Bad code
BEGIN

<SQL>;
EXCEPTION
WHEN OTHERS
THEN
IF SQLCODE = -2291
THEN
<SQL>;
END IF;
END;
Good code
DECLARE ex_parent_missing EXCEPTION;
PRAGMA EXCEPTION_INIT (ex_parent_missing,-2291);
BEGIN
<SQL>;
EXCEPTION
WHEN ex_parent_missing
THEN
<SQL>;
END;

Unnamed Exception

Named Exception

5. Handle exceptions that cannot be avoided but can be anticipated.


Example:
CREATE OR REPLACE FUNCTION F_BOOK_TITLE ( v_isbn_in IN book.isbn%TYPE)
RETURN book.title%TYPE
IS
v_ title book.title%TYPE;
BEGIN
SELECT title INTO v_title
FROM book
WHERE isbn =v_isbn_in;
RETURN v_rec.title;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
RETURN NULL;
END;

Tag module END statements with module names


Every program (indeed, every block of code; Self-document using block and loop labels. ) has an
END statement. We should append the name of the program to the end statement:
Example:
CREATE OR REPLACE PACKAGE BODY PKG_EXPAND_ALL_INVOICE
IS
PROCEDURE P_EXPAND_SINGLE_CLICK (n_invoice_id number)
IS
BEGIN
<SQL>;
END proc_single_click;
PROCEDURE P_EXAPAND_ALL_INVO (n_invoice_id number)
IS
BEGIN
Tagging of sub program
<SQL>;
END proc_all_exapand;
END invo_expand;

Tagging of Package

Coding Style
1.
2.
3.
4.
5.
6.
7.
8.

Use white space to improve readability.


Use a consistent commenting style that is low in maintenance and high in readability.
Comment only to add value.
Use consistent formats for different constructs of the language, including SQL
statements.
Distinguish between the SQL syntax and your application constructs. Put all keywords to
the left, application elements to the right.
Separate the distinct clauses with white space.
Identify the driving table while using joins.
Use meaningful aliases, especially for tables.

Coding Formation Rules


Rule
1
2
3
4
5
6
7

Description
Keywords are written uppercase, names are written in lowercase.
3 space indention.
One command per line.
Keywords THEN, LOOP, IS, ELSE, ELSIF, WHEN on a new line.
Commas in front of separated elements.
Call parameters aligned, operators aligned, values aligned.
SQL keywords are right-aligned within a SQL command.

Example

Bulk Operations
Use BULK OPERATIONS (BULK COLLECT, FORALL) whenever we have to repeatedly execute a
DML or SELECT command for more than 4 times.
Reason:
Context switches between PL/SQL and SQL are extremely costly. (Depending on the
PLSQL_OPTIMIZE_LEVEL parameter this will be done automatically.)
Example
-

Bad Code
DECLARE TYPE T_EMPLOYEE_TYPE IS TABLE OF emp.empno%TYPE;
t_employees t_employee_type:= t_employee_type (7369, 7698, 7839,
7844, 7876);
BEGIN
FOR i IN 1...t_employees. COUNT ()
Without Bulk
LOOP
Operation

UPDATE EMP
SET sal = sal * 1.1
WHERE empno = t_employees (i);
END LOOP;
-

END;
Good Code
DECLARE TYPE T_EMPLOYEE_TYPE IS TABLE OF emp.empno%TYPE;
t_employees t_employee_type:= t_employee_type (7369, 7698, 7839,7844,7876);
BEGIN
FORALL i IN 1...t_employees. COUNT ()
UPDATE EMP
SET sal = sal * 1.1
With Bulk
WHERE empno = t_employees (i);
Operation
END;

Miscellaneous
1. Never EXIT or RETURN from WHILE and FOR loops
2. Avoid Not keyword while writing query(Not IN, Not LIKE, Not Exist)
3. Avoid BEFORE TRIGGER FOR VALIDATIONS. Use BEFORE triggers ONLY to modify :NEW
value
4. Avoid writing the redundant code
5. Remove unnecessary objects from schemas which not require for current patch
6. Express complex expressions unambiguously using parentheses
7. Adopt meaningful naming conventions for source files
8. Maintain the statistics of objects
9. Try to avoid loops instead of use bulk operation
10. Try to use CASE rather than DECODE
Reason:
DECODE is an old function that has been replaced by the easier-to understand
and more common CASE function. Contrary to the DECODE statement CASE may also be
used directly within PL/SQL.
11. Always use COALESCE instead of NVL, if parameter 2 of the NVL function is a function
call or a SELECT statement.

Reason:
The NVL function always evaluates both parameters before deciding which one
to use. This can be harmful if parameter 2 is either a function call or a select statement,
as it will be executed regardless of whether parameter 1 contains a NULL value or not.
The COALESCE function does not have this drawback.

Stop guessing and start testing.

S-ar putea să vă placă și