Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select max value of a column in table with no rows

I am using oracle database

While inserting a row in a table, i need to find the max value of a column and increment it by 1, and use that value in row i am inserting.

INSERT INTO dts_route 
   (ROUTE_ID, ROUTE_UID, ROUTE_FOLDER)
VALUES (
                        (SELECT MAX(ROUTE_ID) + 1 FROM  route) ,
                        ROUTE_UID,
                        ROUTE_FOLDER)

This works fine if their is at least one entry in table. But returns null when their are no entries in table.

How can i get default value of 1 when their are no entries in table.

like image 612
changed Avatar asked Feb 04 '11 17:02

changed


3 Answers

SELECT COALESCE(MAX(ROUTE_ID),0) ...
like image 128
codymanix Avatar answered Nov 10 '22 00:11

codymanix


This is not a safe way of creating an auto-increment field. You can use an Oracle sequence to achieve this goal.

As for the null, you can use NVL to give a default value (say, 0) in case the function returns null.

like image 42
Ilya Kogan Avatar answered Nov 09 '22 23:11

Ilya Kogan


Use sequence for the ID. You need to create sequence. See below link

http://www.basis.com/onlinedocs/documentation/b3odbc/sql_sequences.htm

like image 2
Chirag Tayal Avatar answered Nov 10 '22 00:11

Chirag Tayal