Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - decrease value to zero

Tags:

sql

mysql

I know how to increase/decrease value in column.

value type is INT(11)

Command:

UPDATE table SET value = value - 1 WHERE id = 1

But when value reaches "0" it keeps decreasing.

Question: How to decrease until zero, so I don't get value (-1) in column?

Thank you for your code / ideas / suggestions

like image 915
Ing. Michal Hudak Avatar asked Dec 19 '14 15:12

Ing. Michal Hudak


People also ask

How do you decrement a value in SQL?

You can decrement value in MySQL with update command. With this, you can also restrict the value to not reach below 0. update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0; To avoid the value to go below zero, you can use yourColumnName > 0.

How do you change a null to zero in SQL?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.

What does <> 0 mean in SQL?

“Every [SQL] data type includes a special value, called the null value,”0 “that is used to indicate the absence of any data value”.1. The null value does not indicate why a value is absent—it simply marks the places that do not have a data value.

Is equal to zero in SQL?

SQL Server IS NULL / IS NOT NULL In SQL Server, NULL value indicates an unavailable or unassigned value. The value NULL does not equal zero (0), nor does it equal a space (' ').


1 Answers

Just use a conditional:

UPDATE table
    SET value = value - 1
    WHERE id = 1 AND value > 0;
like image 172
Gordon Linoff Avatar answered Sep 22 '22 04:09

Gordon Linoff