3

Suppose I have a SQL database in which a column could look something like this

Numbers
-------
1
1
2
3
4
4

Is it possible to create a single SQL query that simply grabs the largest number, which in this case would be 4? Or would I have to query every single number, put them in some sort of list in an external program, and write an algorithm to find the largest one?

3 Answers 3

9

Use can use the MAX Aggregate function. Since your table only has one column it would look like

SELECT MAX(NUMBERS) n from yourtable

depending on your backend you could also put into a variable. For example in SQL Server

Declare @TheMax int
SELECT @TheMax = MAX(NUMBERS) 
FROM yourTable

Here's a working example on data.stackexchange.com

If you also wanted the Max Per somthing you'd need a group by

For example this query on Data.SE gives the max score per tag

SELECT 
      tagname, max(score) 
FROM 
   posts p
   INNER JOIN postTags pt
   ON p.id = pt.postId
   INNER JOIN tags t
   ON pt.tagid = t.id 
GROUP BY 
   tagname ​
Sign up to request clarification or add additional context in comments.

Comments

5

When x is your column name then:

SELECT MAX(x) FROM numbers

Comments

1

This should work on most SQL servers.

Select Max(Number) From Table

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.