Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculated column in where-clause - performance

Since you can't use a calculated column in a where-clause in MySQL like this:

SELECT a,b,c,(a*b+c) AS d FROM table WHERE d > n ORDER by d 

you have to use

SELECT a,b,c,(a*b+c) AS d FROM table WHERE (a*b+c) > n ORDER by d 

Is the calculation (in that example "(a*b+c)" executed once per row or twice? Is there a way to make it faster? I find it strange it's possible to ORDER on the column but not to have a WHERE-clause.

like image 347
Raphael Jeger Avatar asked Apr 17 '13 19:04

Raphael Jeger


People also ask

Are there any disadvantages of using computed column?

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.

When should you use a calculated column?

Calculated columns in DAX are useful whenever you have to use data from other tables in the data model, or consider aggregated data in a computation. Two examples where the calculated columns are very useful are the Static Segmentation and the ABC Classification patterns.

How can you use a computed column in an SQL query?

Go to your database, right click on tables, select “New Table” option. Create all columns that you require and to mark any column as computed, select that column and go to column Properties window and write your formula for computed column.

How do I find the computed column in SQL Server?

Get a list of computed columns in a SQL Server database. We can use the system function sys. computed_columns and join it with the sys. objects to get a list of available computed columns, their data type, and the column definition (formula).


1 Answers

You can use HAVING to filter on a computed column:

SELECT a,b,c,(a*b+c) AS d, n FROM table HAVING d > n ORDER by d 

Note that you need to include n in the SELECT clause for this to work.

like image 115
Barmar Avatar answered Sep 22 '22 22:09

Barmar