You can do this two ways:
- A subquery in the
WHERE
clause (will return all rows with the max time, may be more than one)
- Use
ORDER BY
and ROWNUM
to select a row based on criteria you specify (guarantees just one row - but will need to be very specific in order to be deterministic)
Subquery:
SELECT
<whatever>
FROM
my_table
WHERE
writime =
(
SELECT
MAX(writime)
FROM
my_table
)
As I mentioned earlier, if multiple rows have the same value for writime
this query will return all of those rows. If this is your desired output (or acceptable), great!
If not, you'll need to use ROWNUM
(see this article for more detail/optimization considerations1):
SELECT
*
FROM
(
SELECT
<whatever>
FROM
my_table
ORDER BY
writime DESC
,<additional sort columns>
)
WHERE
ROWNUM = 1
This is guaranteed to return just one row. HOWEVER, this is not guaranteed to return exactly the same row (given the same point in time) unless you provide additional criteria in the ORDER BY
statement - generally this would be some columns chosen for business context plus the primary key column(s)2 of the table.
You certainly can combine these approaches (which may be better from a performance perspective, depending on what indexes exist on the table and how the data is distributed):
SELECT
*
FROM
(
SELECT
<whatever>
FROM
my_table
WHERE
writime =
(
SELECT
MAX(writime)
FROM
my_table
)
ORDER BY
<additional sort columns>
)
WHERE
ROWNUM = 1
1 Because selecting the top N requires a sort of the heap (in the absence of the table organized by writime or a covering index), this can be a very expensive operation. You'll need to look at how your table is structured/indexed to determine what the ideal query is - the Ask Tom article has some methods to achieve this.
2 Because the primary key is unique, sorting based on its column(s) will guarantee the same sort order each time.