Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking the second last row with only one select in SQL Server?

I was trying to select the second last row with SQL Server. So I wrote a query like this:

SELECT TOP 1 * From Cinema  WHERE CinemaID!=(SELECT TOP 1 CinemaID                   FROM Cinema                  ORDER BY CinemaID DESC)                       ORDER BY CinemaID DESC  

and it did what I need. But I want to do the same thing with only one select.

I read that the LIMIT clause in MySql does that. But I couldn't find any equivalent of that. So I appreciate any help about finding something useful.

like image 286
Bedir Yilmaz Avatar asked Nov 20 '11 02:11

Bedir Yilmaz


People also ask

How do I select the second last row in SQL?

Here is the query to get the second last row of a table in MySQL. mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1; The output displays the second last record.

How do I get the last row in SQL?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How do I select the last 3 rows in SQL?

I want to select the last 3 rows of an sql table. I know I should use SELECT * FROM table ORDER BY DESC LIMIT 3 , but the problem with this code is that it selects the rows from the end. For example, it selects 30, then 29, then 28. But, I need them in this format: 28, 29, 30 .

How do I select the last 5 rows in SQL Server?

mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records. We can match both records with the help of the SELECT statement.


1 Answers

To get the 2nd last row in one select:

SELECT TOP 1 * From (select Top 2 * from Cinema ORDER BY CinemaID DESC) x                      ORDER BY CinemaID 

It's really only "one" select because the outer select is over only 2 rows.

like image 146
Bohemian Avatar answered Sep 21 '22 20:09

Bohemian