# SQL Help!

**URL:** <https://boards.straightdope.com/t/sql-help/690056>\
**Category:** Factual Questions\
**Created:** [June 4, 2014, 8:40pm UTC](https://boards.straightdope.com/t/sql-help/690056 "2014-06-04T20:40:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kinthalis](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/kinthalis/32/16084_2.png) [@Kinthalis](https://boards.straightdope.com/u/Kinthalis)\
**Post date:** [June 4, 2014, 8:40pm UTC](https://boards.straightdope.com/t/sql-help/690056/1 "2014-06-04T20:40:53Z")

</div>

SQL the bane of my existence.

I’m having trouble creating a stored procedure that returns a single record from a table that looks like this:

```auto

ID Min Max
1 10 20
2 25 45
3 46 99
4 120 145

```

Where the argument coming in from the request is between min and max. That’s simple, but there’s another layer. As you cna see the ranges are not always sequential accross records, so IF the value is NOT between the min and max of any record, then I need to return the record where the max is closest to the passed argument.

So for an input of 20 I should get record Id#1, obviously, but for an input of 105 I should get record id#3.

Anyone care to help me out?

---

<div class="post-metadata">

**Author:** ![KayLovesPurple](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/kaylovespurple/32/6114_2.png) [@KayLovesPurple](https://boards.straightdope.com/u/KayLovesPurple)\
**Post date:** [June 4, 2014, 9:12pm UTC](https://boards.straightdope.com/t/sql-help/690056/2 "2014-06-04T21:12:01Z")

</div>

Without much thinking, so not an optimal solution (but a starting point, hopefully) :

DECLARE @Response INT = NULL

SET @Response = ID from tableName WHERE argument BETWEEN Min AND Max

IF @Response = NULL --no interval found  
BEGIN  
SET @Response = (SELECT TOP 1 ID FROM tableName ORDER BY Max - argument)  
END

---

<div class="post-metadata">

**Author:** ![Kinthalis](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/kinthalis/32/16084_2.png) [@Kinthalis](https://boards.straightdope.com/u/Kinthalis)\
**Post date:** [June 5, 2014, 12:23am UTC](https://boards.straightdope.com/t/sql-help/690056/3 "2014-06-05T00:23:15Z")

</div>

Kinthalis loves purple too! Thanks, this helps a lot.
