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 will not show here how to use specific. T-SQL tricks, nor will not 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 seein this articles be surprised of how many SQL Server programmers do not even know all T-SQL commands and all of those effective 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 to. But spend a weekend at MSDN AND Browse Through All T-SQL Commands: The Mission HE Re is to learn a lot of what can and what can't be done. and in the fulure, when, you'll remember "Hey, There's this command" exactly what i need ", and then you ' LL Refer Again To Msdn To See ITICLE 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 it.. Don't use Cursors. The be your preferred warred warred warred..................................
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 every FETCH being executed has about the same performance of executing a SELECT? This means that if your cursor has 10,000 records, it will execute about 10,000 SELECTs! If you can do this in a couple of SELECT, UPDATE or DELETE, 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 specifying what you want, not how it should 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 should 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 al . L 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, except for DBA work. 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, do not 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. DO NOT 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: 1. Reduce memory consumption and network bandwidth 2. Ease security design 3. 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 on SELECT, but INSERT and DELETE 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 your SELECT, 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 with the DELETE and UPDATE, because they often involve a SELECT for the WHERE part and after this they update the table. DO NOT 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, eg, 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 DO nOT 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 shouth't. First, Your User Will Hate Browsing Through 100,000 Records to Find The Right One. A Better UI Is Needed here, Because You Should Ideally Show No more That 100 or 200 records to your users. DO NOT 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, EG 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.NET the SqlCommand) 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 DO NOT 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. DO NOT Ign ore 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 The User for Some Action. Don't do SELECT MAX (ID) from Master When Insert In a Detail Table. This is Another Common Mistake, and Will Fail When Two Users Are Inserting Data At The Same Time. Use One of Scope_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 evil 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, do not do this, normalize your table It will be more flexible and faster, and will reduce the Nullable Column. Don't Use The text DataType Unless Data. The text DataType is not flexible to query, is Slow and Wastes a Lot O f space if used incorrectly. Sometimes a VARCHAR will handle your data better. DO NOT 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 friends, and you '