PL/SQL Best Practices
In enterprise data-driven applications, the quality of SQL statements used in stored procedures plays a vital role in applications' performance. Bad SQL statements can break the application. In this article, I discuss some best practices for using PL/SQL.
SQL Best Practices
The key aspect and purpose of coding standards have always been to make development & maintenance easier for developers. Best Practices make the job even more accessible. Coding standards must address several areas of the development process to satisfy the requirement for making maintenance easier for developers.
Identifiers
Case
- Use all Pascal cases for table and view names
- Use Pascal case for column names
- Use camel case for variables
- Use Pascal case for the stored procedure name
- Column names with white spaces between two words should be written within the brackets[]. E.g., [Student Name]
- Avoid using keywords for columns or table names.
Prefixes and suffixes
Use the following standard prefixes for database objects,
| Object type | Prefix | Example |
| Primary key Clustered | pkc_ | pkc_MyTable__Column |
| Primary key Non-clustered | pkn_ | pkn_TB_TABLE__ColumnList |
| Index Clustered | ixc_ | ixc_TS2_TABLE__Column |
| Index Non-clustered | ixn_ | ixn_TB_TABLE__ColumnList |
| Foreign key | fk_ | fk_THIS_TABLE__ColumnB__to__TB_PKEY_TABLE__ColumnA |
| Unique Constraint | unq_ | unq_TB_TABLE__Column_List |
| Check Constraint | chk_ | chk_TB_TABLE__Column |
| Column Default | dft_ | dft_TB_TABLE_ColumnList |
| Passed Parameter | @p | @pPassedVariableName |
| Local Variable | @ | @VariableName |
| Table | tbl_, *_ | tbl_TableName |
| Index | idx_ | idx_IndexName |
| Function | fn_ | fn_FuntionName |
| View | vw_ | vw_QuestionResult |
| Trigger | tr_ | tr_TriggerName |
| Sequence | seq_ | seq_SequenceName |
| User-Defined Scalar Function | ufs_ | ufs_GetOccBucketValue |
| User-Defined Table Function | uft_ | uft_GetOcc |
| Stored Procedure | usp_ | usp_GetId, usp_InsertCase, usp_UpdateCase, usp_InsertUpdate, usp_AnalystTestAllocationRpt Note :Not use sp_ as it is for system stored procedures. |
Use the following standard prefixes for scripts,
| Script type | Prefix | Example |
| Stored procedure script | proc_ | proc_Calendar.sql |
| Schema script | def_ | def_Calendar.sql |
| Conversion script | conv_ | conv_Schedule.sql |
| Rollback script | rbk_ | rbk_Schedule.sql |
Save all scripts using the .sql extension. Use the full table name if a column references an Id in another table.
For example, use TitleId in table TB_AUTHOR to reference column Id or TitleId in table TB_TITLE.
Use all lowercase for system names, statements, variables, and functions,
- Reserved words (begin, end, table, create, index, go, identity).
- Built-in types (char, int, varchar).
- System functions and stored procedures (cast, select, convert).
- System and custom extended stored procedures (xp_cmdshell).
- System and local variables (@@error, @@identity, @value).
- References to system table names (syscolumns).
Stored Procedures (and other DML scripts)
Use the following outline for creating stored procedures,
USE{database name}
IF OBJECT_ID('{owner}.{procedure name}', 'IsPRocedure') IS NOT NULL
BEGIN
DROP PROCEDURE {owner}.{procedure name};
END
GO
CREATE PROCEDURE {owner}.{procedure name}
[{parameter} {data type}]
as
/*******************************************************************
* PROCEDURE: {procedure name}
* PURPOSE: {brief procedure description}
* NOTES: {special set up or requirements, etc.}
* CREATED: {developer name} {date}
* MODIFIED
* DATE AUTHOR DESCRIPTION
*-------------------------------------------------------------------
* {date} {developer} {brief modification description}
*******************************************************************/
DECLARE {variable name} {data type};
-- Add more variables as needed
SET {session variables}
-- Add more session variables as needed
{initialize variables};
{body of procedure};
RETURN;
EXCEPTION
WHEN {error type} THEN
{error handler};
END;
GO
Using the above SQL syntax, create a stored procedure in a SQL database. USE a statement to switch to the specified database and then check if the stored procedure already exists; if it does, drop it. Then CREATE PROCEDURE statement is used to create a new stored procedure, which is given a name, an owner, and a list of parameters; their data types are also provided.
Then DECLARE statement creates local variables, and the SET statement sets variables as a session. In the next step, it initializes variables, executes defined SQL statements, and finishes by including a RETURN statement and an EXCEPTION block that is used to catch and handle any errors that may occur while the procedure is running.
Formatting
Use single-quote characters to delimit strings. Nest single quotes to express a single quote or apostrophe within a string,
set @Example = 'Bills example'
Use parenthesis to increase readability, especially when working with branch conditions or complicated expressions,
if((select 1 where 1 = 2) isnot null)
Use BEGIN and END blocks only when multiple statements are present within a conditional code segment.
Whitespace
- Use one blank line to separate code sections.
- Do not use white space in identifiers
Comments
- Use single-line comment markers where needed (--). Reserve multi-line comments (/*..*/) for blocking out sections of code.
- Comment only where the comment adds value. Don't over-comment, and try to limit comments to a single line. An overuse of multi-line comments may indicate a design that is not elegant. Choose identifier names that are self-documenting whenever possible.
DML Statements (select, insert, update, delete)
- A correlated subquery using "exists" or "not exists" is preferred over the equivalent "in" or "not in" subquery due to performance degradation potential in some cases using "not in".
- Avoid the use of cross-joins if possible.
When a result set is unnecessary, use syntax that does not return a result set.
IF EXISTS (SELECT 1
FROM dbo.TB_Location
WHERE Type = 50)
BEGIN
IF ((SELECT COUNT(Id) FROM dbo.TB_Location WHERE Type = 50) > 0)
END
- If more than one table is involved in a from clause, each column name must be qualified using either the complete table name or an alias. The alias is preferred.
-
Always use column names in an "order by" clause. Avoid positional references.
Select
Do not use a select statement to create a new table (by supplying an into a table that does not exist).
Always supply a friendly alias to the client when returning a variable or computed expression.
SELECT @identity AS ExamId,
(@pointsReceived/ @pTotalPoints)AS Average
Opt for a more descriptive alias.
SELECT @identity AS UserId
--is preferred over
SELECT @identity AS Id
Use the following outline for select statements. Each column in the select list should appear on its line. Each unrelated constraint within the where clause should appear on its line.
SELECT
t.TaskId
FROM Task.dbo.TASK t
INNER JOIN Task.dbo.ENROLLMENT et
ON t.TaskId = et.TaskId
WHERE et.MemberId = @pMemberId
AND (
(t.Due_DT <= @pStartDate)
OR (t.DueDaTe >= @pEndDate)
OR (et.FLAG = 1)
)
Inserts
Always list column names within an insert statement. Never perform inserts based on column position alone.
Do not call a stored procedure during an insert, as in,
INSERT INTO SUBSCRIBE
EXECUTE SUBSCRIBERS_BUILDNEW_SYSTEM;
Use the following outline to insert statements moving values or variables into a single row. Place each column name and value on its line and indent both to match as shown.
Example,

Vijay Pratap SinghPosted Jan 12, 2023, 4:55 AM
Thanks for sharing
Hoang TuanPosted Oct 10, 2019, 2:01 AM
Very helpful, thank you very much.
Pankajkumar PatelPosted Sep 18, 2019, 11:37 PM
Nice article
Vikas Kumar GargPosted Jan 16, 2015, 12:20 PM
thanks for sharing these important points to help in coding.
Chirag SolankiPosted Jun 27, 2012, 1:32 AM
thx. great article.
Sudhakar ChaudharyPosted Jun 18, 2012, 11:30 AM
nice article. thanks for sharing.
Anil KumarPosted Jun 18, 2012, 8:18 AM
tnx for sharing :)