简体   繁体   中英

sum() vs. count()

Consider a voting system implemented in PostgreSQL, where each user can vote up or down on a "foo". There is a foo table that stores all the "foo information", and a votes table that stores the user_id , foo_id , and vote , where vote is +1 or -1.

To get the vote tally for each foo, the following query would work:

SELECT sum(vote) FROM votes WHERE foo.foo_id = votes.foo_id;

But, the following would work just as well:

(SELECT count(vote) FROM votes 
 WHERE foo.foo_id = votes.foo_id 
 AND votes.vote = 1)
- (SELECT count(vote) FROM votes 
   WHERE foo.foo_id = votes.foo_id 
   AND votes.vote = (-1))

I currently have an index on votes.foo_id .

Which is a more efficient approach? (In other words, which would run faster?) I'm interested in both the PostgreSQL-specific answer and the general SQL answer.

EDIT

A lot of answers have been taking into account the case where vote is null. I forgot to mention that there is a NOT NULL constraint on the vote column.

Also, many have been pointing out that the first is much easier to read. Yes, it is definitely true, and if a colleague wrote the 2nd one, I would be exploding with rage unless there was a performance necessity. Never the less, the question is still on the performance of the two. (Technically, if the first query was way slower, it wouldn't be such a crime to write the second query.)

Of course, the first example is faster, simpler and easier to read. Should be obvious even before one gets slapped with aquatic creatures . While sum() is slightly more expensive than count() , what matters much, much more is that the second example need two scans.

But there is an actual difference , too: sum() can return NULL where count() doesn't. I quote the manual on aggregate functions :

It should be noted that except for count, these functions return a null value when no rows are selected. In particular, sum of no rows returns null, not zero as one might expect,

Since you seem to have a weak spot for performance optimization, here's a detail you might like: count(*) is slightly faster than count(vote) . Only equivalent if vote is NOT NULL . Test performance with EXPLAIN ANALYZE .

On closer inspection

Both queries are syntactical nonsense, standing alone. It only makes sense if you copied them from the SELECT list of a bigger query like:

SELECT *, (SELECT sum(vote) FROM votes WHERE votes.foo_id = foo.foo_id)
FROM   foo;

The important point here is the correlated subquery - which may be fine if you are only reading a small fraction of votes in your query. We would see additional WHERE conditions, and you should have matching indexes.

In Postgres 9.3 or later, the alternative, cleaner, 100 % equivalent solution would be with LEFT JOIN LATERAL ... ON true :

SELECT *
FROM   foo f
LEFT   JOIN LATERAL (
   SELECT sum(vote) FROM votes WHERE foo_id = f.foo_id
   ) v ON true;

Typically similar performance. Details:

However , while reading large parts or all from table votes , this will be (much) faster:

SELECT f.*, v.score
FROM   foo f
JOIN   (
   SELECT foo_id, sum(vote) AS score
   FROM   votes
   GROUP  BY 1
   ) v USING (foo_id);

Aggregate values in a subquery first, then join to the result.
About USING :

The first one will be faster. You can try it on a simple way.

Generate some data:

CREATE TABLE votes(foo_id integer, vote integer);
-- Insert 1000000 rows into 100 foos (1 to 100)
INSERT INTO votes SELECT round(random()*99)+1, CASE round(random()) WHEN 0 THEN -1 ELSE 1 END FROM generate_series(1, 1000000);
CREATE INDEX idx_votes_id ON votes (foo_id);

Check both

EXPLAIN ANALYZE SELECT SUM(vote) FROM votes WHERE foo_id = 5;
EXPLAIN ANALYZE SELECT (SELECT COUNT(*) AS count FROM votes WHERE foo_id=5 AND vote=1) - (SELECT COUNT(*)*-1 AS count FROM votes WHERE foo_id=5 AND vote=-1);

But the truth is that they are not equivalent, to make sure the first one will work as the second, you need to treat for the null case:

SELECT COALESCE(SUM(vote), 0) FROM votes WHERE foo_id = 5;

One more thing. If you are using PostgreSQL 9.2, you can create your index with both columns in it, and that way you can have a chance of using index-only scan:

CREATE INDEX idx_votes_id ON votes (foo_id, vote);

BUT! In some situations this index may be worst, so you should try with both and run EXPLAIN ANALYZE to see which one is the best, or even create both and check which one PostgreSQL is using most (and exclude the other).

I would expect the first query to work faster as this is a single query and it's more readable (handy in case you'd have to get back to this after some time).

Second query consists of two queries. You only get a result as if it was a single query.

That said, to be absolutely sure which of these works better for you I would populate both tables with lots of dummy data and check the query execution time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM