Sorting Results

Use this

SELECT * FROM table_name ORDER BY row_name ASC

To Sort On Multiple Values

select * FROM table_name ORDER BY HighestPriority DESC, NextRowName DESC, NextRowName DESC

ORDER BY With $wpdb->prepare

ORDER BY and %s does not work with $wpdb->prepare, in our tests the following order by gets ignored:

  $sql = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_devices 
                          ORDER BY %s ASC
                        ", $SortOrder);

Whereas this works as expected.

  $sql = "SELECT * FROM {$wpdb->prefix}table_devices 
                          ORDER BY $SortOrder ASC

So it seems that $wpdb->prepare() adding single quotes around the inserted name field causes it to break.

Date Order

ASC = oldest first

DESC = most recent first


When using GROUP BY, if you also use ORDER BY it must come after the GROUP BY

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.


Your email address will not be published.