Wednesday 26 June 2013

How To Use ORDER BY Command In SQL

sql - order by

In previous chapter i have explained you How To Use UPDATE command In SQL

now i am gonna eplain you How To Use ORDER BY Command In SQL


 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
5Tizag2008-07-25 00:00:00.00019" LCD Screen3
6Tizag2008-07-25 00:00:00.000HP Printer2
1Tizag2008-08-01 00:00:00.000Pen4
2Tizag2008-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
1Tizag2008-08-01 00:00:00.000Pen4
2Tizag2008-08-01 00:00:00.000Stapler1
5Tizag2008-07-25 00:00:00.00019" LCD Screen3
6Tizag2008-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 Files12
4Gerald Garner2008-08-15 00:00:00.00019" LCD Screen3
5Tizag2008-07-25 00:00:00.00019" LCD Screen3
6Tizag2008-07-25 00:00:00.000HP Printer2
1Tizag2008-08-01 00:00:00.000Pen4
2Tizag2008-08-01 00:00:00.000Stapler1

No comments: