Database Coding Guidelines
Database Coding Guidelines
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
Naming Conventions
General Guidelines
1.
2.
3.
4.
5.
6.
7.
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
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
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
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_
Note:
This approach strongly reinforces the fact that this variable "represents" a column in this
program.
Example
-
Bad code:
CREATE TABLE ORDER (NAME VARCHAR2(20), VALUE NUMBER);
Good code:
Reserved keyword
: Procedure name
F_
: Function name:
T_
: Type name
: View name
P_
: Procedure name
Example:
F_
: Function name:
Example:
: Type name
Example:
: View name
Example:
IX_
: Index name
Example:
: Primary key
Example:
FK_
: Foreign Key
Example:
ALTER TABLE INVOICE_HEADER ADD CONSTRAINT TENANTFK_EPTNT_FK FOREIGN KEY
(TENANT_FK) REFERENCES EP_TENANT (GUID);
TR_
: Trigger name
Example:
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
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
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.
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
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
Tagging of Package
Coding Style
1.
2.
3.
4.
5.
6.
7.
8.
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.