Let's consider a simple query:
select distinct p.id
from posts p
inner join Users u on u.id = p.owneruserid
inner join votes v on v.UserId = u.Id
inner join Badges b on b.UserId = u.Id
where CommentCount > 1 and p.id < 100000
When I run this query directly: elapsed time = 7667 ms.
But if I wrap this query into a function:
alter function getPostsWhereCount()
returns @ids table (id int)
as
begin
insert into @ids
select distinct p.id
from posts p
inner join Users u on u.id = p.owneruserid
inner join votes v with on v.UserId = u.Id
inner join Badges b with on b.UserId = u.Id
where CommentCount > 1 and p.id < 100000
return
end
And run: select * from getPostsWhereCount()
elapsed time = 10722 ms.
Also, I've noticed that CPU time = 20779 ms
for the first query and CPU time = 10766 ms
for the last one
Why there are differences?