-1

I am trying to insert different content based on if a SQL table has Rows. So far the Query will check what the max value of sortingOrder is and then + 1. However this query will break if there is no rows in the table. How can I implement a if statement to check if the table has no rows and then if it doesn't set the sortingOrder to '1'.

INSERT INTO faq (question, answer, sortingOrder) 
VALUES ('$questionData', '$answerData', (SELECT MAX(sortingOrder) FROM faq C) +1)

Thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

The best solution is to make sortingOrder an AUTO_INCREMENT column. The database will assign the values automatically, incrementing them for each row.

If you can't do that for some reason, you can check if the subquery returns NULL and replace it with 1.

INSERT INTO faq (question, answer, sortingOrder) 
SELECT '$questionData', '$answerData', IFNULL(MAX(sortingOrder)+1, 1)
FROM faq
Barmar
  • 741,623
  • 53
  • 500
  • 612