Skip to Content
MySQL Cookbook, 2nd Edition
book

MySQL Cookbook, 2nd Edition

by Paul DuBois
November 2006
Intermediate to advanced
977 pages
30h 42m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook, 2nd Edition

Sorting by Day of Week

Problem

You want to sort rows in day-of-week order.

Solution

Use DAYOFWEEK() to convert a date column to its numeric day-of-week value.

Discussion

Day-of-week sorting is similar to calendar-day sorting, except that you use different functions to get at the relevant ordering values.

You can get the day of the week using DAYNAME(), but that produces strings that sort lexically rather than in day-of-week order (Sunday, Monday, Tuesday, and so forth). Here the technique of displaying one value but sorting by another is useful (see Displaying One Set of Values While Sorting by Another). Display day names using DAYNAME(), but sort in day-of-week order using DAYOFWEEK(), which returns numeric values from 1 to 7 for Sunday through Saturday:

mysql>SELECT DAYNAME(date) AS day, date, description
    -> FROM event
    -> ORDER BY DAYOFWEEK(date); +----------+------------+-------------------------------------+ | day | date | description | +----------+------------+-------------------------------------+ | Sunday | 1809-02-12 | Abraham Lincoln's birthday | | Sunday | 1776-07-14 | Bastille Day | | Monday | 1215-06-15 | Signing of the Magna Carta | | Tuesday | 1944-06-06 | D-Day at Normandy Beaches | | Thursday | 1989-11-09 | Opening of the Berlin Wall | | Friday | 1732-02-22 | George Washington's birthday | | Friday | 1958-01-31 | Explorer 1 launch date | | Friday | 1957-10-04 | Sputnik launch date | | Saturday | 1919-06-28 | Signing of the Treaty of Versailles | | Saturday | 1789-07-04 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Cookbook, 3rd Edition

MySQL Cookbook, 3rd Edition

Paul DuBois
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
MySQL Cookbook

MySQL Cookbook

Paul DuBois
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal

Publisher Resources

ISBN: 059652708XSupplemental ContentErrata Page