sql min max

Hi

What is the most performant way to select the min and max value

here is my query

select (min odometer) and (max odometer) 
From MyTable
Where gpsDateTime between '2018-01-01' and '2018-01-17' and eventID = 1

Open in new window


i basically need  to return 2 item, the max odometer and min odometer reading based on the datetime
I'm looking for the most efficient SQL that can achieve this

SQL server 2014
websssAsked:
Who is Participating?
 
Scott PletcherSenior DBACommented:
That's pretty much it.

select min(odometer) as odometer_min, max(odometer) as odometer_max
From dbo.MyTable
Where gpsDateTime >= '2018-01-01' and gpsDateTime < '2018-01-18' and eventID = 1
0
 
ste5anSenior DeveloperCommented:
First of all: Use correct SQL. This includes using an save date literal format.

SELECT MIN(odometer) AS min_odometer ,
       MAX(odometer) AS max_odometer
FROM   MyTable
WHERE  gpsDateTime
       BETWEEN '20180101' AND '20180117'
       AND eventID = 1;

Open in new window


Performance depends on correct indices. Thus you need a combined index over (eventID, gpsDateTime, odometer) to cover your query.
0
 
websssAuthor Commented:
sorry ste5an awarded too soon
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.