Ethan Mick

Count Values in SQL Table Grouped by Value

A very useful SQL query is looking up how often a value occurs, grouped by those values. For example, in a table of pets, how often does each kind of pet occur?

Here, you want to count the pets grouped by the type:

-- table: create table pets (type text, name text, pet_type text);
select count(pet_type) AS count,
pet_type
from pets
where user_id is not null
group by pet_type
order by count desc;

The result looks like this:

count pet_type
1233 "dog"
327 "cat"
59 "bird"

Be the best web developer you can be.

A weekly email on Next.js, React, TypeScript, Tailwind CSS, and web development.

No spam. Unsubscribe any time.