For example I have a table with 2 columns, first_name
and last_name
with these values
Ali Khani
Elizabette Amini
Britney Spears
,...
I want to write a select
query that generate a table like this:
1 Ali Khani
2 Elizabette Amini
3 Britney Spears
,...
Thanks for your help.
If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.
The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment.
To add a new AUTO_INCREMENT integer column named c : ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c); We indexed c (as a PRIMARY KEY ) because AUTO_INCREMENT columns must be indexed, and we declare c as NOT NULL because primary key columns cannot be NULL .
The auto increment in SQL is a feature that is applied to a field so that it can automatically generate and provide a unique value to every record that you enter into an SQL table. This field is often used as the PRIMARY KEY column, where you need to provide a unique value for every record you add.
If it is MySql you can try
SELECT @n := @n + 1 n, first_name, last_name FROM table1, (SELECT @n := 0) m ORDER BY first_name, last_name
SQLFiddle
And for SQLServer
SELECT row_number() OVER (ORDER BY first_name, last_name) n, first_name, last_name FROM table1
SQLFiddle
here's for SQL server, Oracle, PostgreSQL
which support window functions.
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone
select
ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1,
period_next_id, period_name_long
from
(
select distinct col1, period_name_long, 'X' as num
from {TABLE}
) as x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With