[TIL] Database MySQL - WHERE, GROUP BY, ORDER BY queries

03/20/23

·

2 min read

[TIL] Database MySQL - WHERE, GROUP BY, ORDER BY queries

WHERE query

To find 'scope'

  • select * from orders where created_at between '2020-07-13 and '2020-07-15';

To find 'existence'

  • select * from checkins where week in (1, 2, 3);

To find 'patterns'

  • select * from users where email like '%@google.com';

  • % : whatever can come in here

To set a 'limit'

  • select * from orders where payment_method = 'CARD' limit 5;

  • LIMIT only shows the specific number of rows

To remove 'duplicates'

  • select distinct(payment_methods) from orders;

To 'count' rows

  • select count(*) from orders where payment_method = 'CARD';

Group by

To 'count' rows with GROUP BY

  • select name, count(*) from users group by name;

To get the 'minimum' value

  • select week, min(likes) from checkins group by week;

To get the 'maximum' value

  • select week, max(likes) from checkins group by week;

To get the 'average' value

  • select week, avg(likes) from checkins group by week;

  • To get a 'rounded' average:

    • select week, round(avg(likes), 2) from checkins group by week;

To get the 'sum' of values

  • select week, sum(likes) from checkins group by week;

Order by

select payment_method, count(*) cnt_pm from orders o
where course_title = 'web development'
group by payment_method 
order by cnt_pm desc;

The order that the queries get executed

  • FROM -> GROUP BY -> SELECT -> ORDER BY