Mikk
Mikk

Reputation: 455

How to query highest value from table column in SQL Server 2012?

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

Upvotes: 1

Views: 5141

Answers (3)

CSS
CSS

Reputation: 412

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,

Upvotes: 2

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

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);
    }

Upvotes: 2

fnurglewitz
fnurglewitz

Reputation: 2127

select max(ID) from [Table]

SQLFiddle

Upvotes: 7

Related Questions