How to select the last record of a table in SQL?
This is a sample code to select all records from a table. Can someone show me how to select the last record of that table?
select * from table
When I use: SELECT * FROM TABLE ORDER BY ID DESC LIMIT
I get this error: Line 1: Incorrect syntax near 'LIMIT'.
This is the code I use:
private void LastRecord()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HELPDESK_OUTLOOKConnectionString3"].ToString());
conn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT * FROM HD_AANVRAGEN ORDER BY " +
"aanvraag_id DESC LIMIT 1", conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBox1.Text = (myReader["aanvraag_id"].ToString());
TextBox1.Text += (myReader["wijziging_nummer"].ToString());
TextBox1.Text += (myReader["melding_id"].ToString());
TextBox1.Text += (myReader["aanvraag_titel"].ToString());
TextBox1.Text += (myReader["aanvraag_omschrijving"].ToString());
TextBox1.Text += (myReader["doorlooptijd_id"].ToString());
TextBox1.Text += (myReader["rapporteren"].ToString());
TextBox1.Text += (myReader["werknemer_id"].ToString());
TextBox1.Text += (myReader["outlook_id"].ToString());
}
}
Solution 1:
Without any further information, which Database etc the best we can do is something like
Sql Server
SELECT TOP 1 * FROM Table ORDER BY ID DESC
MySql
SELECT * FROM Table ORDER BY ID DESC LIMIT 1
Solution 2:
to get the last row of a SQL-Database use this sql string:
SELECT * FROM TableName WHERE id=(SELECT max(id) FROM TableName);
Output:
Last Line of your db!
Solution 3:
Assuming you have an Id column:
SELECT TOP 1 *
FROM table
ORDER
BY Id DESC;
Also, this will work on SQL Server. I think that MySQL you might need to use:
SELECT *
FROM table
ORDER
BY Id DESC
LIMIT 1
But, I'm not 100% sure about this.
EDIT
Looking at the other answers, I'm now 100% confident that I'm correct with the MySQL statement :o)
EDIT
Just seen your latest comment. You could do:
SELECT MAX(Id)
FROM table
This will get you the highest Id number.