Tuesday, June 16, 2009

Select MAX from a column

I tried using below function to get a sequence value for a coulmn, but kept getting NULL when when the table is empty.

begin
select max(nvl(id, 0)) + 1 INTO t_id FROM table_name;
exception when NO_DATA_FOUND then
t_id := 1;
end;

The real trick is that "select max(id) FROM table_name" always returns NULL, and does not raise NO_DATA_FOUND error.

The fix is to use below statement:

select nvl(max(id), 0) + 1 INTO t_id FROM table_name;

Note "select count(id) from table_name" always returns 0 when the table is empty.

No comments: