Wednesday, January 20, 2016

SQL ORDER BY: Display Records in According to Date and Time in Descending Order

Hi there buddy! This article is about using some important SQL clause. This is about the use of SQL ORDER BY clause.

ORDER BY is the keyword used to arrange records in a specific order, either in ascending (which is the default ordering if not set) or in descending order. ORDER BY is used in a select statement. Remember that an order by clause can only be used in the main query and cannot be used in the subquery. By the way, a subquery is a query inside a query. The syntax of a subquery is provided below.

Select column_name from table where column_name order by column_name = (select column_name from table where condition);

Now' I'll give you and example that uses the order by clause in a query. Below is the POST table which contains the columns, post_id (primary key), post_content, date_posted and time_posted. If you are going to arrange the records in a certain table by date and time, make sure that you use the 24 hour format to avoid unexpected results. So let's create a query to arrange the below data in descending order. Why descending? You must put or display the latest post above and below are the older post so that users can easily read what's new.

POST Table


select * from post order by date_posted desc,time_posted desc

The code above will first arrange the record in descending order according to the date_posted and then followed by time_posted also in descending order. For multiple columns, you need to put a comma(,) as a separator between columns.


Hope this helps! ^_^

Watch out for more articles related to pogramming and systems administration!

SQL ORDER BY: Display Records in According to Date and Time in Descending Order

No comments:

Post a Comment