Coding Rules
Coding Rules
programming guidelines
Databases are the heart and soul of many of the recent enterprise
applications and it is very essential to pay special attention to
database programming. There are many occasions where database
programming is overlooked, thinking that it's something easy and can
be done by anyone. This is wrong. If you don't use database specialists
during your development cycle, database often ends up becoming the
performance bottleneck. Below are some of the database programming
best practices
Also avoid searching with not equals operators (<> and NOT) as
they result in table and index scans.
SELECT MIN(Salary)
FROM Employees
WHERE EmpID IN
(
SELECT TOP 2 EmpID
FROM Employees
ORDER BY Salary Desc
)
SELECT MIN(Salary)
FROM
(
SELECT TOP 2 Salary
FROM Employees
ORDER BY Salary Desc
) AS A
• Do not prefix your stored procedure names with 'sp_'. The prefix
sp_ is reserved for system stored procedure that ship with SQL
Server. Whenever SQL Server encounters a procedure name
starting with sp_,, it first tries to locate the procedure in the
master database, then looks for any qualifiers (database, owner)
provided, then using dbo as the owner. So, you can really save
time in locating the stored procedure by avoiding sp_ prefix. But
there is an exception! While creating general purpose stored
procedures that are called from all your databases, go ahead and
prefix those stored procedure names with sp_ and create them in
the master database.
• Views are generally used to show specific data to specific users
based on their interest. Views are also used to restrict access to
the base tables by granting permission on only views. Yet
another significant use of views is that, they simplify your
queries. Incorporate your frequently required complicated joins
and calculations into a view, so that you don't have to repeat
those joins/calculations in all your queries, instead just select
from the view.
• Use char data type for a column, only when the column is non-
nullable. If a char column is nullable, it is treated as a fixed
length column in SQL Server 7.0+. So, a char(100), when NULL,
will eat up 100 bytes, resulting in space wastage. So, use
varchar(100) in this situation. Of course, variable length
columns do have a very little processing overhead over fixed
length columns. Carefully choose between char and varchar
depending up on the length of the data you are going to store.
Now insert a customer into the table whose name is Tony Blair,
without a middle name:
INSERT INTO Customers
(FirstName, MiddleName, LastName)
VALUES ('Tony',NULL,'Blair')
Now run the above INSERT statement. You get the following error
from SQL Server:
UPDATE dbo.Orders
SET OrderStatus = @ORDER_PENDING
WHERE OrdDate < @ORDER_DATE