Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a column from a select query with index

Tags:

sql

mysql

How can I add a column from a select query but the value from the new column will be the row count of the select query for example.

select quantity from menu;

and returns like this

+--------+
|quantity|
+--------+
|   50   |
|   32   |
|   23   |
+--------+

but I want somthing like this

+----------+--------+
|new column|quantity|
+----------+--------+
|     1    |   50   |
|     2    |   32   |
|     3    |   23   |
+----------+--------+

the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks

like image 850
ropenrom24 Avatar asked Nov 07 '18 13:11

ropenrom24


People also ask

How do you create an index in a select statement?

SQL Server CREATE INDEX statement In this syntax: First, specify the name of the index after the CREATE NONCLUSTERED INDEX clause. Note that the NONCLUSTERED keyword is optional. Second, specify the table name on which you want to create the index and a list of columns of that table as the index key columns.

How do I add an index to a column in MySQL?

To create indexes, use the CREATE INDEX command: CREATE INDEX index_name ON table_name (column_name); You can an index on multiple columns.


2 Answers

Since you can access the latest version of MySQL, we can simply use the Row_Number() functionality:

SELECT  
  ROW_NUMBER() OVER () AS new_column, 
  quantity 
FROM menu;
like image 197
Madhur Bhaiya Avatar answered Oct 20 '22 09:10

Madhur Bhaiya


You can use:

select row_number() over (order by quantity desc) as col1, quantity
from menu;

This assumes that you want the rows enumerated by quantity in descending order.

like image 26
Gordon Linoff Avatar answered Oct 20 '22 08:10

Gordon Linoff