Tuesday, January 24, 2017

SQL Server Computed Columns


   Computed Columns can be really useful and powerful when you use them in right place and in right way. Let's say we have the following inventory table.




We want to have a column in this table which will contain the amount of money we spend for the inventory. (InvoicePrice * InStock) should be good for now.
Following command creates a computed column in our table.




You do not need PERSISTED at the end of the query.  If you don't use PERSISTED, everytime you run a query on this table, SQL Server will calculate the InStock value. This will cause slower query run times.
With PERSISTED, SQL Server will create the InStock column physically on the disk. That means your table will be larger, but your queries will run faster since SQL Server does not need to calculate each row.
Also if the computed column is PERSISTED you can use it as FOREIGN KEY, CHECK or NOT NULL constraints.
With PERSISTED or Without PERSISTED, when you query the table, you will see the following same results.



Computed Column is an important feature of SQL Server and there are many ways to ask questions about them, Pay attention to them If you are studying for SQL Server Certification.

No comments:

Post a Comment