Hello all,
I am trying to get the latest record inserted in a SQL table based on its CreatedDate. For instance, in the table below, I would like to get the third row.
A B C 2009-05-04 19:30:52.847
A B D 2009-05-04 19:30:55.050
A B E 2009-05-04 19:30:57.003
I have a working query, but I am wondering if there is better way to achieve the same result. Below is the table, data and query I am using right now for my test. Is there any better way to do this?
CREATE TABLE TestTable (
ColumnA NVARCHAR(10),
ColumnB NVARCHAR(10),
ColumnC NVARCHAR(10),
CreatedDate DATETIME DEFAULT Getutcdate())
INSERT INTO TestTable(ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'C');
INSERT INTO TestTable(ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'D');
INSERT INTO TestTable(ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'E');
SELECT *
FROM TestTable
WHERE CreatedDate = (SELECT Max(CreatedDate)
FROM TestTable
WHERE ColumnA = 'A'
AND ColumnB = 'B'
GROUP BY ColumnA,
ColumnB)
Thanks!