Group Rows With Conditions

WHERE filters rows before grouping (i.e. GROUP BY) while HAVING filters rows after grouping.

Create Table

-- Create table called adventurers
CREATE TABLE adventurers (
    -- string variable
    name varchar(255),
    -- integer variable
    age int,
    -- string variable
    race varchar(255),
    -- string variable
    weapon varchar(255)

Insert Rows

-- Insert into the table adventurers
INSERT INTO adventurers (name, age, race, weapon)
VALUES ('Fjoak Doom-Wife', 28, 'Human', 'Axe'),
       ('Alooneric Cortte', 29, 'Human', 'Bow'),
       ('Piperel Ramsay', 35, 'Elf', 'Axe'),
       ('Casimir Yardley', 14, 'Elf', 'Bow')

Group Rows

-- Retrieve the race and average age from the table
SELECT race, age, AVG(age) FROM adventurers
-- Grouped by race
GROUP BY race age
-- That are older than 20
HAVING age > 20