1

I'm trying to find the following statistic: How many users have made at least one order

(yeah, sounds like homework .. but this is a simplistic example of my real query).

Here's the made up query

SELECT COUNT(UserId)
FROM USERS a
WHERE EXISTS(
    SELECT OrderId
    FROM ORDERS b
    WHERE a.UserId = b.UserId
)

I feel like I'm getting the correct answers but I feel like this is an overkill and is inefficient.

Is there a more efficient way I can get this result?

If this was linq I feel like I want to use the Any() keyword....

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • This could help: http://stackoverflow.com/questions/2065329/sql-server-in-vs-exists-performance – sgeddes Sep 16 '14 at 00:13
  • 1
    [_Your eyes can deceive you. Don't trust them._](http://en.wikiquote.org/wiki/Star_Wars_Episode_IV:_A_New_Hope) Your query is fine. Trust the compiler to find the optimal plan based on your data and inidices. – D Stanley Sep 16 '14 at 00:19

3 Answers3

3

It sounds like you just could use COUNT DISTINCT:

SELECT COUNT(DISTINCT UserId)
FROM ORDERS 

This will return the number of distinct values of UserId appear in the table OrderId.

In response to sgeddes's comment, to ensure that UserId also appears in Users, simply do a JOIN:

SELECT COUNT(DISTINCT b.UserId)
FROM ORDERS b
  JOIN USERS a 
    ON a.UserId = b.UserId
Community
  • 1
  • 1
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1
Select count(distinct u.userid)
From USERS u
Inner join ORDERS o
On o.userid = u.userid
radar
  • 13,270
  • 2
  • 25
  • 33
1

Your query should be fine, but there are a few other ways to calculate the count:

SELECT COUNT(*)
FROM USERS a
WHERE UserId IN (
    SELECT UserId 
    FROM ORDERS b
)

or

SELECT COUNT(DISTINCT UserID)
FROM USERS a
INNER JOIN ORDERS b ON a.UserID = b.UserID

The only way to know which is faster is to try each method and measure the performance.

D Stanley
  • 149,601
  • 11
  • 178
  • 240