Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is DISTINCT applied before or after GROUP BY in a MySQL query?

Below is the query I'm running. Does the DISTINCT get applied before or after the GROUP BY?

The table looks like this: id, state

The id is not unique, and an entity can have many entries with the same state or different states.

This behavior could drastically change my results. If DISTINCT is applied before GROUP BY, then it will only count each entity once throughout the entire set ( will only show up in one state ). If it happens after, then each entity will only be counted once per state, but could be counted in many states.

SELECT
    state,
    COUNT( DISTINCT entity_id ) AS count
FROM entities
GROUP BY state
ORDER BY count DESC;

My goal is to count each entity only once per state but to allow an entity to be counted in more than one states ... which is the behavior I would expect if DISTINCT is applied after GROUP BY.

like image 781
T. Brian Jones Avatar asked Mar 21 '23 01:03

T. Brian Jones


1 Answers

The GROUP BY is applied first:

http://sqlfiddle.com/#!2/92876/1

Using the same query as you've got in your question on the following data:

CREATE TABLE Entities (
  state INT,
  id INT
);

INSERT INTO Entities VALUES
  (1, 1), (1, 1), (1, 1),
  (2, 1),
  (3, 1),
  (1, 2),
  (1, 3),
  (2, 3);

the following result was output:

STATE | COUNT
1     | 3
2     | 2
3     | 1
like image 189
Bilal Akil Avatar answered Apr 06 '23 00:04

Bilal Akil