Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better to use in SQL Server: sqrt or pow?

What is more efficient to use in SQL Server: pow(x,1/2) or sqrt(x)? Which one cost less, and which one is faster?

like image 750
edgarmtze Avatar asked Feb 12 '11 21:02

edgarmtze


People also ask

Can you do square root in SQL?

SQRT() function in SQL Server returns the square root of a number. SQL SQRT() function is used to find out the square root of any number. For example, you can use the SELECT statement to find out the square root of any number.

What does SQRT do in SQL?

The SQRT() function returns the square root of a number.

Can you do exponents in SQL?

POWER() function : This function in SQL Server is used to return a results after raising a specified exponent number to a specified base number. For example if the base is 5 and exponent is 2, this will return a result of 25.

What is the use of power in SQL?

The POWER() function returns the value of a number raised to the power of another number.


2 Answers

Mathematically: SQRT is just a specialized form of POWER, using 1/2 as the exponent

But in SQL Server, the implementation is different. POWER is able to take any floating point as the 2nd argument, so detecting special cases and optimizing differently for each special case (p2=1=>identity and p2=0.5=>sqrt) would make POWER slower than it needs to be.

If you need the Square Root, use SQRT. POWER is demonstrably about 15% slower.

Note: make sure you're using POWER not POW and use 0.5 not 1/2 (literally) since 1/2 = 0

Comparison tests (and timings from SQL Server 2005):

declare @dummy float -- to hold the result without generating resultset
declare @t1 datetime, @t2 datetime, @t3 datetime
declare @a float
set @a = rand()*1000000
declare @i int

select @t1 = getdate()
set @i = 0
while @i < 10000000
begin
    select @dummy= sqrt(@a)
    set @i = @i + 1
end

select @t2 = getdate()

set @i = 0
while @i < 10000000
begin
    select @dummy= power(@a, 0.5)
    set @i = @i + 1
end
select @t3 = getdate()

select
Time_SQRT  = datediff(ms, @t1, @t2),
Time_POWER = datediff(ms, @t2, @t3)

/*
Time_SQRT   Time_POWER
----------- -----------
14540       16430
14333       17053
14073       16493
*/
like image 134
RichardTheKiwi Avatar answered Oct 27 '22 08:10

RichardTheKiwi


I'd like to see the source code that says SQRT uses POWER internally. SQRT is usually calculated using Newton's iterative method; I thought POWER would be more likely to use something else (like natural log and exponential).

I agree with the comment that said it isn't likely to matter. At best, it's the kind of micro-optimization that will be swamped by poor decisions about normalization, indexing, clustering, poorly written queries, etc.

like image 36
duffymo Avatar answered Oct 27 '22 09:10

duffymo