Categories: Development

MySQL count for multiple conditions

MySQL COUNT allows you to count rows in your MySQL database, a useful way to use this is to apply a condition like:

SELECT COUNT(*) FROM invoices WHERE `paid` = 1

That returns the amount of rows that have paid as 1.

A good way of using COUNT is to apply a GROUP BY and column reference, this can give you a greater look at the database makeup.

Saying that a database which has coffee drank per day as amount, these values could be anything from 0 through to (hopefully no more than) 6. To get the count of days i had 0 coffees or 1 coffee or 2 coffee etc I would run this:

SELECT amount, COUNT(*) FROM coffee GROUP BY amount

Which outputs:

amount COUNT(*)
0 0
1 5
2 16
3 9

Another way which would suit a different example is seeing the count of fruit sold but only for certain fruit:

SELECT fruit, COUNT(*) FROM sales WHERE fruit IN ('LEMON', 'LIME', 'ORANGE') GROUP BY fruit

Thus returning the count only for lemons, limes and oranges.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago