Usage of HAVING in SQL

CREATE table table_name
(
  name TEXT,
  subject TEXT,
  number_grade INTEGER
  );

INSERT INTO table_name (name, subject, number_grade) VALUES ("person_a","math",81);
INSERT INTO table_name (name, subject, number_grade) VALUES ("person_a","science",75);
INSERT INTO table_name (name, subject, number_grade) VALUES ("person_b","math",76);
INSERT INTO table_name (name, subject, number_grade) VALUES ("person_b","science",90);
INSERT INTO table_name (name, subject, number_grade) VALUES ("person_c","math",81);
INSERT INTO table_name (name, subject, number_grade) VALUES ("person_c","science",100);
INSERT INTO table_name (name, subject, number_grade) VALUES ("person_c","chemistry",90);

SELECT * FROM table_name;

Name of the game is to find everyone who had a grade that is bigger than 80 for every subject they took.

I tried this:

SELECT name FROM table_name 
WHERE number_grade > 80
GROUP BY NAME;

and it gives me all the names in the table.
and the correct answer is this:

SELECT name FROM table_name 
GROUP BY name
HAVING min(number_grade) > 80; 

so the difference between HAVING and WHERE is that WHERE can only apply to one element inside the database? and HAVING coming after GROUP BY while WHERE is always before GROUP BY?

am I understanding this correctly?

Where applies to an individual row and having applies to groups.

1 Like

To clarify the difference, here you have an interesting link.

1 Like