About Me

Wednesday, 18 April 2012

SQL - Order By

SQL - Order By

ORDER BY is the SQL command used to sort rows as they are returned from a SELECT query. SQL order by command may be added to the end of any select query and it requires at least one table column to be specified in order for SQL to sort the results.

SQL Order by query:

USE mydatabase;

SELECT *
FROM orders
WHERE customer = 'Tizag'
ORDER BY day_of_order;
Executing this query should offer a list of orders made by Tizag and you may noticed that the result set has now been sorted (low to high) according to the date value. In other words, the oldest order to the newest order.

SQL Results:

idcustomerday_of_orderproductquantity
5Tia2008-07-25 00:00:00.00019" LCD Screen3
6Tia2008-07-25 00:00:00.000HP Printer2
1Tia2008-08-01 00:00:00.000Pen4
2Tia2008-08-01 00:00:00.000Stapler1

SQL - Ascending Descending

The default sort order for ORDER BY is an ascending list, [a - z] for characters or [0 - 9] for numbers. As an alternative to the default sorting for our results, which is ASCENDING (ASC), we can instead tell SQL to order the table columns in a DESCENDING (DESC) fashion [z-a].

SQL Order by Descending:

USE mydatabase;

SELECT *
FROM orders
WHERE customer = 'Tizag'
ORDER BY day_of_order DESC

SQL Results:

idcustomerday_of_orderproductquantity
1Tia2008-08-01 00:00:00.000Pen4
2Tia2008-08-01 00:00:00.000Stapler1
5Tia2008-07-25 00:00:00.00019" LCD Screen3
6Tia2008-07-25 00:00:00.000HP Printer2
If you compare these results to the results above, you should notice that we've pulled the same information but it is now arranged in a reverse (descending) order.

SQL - Sorting on Multiple Columns

Results may be sorted on more than one column by listing multiple column names in the ORDER BY clause, similar to how we would list column names in each SELECT statement.

SQL Order by Multiple columns:

USE mydatabase;

SELECT *
FROM orders
ORDER BY customer, day_of_order;
This query should alphabetize by customer, grouping together orders made by the same customer and then by the purchase date. SQL sorts according to how the column names are listed in the ORDER BY clause.

SQL Results:

idcustomerday_of_orderproductquantity
3A+Maintenance2008-08-16 00:00:00.000Hanging Files 12
4Gerald Garner2008-08-15 00:00:00.00019" LCD Screen3
5Tia2008-07-25 00:00:00.00019" LCD Screen3
6Tia2008-07-25 00:00:00.000HP Printer2
1Tia2008-08-01 00:00:00.000Pen4
2Tia2008-08-01 00:00:00.000Stapler1

0 comments:

Post a Comment