-1

Below is my table book.

        ID  BookName StoreId  Sequence Price
        1    ABC       1         1      450
        2    DEF       1         2      450
        3    GHF       2         1      300

So above table is book table, Each store will have multiple books. I am writing a function which will insert book record in this table. While inserting the new record our requirement is new book sequence should Max(Sequence) + 1 of corresponding store. I have written below query for that.

    INSERT INTO Book(BookName,StoreId,Sequence,Price) Values
       (@name,@sid,(SELECT MAX(Sequence) + 1 from book where StoreId=@StoreId),@price)

This query is working fine when we already have inserted storeId present in table but as soon as i give storeId not present table Sequence will come as NULL because we don't have any existing sequence for that store and Max(sequence)+1 will give Null. What is best way to resolve this?

Tharif
  • 13,538
  • 9
  • 54
  • 76
Manthan Davda
  • 165
  • 1
  • 8
  • 3
    On a side note, you have to `LOCK TABLE Book IN EXCLUSIVE MODE` before you do this, otherwise you can insert duplicate IDs from concurrent transactions. I strongly suggest using a counter table based approach instead; search for "postgresql gapless sequence" to learn more. – Craig Ringer Oct 24 '15 at 08:33

2 Answers2

0

Try It :

INSERT INTO Book
       (BookName,StoreId,Sequence,Price)
Values
       (@name,@sid,(SELECT MAX(Sequence) + 1 from book),@price)
Craig Ringer
  • 283,586
  • 65
  • 635
  • 730
Chilli
  • 123
  • 3
0

You will have to use some sort of isnull function or coalesce.

refer this.

What is the PostgreSQL equivalent for ISNULL()

INSERT INTO Book(BookName,StoreId,Sequence,Price) Values
       (@name,@sid,coalesce((SELECT MAX(Sequence) + 1 from book where StoreId=@StoreId),1),@price)
Community
  • 1
  • 1
Abdul Rehman Sayed
  • 6,364
  • 6
  • 41
  • 71