Original translated from: http://www.codeproject.com/cs/database/sqldodont.asp
SQL Server do's and Don's TS
So, you are now the leader of a SQL Server based project and this is your first one, perhaps migrating from access. or maybe you have performance problems with your SQL Server and don't know what to do next. or maybe you simply want to know of some design guidelines for solutions using SQL Server and designing database access layers (DAL): This article is for you.
Even if you are not using SQL Server, most of these design guidelines apply to other DBMS, too: Sybase is a very similar environment for the programmer, and Oracle designs may benefit from this too. I won't show here how to use specific T-SQL tricks, nor won't give you miracle solutions for your SQL server problem. this is by no means a complete, closed issue. what I intend to do is give you some advices for a sound design, with lessons learned through the last years of my life, seeing the same design errors being done again and again.
Do know your tools.
Please, don't underestimate this tip. this is the best of all of those you'll see in this article. you 'd be surprised of how many SQL Server programmers don't even know all T-SQL commands and all of those valid tools SQL Server has.
"What? I need to spend a month learning all those SQL commands I'll never use ??? "You might say. no, you don't need. but spend a weekend at msdn and browse through all T-SQL commands: the mission here is to learn a lot of what can and what can't be done. and, in the future, when designing a query, you'll remember "Hey, there's this command that does exactly what I need ", and then you'll refer again to msdn to see its exact syntax.
In this article I'll assume that you already know the T-SQL syntax or can find about it on msdn.
Don't use cursors
Let me say it again: Don't use cursors. they shoshould be your preferred way of killing the performance of an entire system. most Beginners use cursors and don't realize the performance hit they have. they use memory; they lock tables in weird ways, and they are slow. worst of all, they defeat most of the performance optimization your DBA can do. did you know that everyFETCH
Being executed has about the same performance of executingSELECT
? This means that if your cursor has 10,000 records, it will execute about 10,000SELECT
S! If you can do this in a coupleSELECT
,UPDATE
OrDELETE
, It will be much faster.
Beginner SQL programmers find in cursors a comfortable and familiar way of coding. Well, unfortunately this lead to bad performance. The whole purpose of SQL is specifyingWhatYou want, notHowIt shoshould be done.
I 've once rewritten a cursor-based stored procedure and substituted some code for a pair of traditional SQL queries. the table had only 100,000 records and the stored procedure used to take 40 minutes to process. you shoshould see the face of the poor programmer when the new stored procedure took 10 seconds to run!
Sometimes it's even faster to create a small application that gets all the data, proccess it and update the server. T-SQL was not done with loop Performance in mind.
If you are reading this article, I need to mention: there is no good use for cursors; I have never seen cursors being well used, doesn't work for DBA. and good DBAs, most of the time, know what they are doing. but, if you are reading this, you are not a DBA, right?
Do normalize your tables
There are two common excuses for not normalizing databases: Performance and pure laziness. you'll pay for the second one sooner or later; and, about performance, don't optimize what's not slow. often I see programmers de-Normalizing databases because "This will be slow ". and, more frequent than the inverse, the resulting design is slower. dbmss were designed to be used with normalized databases, so design with normalization in mind.
Don't select *
This is hard to get used, I know. And I confess: often I use it; but try to specify only the columns you'll need. This will:
- Reduce memory consumption and network bandwidth
- Elastic security design
- Gives the query optimizer a chance to read all the needed columns from the indexes
Do know how your data will be/is being acessed
A robust index design is one of the good things you can do for your database. And doing this is almost an art form. Everytime you add an index to a table, things get faster onSELECT
,INSERT
AndDELETE
Will be much slower. There's a lot of work in building and mantaining indexes. If you add several indexes to a table to speed yourSELECT
, You'll soon notice locks being held for a long time while updating indexes. So, the question is: what is being done with this table? Reading or updating data? This question is tricky, specially withDELETE
AndUPDATE
, Because they often involveSELECT
ForWHERE
Part and after this they update the table.
Don't create an index on the "sex" column
This is useless. first, let's understand how indexes speed up table access. you can see indexes as a way of quickly partitioning a table based on a criteria. if you create an index with a column like "sex", you'll have only two partitions: male and female. what optimization will you have on a table with 1,000,000 rows? Remember, mantaining an index is slow. Always design your indexes with the most Sparse Columns first and the least Sparse Columns last, e. g, name + province + sex.
Do use transactions
Specially on long-running queries. This will save you when things get wrong. Working with data for some time you'll soon discover some unexpected situation which will make your stored procured crash.
Do beware of deadlocks
Always access your tables on the same order. when working with stored procedures and transactions, you may find this soon. if you lock the table a then table B, always lock them in this very same order in all stored procedures. if you, by accident, lock the table B and then table A in another procedure some day you'll have a deadlock. deadlocks can be tricky to find if the lock sequence is not carefully designed.
Don't open large recordsets
A common request on programming forums is: "How can I quickly fill this combo with 100,00 items? ". Well, this is an error. you can't and you shouldn't. first, your user will hate browsing through 100,000 records to find the right one. A better UI is needed here, because you shoshould ideally show no more that 100 or 200 records to your users.
Don't use server side cursors
Unless you know what your are doing. Client Side cursors often (not always) Put less overhead on the network and on the server, and reduce locking time.
Do use parametrized queries
Sometimes I see in programming forums, questions like: "My queries are failing with some chars, e.g. Quotes. How can I avoid it? ". And a common answer is: "replace it by double quotes ". wrong. this is only a workaround and will still fail with other chars, and will introduce serious security bugs. besides this, it will trash the SQL Server Caching System, which will cache several similar queries, instead of caching only one. learn how to use parameterized queries (In ADO, through the use of the command object, or in ADO. netSqlcommand) And never have these problems again.
Do always test with large databases
It's a common pattern programmers developing with a small test database, and the end user using large databases. this is an error: disk is cheap, and performance problems will only be noticed when it's too late.
Don't import bulk data with insert
Unless strictly necessary. Use DTS or the BCP utility and you'll have both a flexible and fast solution.
Do beware of timeouts
When querying a database, the default timeout is often low, like 15 seconds or 30 seconds. Remember that report queries may run longer than this, specially when your database grows.
Don't ignore simultaneous editing
Sometimes two users will edit the same record at the same time. when writing, the last writer wins and some of the updates will be lost. it's easy to detect this situation: Create a timestamp column and check it before you write. if possible, merge changes. if there is a conflict, prompt the user for some action.
Don't do select max (ID) from master when inserting in a detail table.
This is another common mistake, and will fail when two users are inserting data at the same time. Use oneSCOPE_IDENTITY
,IDENT_CURRENT
, And@@IDENTITY
. Avoid@@IDENTITY
If possible because it can introduce some nasty bugs with triggers.
Do avoid nullable Columns
When possible. they consume an extra byte on each nullable column in each row and have more overhead associated when querying data. the Dal will be harder to code, too, because everytime you access this column you'll need to check
I'm not saying that nulls are the edevil incarnation, like some people say. I believe they can have good uses and simplify coding when "Missing Data" is part of your business rules. but sometimes nullable columns are used in situations like this:
Customername1
Customeraddress1
Customeremail1
Customername2
Customeraddress2
Customeremail3
Customername1
Customeraddress2
Customeremail3
This is horrible. Please, don't do this, normalize your table. It will be more flexible and faster, and will reduce the nullable columns.
Don't use the text datatype
Unless you are using it for really large data. The text datatype is not flexible to query, is slow and wastes a lot of space if used incorrectly. Sometimes a varchar will handle your data better.
Don't use temporary tables
Unless strictly necessary. often a subquery can substitute a temporary table. they induce overhead and will give you a big headache when programming under COM + because it uses a database connection pool and temporary tables will last forever. in SQL Server 2000, there are alternatives like the table data type which can provide in-memory solutions for small tables inside stored procedures too.
Do learn how to read a query execution plan
The SQL Server Query analyzer is your friend, and you'll learn a lot of how it works and how the query and index design can affect performance through it.
Do use referential integrity
This can be a great time saver. Define all your keys, unique constraints and Foreign keys. Every validation you create on the server will save you time in the future.
Conclusion
As I 've said before, this is by no means a complete SQL server performance and best practices guide. this wocould take a complete book to cover. but I really believe that this is a good start, and if you follow these practices, surely you will have much less trouble in the future.