Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL How to Select the most recent date item

Hello I have a table with columns:

*using oracle

ID                  NUMBER USER_ID            NUMBER DATE_ADDED          DATE DATE_VIEWED        DATE DOCUMENT_ID        VARCHAR2 URL                VARCHAR2 DOCUMENT_TITLE      VARCHAR2 DOCUMENT_DATE        DATE 

I want to know how i can get the most recently added document for a given user.

Select * FROM test_table WHERE user_id = value AND (do something with date_added column) 

Thanks

like image 215
Matt Avatar asked Nov 03 '10 19:11

Matt


People also ask

How do I get the latest value in SQL?

We could use LAST_VALUE() in SQL Server to find the last value from any table. LAST_VALUE() function used in SQL server is a type of window function that results the last value in an ordered partition of the given data set.

How do I get the last date a SQL query was updated?

SELECT name AS TableName, create_date AS CreatedDate, modify_date as ModifyDate FROM sys. tables order by ModifyDate; ...will tell me the last time a table was created and modified (from a DDL perspective).


2 Answers

Select *  FROM test_table  WHERE user_id = value  AND date_added = (select max(date_added)     from test_table     where user_id = value)
like image 195
sh_kamalh Avatar answered Sep 20 '22 15:09

sh_kamalh


Not sure of exact syntax (you use varchar2 type which means not SQL Server hence TOP) but you can use the LIMIT keyword for MySQL:

Select * FROM test_table WHERE user_id = value      ORDER BY DATE_ADDED DESC LIMIT 1 

Or rownum in Oracle

 SELECT * FROM      (Select rownum as rnum, * FROM test_table WHERE user_id = value ORDER BY DATE_ADDED DESC)  WHERE rnum = 1 

If DB2, I'm not sure whether it's TOP, LIMIT or rownum...

like image 45
gbn Avatar answered Sep 19 '22 15:09

gbn