Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the item index number in a query result

Tags:

sql

sql-server

is there a simple way to get the number of the current item in a simple SELECT? I need to deliver a column based on a calculation that involves the number of the current index in the select. I am simplifing my problem to an extreme, but roughly speaking, here is an example:

SELECT column1 * ITEMINDEX FROM table

I hope I am being clear. I am using SQL Server. Thank you.

like image 522
Marcos Buarque Avatar asked Sep 23 '09 15:09

Marcos Buarque


People also ask

How do you find the index of a query?

To see the index for a specific table use SHOW INDEX: SHOW INDEX FROM yourtable; To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA.

How do I know which index is used in SQL query?

In SQL Management Studio, just type in the query, and hit Control-L (display query execution plan). There, you will be able to see whether any indexes are being used. A "table scan" means the index is not used. An "index scan" means the index is used.

How do you find the results of a query?

You have the option of displaying your query results on the Run SQL window, as opposed to Data Display windows. To do this, go to View > Data Grid (Ctrl+G). Once you have selected this option, a panel will appear at the bottom of the window - your query results will be displayed there.

What is a query index?

Indexing is the way to get an unordered table into an order that will maximize the query's efficiency while searching. When a table is unindexed, the order of the rows will likely not be discernible by the query as optimized in any way, and your query will therefore have to search through the rows linearly.


1 Answers

In SQL Server 2005+:

SELECT  m.*, ROW_NUMBER() OVER (ORDER BY column) AS rn
FROM    mytable m

SQL does not have concept of implicit row number, that's why you need ORDER BY clause to define the order of rows.

like image 112
Quassnoi Avatar answered Oct 01 '22 00:10

Quassnoi