Treat NULL as Zero 0 before Incrementing Column value by 1 - SQL Server

← PrevNext →

Let's imagine you have an online quiz application where users answer multiple-choice questions. You want to keep track of how many times each question has been attempted.

However, some questions in the "dbo.Quiz" table have a number_of_attempts value of NULL because they have never been attempted before. Instead of treating NULL as an actual value, you want to treat it as 0 and increment the count by 1 whenever a user attempts the question.

For example, suppose the dbo.Quiz table contains the following columns:

When a user attempts a specific question, you want to increase its number_of_attempts value by 1, regardless of whether the current value is NULL or an existing number.

The SQL query

UPDATE dbo.Quiz
SET number_of_attempts = COALESCE(number_of_attempts, 0) + 1
WHERE QID IN (2, 3, 9);

If the "number_of_attempts" value for a question is NULL, it is treated as 0 and incremented to 1. However, if the number_of_attempts value is already a number, it is simply incremented by 1.

COALESCE() function in SQL Server

The COALESCE() function in SQL Server is useful when dealing with NULL values.

Syntax:

COALESCE(expression1, expression2, ..., expressionN)

COALESCE takes multiple expressions and returns the first non-NULL expression from the list.

See this example

← PreviousNext →