Vahag Chakhoyan
Vahag Chakhoyan

Reputation: 779

sql 'select max' query

I have a table with name "table_name" approximately like this

+----+-----------+
| ID | title     |
| 1  | title 1   |
| 2  | title 2   |
| ...| ......... |
| ...| ......... |
| n  | title n   |
+----+-----------+.

And I need a query that returns this result

+------+-----------+
| n+1  | title 1   |
| n+1  | title 2   |
| ...  | ......... |
| ...  | ......... |
| n+1  | title n   |
+------+-----------+

(n+1 is select max(ID) from table_name)

how can I do that?

Upvotes: 0

Views: 146

Answers (4)

Rupsingh
Rupsingh

Reputation: 1138

For Mysql

select (1+max(ID)) as ID ,title
from table_name;

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can select this max ID to a variable, and then simply use it in your select:

DECLARE @maxId INT = (SELECT MAX(ID) FROM [dbo].[table1]);
SELECT @maxId, t.title, t.column2, t.column3 ... from [dbo].[table2] t

Upvotes: 1

qxg
qxg

Reputation: 7036

Window function

SELECT MAX(ID) OVER() + 1, title
FROM table_name

Upvotes: 1

jarlh
jarlh

Reputation: 44746

Simply add a sub-query to the select list:

select (select max(ID) + 1 from tablename), title
from tablename

Upvotes: 2

Related Questions