Sorting Query Results

Whereas the WHERE conditional places restrictions on what data is returned, the ORDER BY clause will affect how that data is returned. Much like listing the columns of a table arranges the returned order (compare Figures 4.13 and 4.15), ORDER BY structures the entire list. When you do not dictate the order of the returned data, it will be presented to you in somewhat unpredictable ways (although probably on the primary key in ascending order).

SELECT * FROM tablename ORDER BY column;
SELECT email FROM users ORDER BY registration_date;

The default order when using ORDER BY is ascending (abbreviated ASC), meaning that numbers increase from small to large and dates go from older to most recent. You can reverse this order ...

Get PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.