Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find row number of a record?

Tags:

sql

sql-server

Consider example table below

ProductDetailNo    ProductDescription
      224                Apples
      225                Tomatoes
      226                Potatoes

How do I list the row number for a selected row like below ?

RowNo    ProductDetailNo          Product Description
  2         225                Tomatoes

Using row_number() in my query just returns 1 always for a single record no mater what the logical row is in the database.

Thanks, Damien.

like image 481
Zo Has Avatar asked Jan 05 '12 07:01

Zo Has


People also ask

How do I find the row number in a SQL record?

ROW_NUMBER() gives you the number of the row only within a specific result set.

How do you find the row number?

Getting a row number with ROW Getting a row number is easy—just find the cell you're interested in, click on it, and look at the highlighted row number on the side of the window.

How can we get the number of records or rows?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.

How do I find the row number in SQL Server?

If you'd like to number each row in a result set, SQL provides the ROW_NUMBER() function. This function is used in a SELECT clause with other columns. After the ROW_NUMBER() clause, we call the OVER() function. If you pass in any arguments to OVER , the numbering of rows will not be sorted according to any column.


2 Answers

try this

WITH MyTable AS
(
    SELECT ProductDetailNo, ProductDescription,
    ROW_NUMBER() OVER ( ORDER BY ProductDetailNo ) AS 'RowNumber'
    FROM Product
) 
SELECT RowNumber, ProductDetailNo     
FROM MyTable 
WHERE ProductDetailNo = 225
like image 139
Shoaib Shaikh Avatar answered Oct 28 '22 08:10

Shoaib Shaikh


Please Check This

WITH ArticleSearch AS
    (
        SELECT
            ROW_NUMBER() OVER 
                (
                    ORDER BY tblProducts.ProductDetailNo                                    
                ) AS RowNumber, 
            tblProducts.ProductDetailNo, 
            tblProducts.ProductDescription    
        FROM         
            tblProducts
    )

    SELECT 
        a.RowNumber AS SlNo,
        a.ProductDetailNo,
        a.ProductDescription
    FROM
          ArticleSearch a
    WHERE
          a.ProductDetailNo=225
like image 36
Renju Vinod Avatar answered Oct 28 '22 08:10

Renju Vinod