Finding the Nth Maximal Value | Database Journal

Finding the Nth Maximal Value

Written By
Eli Leiba
Eli Leiba
Jul 22, 2002
1 minute read


This procedure gets a tablename, column and an integer number N as parameters
and finds the Nth maximum value of the column’s value in a table.

For example: running it with ‘products’, ‘UnitPrice’ , 13 , @res

will get the 13TH largest value of unitprice from products
is no such N exist an error message is printed.


Procedure code and usage is listed below:

=====================================


create proc max_nth_value (@tablename varchar(50),

                           @column varchar(50),

                           @n int,

                           @res decimal (10,4) OUTPUT)

AS

set nocount on

declare @sqlStatment varchar(200)

set @sqlStatment = 'select a.' + @column + ' from ' + @tableName + ' a ' +

                   'where ' + convert (varchar(10),@n) +

                   '=(select count(distinct ' + @column + ')' +

                   ' from ' + @tableName + ' b ' +

                   ' where ' + 'a.'+ @column + ' <= ' + 'b.' + @column + ')'
create table #tres (x decimal (10,4))

insert into #tres exec (@sqlStatment)

if @@rowcount = 0 print 'No value found!' else select @res = x from #tres

set nocount off

go

-- usage

declare @res decimal (10,4)

exec max_nth_value 'products','unitprice',8,@res OUTPUT

print @res


»


See All Articles by Columnist
Eli Leiba

Eli Leiba

Eli works at Israel Electric Company as a Senior Application DBA in Oracle and MS SQL Server. He also has certifications from Microsoft and BrainBench in Oracle and SQL Server database administration and implementation. Mr. Leiba holds a B.S. in Computer Science since 1991 and has 11 years experience working in the database field. Additionally, Mr. Leiba teaches SQL Server DBA and Development courses at Microsoft CTEC and also serves as a senior database consultant for several Israeli start-up companies.

Database Journal Logo

DatabaseJournal.com publishes relevant, up-to-date and pragmatic articles on the use of database hardware and management tools and serves as a forum for professional knowledge about proprietary, open source and cloud-based databases--foundational technology for all IT systems. We publish insightful articles about new products, best practices and trends; readers help each other out on various database questions and problems. Database management systems (DBMS) and database security processes are also key areas of focus at DatabaseJournal.com.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.