Opposite SELECT TOP?

Simple, I hope. I searched but cannot find a good working example.

Transact SQL has a convenient SELECT TOP 4 [whatever] FROM.........

I just want to select the last 4 entries from the table, not too many to ask, is this true? !!

You would think that M $ would already cover it!

 sql = "SELECT TOP 4 [news_title], [news_date_added], [news_short_description], [news_ID] FROM [Web_Xtr_News] WHERE ([news_type] = 2 OR [news_type] = 3) AND [news_language] = '" + Language + "' ORDER BY [news_ID] ASC" 

This selects FIRST 4 items that were entered into the table, I need the last 4.

+3
source share
4 answers

Reorder the table from ASC to DESC .

+26
source

This is exactly this: http://www.sqlfiddle.com/#!3/6c813/1

 with bottom as( select top 4 * from tbl order by n desc ) select * from bottom order by n 

Data source:

 | N | |----| | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 | 

Conclusion:

 | N | |----| | 7 | | 8 | | 9 | | 10 | 
+17
source

Why not continue using TOP and reorder?

 sql = "SELECT TOP 4 [news_title], [news_date_added], [news_short_description], [news_ID] FROM [Web_Xtr_News] WHERE ([news_type] = 2 OR [news_type] = 3) AND [news_language] = '" + Language + "' ORDER BY [news_ID] DESC" 

Re-written to use parameters, of course, your original is vulnerable to SQL injection.

+4
source

You can reverse the order using DESC instead of ASC at the end of your request.

0
source

Source: https://habr.com/ru/post/904982/


All Articles