Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sujeet SumanRank #790 · 2.9K reputationPosted Sep 23, 2015, 7:40 AM EDT
Manoj BhoirRank #599 · 4K reputationPosted Sep 23, 2015, 7:02 AM EDT
SELECT * From TableName Where DateColumnName > DATEADD(DAY, -15, GETDATE())
By definition, a table is an unordered set of rows. There is no way to ask SQL Server which row was inserted last unless you are doing so in the same batch as the insert. For example, if your table has an IDENTITY column, you can say:
INSERT dbo.table(column) SELECT 1;
SELECT SCOPE_IDENTITY();
More generally, you can use the OUTPUT clause, which doesn't rely on an IDENTITY column (but will still make it difficult to identify which row(s) the clause identifies if there is no PK):
INSERT dbo.table(column) OUTPUT inserted.* SELECT 1;
If you're not talking about the same batch, then the only real way to identify the last row inserted is to use a date/time column where the timestamp of insertion is recorded. Otherwise it is like you emptied a bag of marbles on the floor, then asking someone to enter the room and identify which one hit the floor last. So for example, you could add a column to track this going forward:
ALTER TABLE dbo.table ADD DateInserted DEFAULT CURRENT_TIMESTAMP;
Now you can find the last row(s) inserted by simply:
WITH x AS (SELECT *, r = RANK() OVER (ORDER BY DateInserted DESC)
FROM dbo.table)
SELECT * FROM x WHERE r = 1;
(If you don't want ties, you can add a tie-breaking column to the ORDER BY, or you can simply change RANK() to ROW_NUMBER()if you don't care which of the tied rows you get.)
You might make the assumption that the last row inserted is the highest identity value, but this isn't necessarily the case. The identity can be reseeded and it can also be overridden using
SET IDENTITY_INSERT ON;.
Raja TRank #685 · 3.5K reputationPosted Sep 23, 2015, 7:52 AM EDT
SELECT * FROM tbl_product
WHERE DATEDIFF(day,c_date,getdate()) between 0 and 15
Note: Here tbl_product is table name and c_date is column name
Vinitha TRank #8,005 · 230 reputationPosted Oct 27, 2021, 9:36 AM EDT
satheesh d190 reputationPosted Nov 3, 2021, 6:52 AM EDT