Optimizing SQL Server Database Design Tips & Tricks

Database design is most crucial part in application development. Database can be anything SQL Server, MySQL, Oracle, etc. I will consider SQL SERVER as a part of discussion.

Tunning the database depends upon various factors like whether one datatype is better depends on the context of it’s usage. Following are most common datatypes used in database.

Numbers Datatype (For storing Primary Keys, Foreign Keys, Status etc) 

An int requires 4 times the storage of a tinyint. More storage means more data and

index pages to read / write, more I/O and thus potentially more seek time. It also means more memory consumption.

For eg. Desigining User Role and Users Table. Generally application will not have more than 5-10 user roles like Admin, Manager, Employee, etc. Most of developers design the table like - 

Table – UserRole

RoleId – Integer (whole number) data from –2^31 (–2,147,483,648) through 2^31–1 (2,147,483,647). It takes 4 Bytes to store.

RoleName – Varchar (50)

Which is not suiting to our requirements. Instead of int we can use tinyint – Integer data from 0 to 255. Storage size is 1 byte. 

 

DateTime Datatype (For storing dates)

Most of the times database tables required date to be stored to maintain record creation date. 

DateTime data type are stored internally two 4-byte integers. The first 4 bytes store the number of days before or after the base date: January 1, 1900. The base date is the system reference date. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.

The smalldatetime data type stores dates and times of day with less precision than datetime. The Database Engine stores smalldatetime values as two 2-byte integers. The first 2 bytes store the number of days after January 1, 1900. The other 2 bytes store the number of minutes since midnight.

So, instead of using datetime as datatype smalldatetime is more efficient in general development.

 

STRING DATATYPE (Storing text data)

All string data stored inside varchar, text, ntext, nvarchar, etc. 

For eg. FirstName data field developers used varchar or nvarchar with default size i.e. 50. We should know the scope of the filed in terms of maximum characters. Generally first name, last name etc.. won’t take more than 20 – 25 characters. So instead of 50 if we use 20 characters we can save half the storage, index size which will increase performance of queries. 

 These are the basics which needs to keep in mind while developing applications. 

Happy Coding … 🙂