1

For example, I have table with a column ID as seen below:

  ID  
------
  1 
  2
  3 
  4 

How can I query so I can get 4?

I'm using SQL Server 2012

3 Answers 3

7
select max(ID) from [Table]

SQLFiddle

2

You should use SELECT max(Id) FROM mytable

And you should be able to accomplish that using code like this:

    int maxId = -1;
    string connectionString = "yourConnectionString";
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            using (SqlCommand command = new SqlCommand("SELECT max(Id) FROM mytable", con))
            {
                maxId = Convert.ToInt32(command.ExecuteScalar());
            }
        }
    }
    catch (Exception err)
    {
        MessageBox.Show(err.Message);
    }
2

You can also use

SELECT TOP 1 ID
FROM mytable
ORDER BY ID DESC

to forego calculation and utilize a sort feature to find the highest value in whatever column you're checking.

Thanks,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.