Sorting Results

Use this

SELECT * FROM table_name ORDER BY row_name ASC
or
DESC

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

With GROUP BY

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

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published.