Skip to content
Advertisement

How do I use SQL to return the first entry in a chronological sort?

I have a table named Dates, let’s just say with two columns for simplicity purposes. One is labeled “date” and that column is of a date data type, and the other one is labeled timestamp and it’s labeled as a Timestamp data type.

For my program the user selects a date to make a booking. Every time I book, I add a timestamp to my booking object. This way, I can track which bookings came first or not.

So what do I want to do? Well essentially I want the first result of a date in which the timestamp came first.

Let’s say I have a table like this:

And I want to select the date 11/2/2019 and my SQL code would return the first inputted value of this, which is the middle entry.

So my SQL should return this:

How would I write an SQL to get the earliest entry of a specific date given that there is a timestamp attached to it.

Here’s what I have so far:

But I’m getting a syntax error. How would I rewrite this query to get the first entry based on the value of the timestamp?

Advertisement

Answer

You can use aggregation:

If you want other columns, one method is a correlated subquery:

If your data has duplicate minimum times, this returns all of them.

Or row_number():

This returns one row when there are duplicates. If you want all of them, use rank() instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement