If I include a computed column in a table, does it place a perfomance burden on it?
For example, if I have a table defined as follows:
CREATE TABLE users(
givenname …,
familyname …,
fullname AS givenname+' '+familyname
);
… does it recalculate every time I SELECT
from the query?
Would it help if the computed column is PERSISTED
?
Some Limitations. You can not reference columns from other tables for a computed column expression directly. You can not apply insert or update statements on computed columns.
There will be no performance difference based on the column position.
A computed column is a virtual column that is not physically stored in the table, unless the column is marked PERSISTED. A computed column expression can use data from other columns to calculate a value for the column to which it belongs.
Computed columns can be persisted. It means that SQL Server physically stores the data of the computed columns on disk. When you change data in the table, SQL Server computes the result based on the expression of the computed columns and stores the results in these persisted columns physically.
Yes, if the computed column is PERSISTED, there is no performance issue in selecting the data (but there is in inserting them).
And yes, it is calculated every time you select the data.
does it recalculate every time I SELECT from the query
If that column is references in a query then the calculation will be performed at least once during the query. This is (yet another) good reason to avoid select * ...
- if you have a query against the users
table that doesn't reference the fullname
column then no calculation will be performed.
Would it help if the computed column is PERSISTED
Obviously, the calculation doesn't need to be performed, but you're now paying for a small amount of storage and I/O costs in having the retrieve the persisted data.
But in short, don't try to second guess these things. If this is a common calculation, create a computed column for it. Later, once you have performance goals and can measure your performance, you can assess whether it has a meaningful performance issue and whether the persisted
trade off (calculation vs storage) has any effect on this.
My tests indicate ,even if you persist the column,the are calculated every time when you select ..
below is some test data
create table numm
(
id int,
col_not_persist as id+1,
col_persist as id+1 persisted
)
insert into numm
(id)
select number from Numbers--just numbers from 1 -1000000
now when you query
select * from numm
execution plan shows two scalar operator(costed less though) and if you can see the definition on top right hand corner.. you can see they are calculated every time they are referenced
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With