TheMeisterSE
TheMeisterSE

Reputation: 541

If row is null else

So I have a column named "votes" which have the value "NULL" when the row first gets created. At the end of the day, I will add the votes coming from another table and put all the votes into the correct row. The problem is that if it is the first time the row gets votes, I will have to write SET votes = '$votes' but if it already has votes I will have to write SET votes = votes + '$votes'. Is there any easy way to detect if it is null or if it has an value?

Upvotes: 1

Views: 133

Answers (4)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

Initialise the field to 0 instead of NULL.

It makes sense for something to start off with no votes.

In fact, I'd make this column NOT NULL!

Upvotes: 2

Padmanathan J
Padmanathan J

Reputation: 4620

Use Ifnull

SET votes = IFNULL(votes, 0) + votes

Upvotes: 2

David Lin
David Lin

Reputation: 13353

You can use the ifnull MYSQL function, the SQL will be like

UPDATE .... SET votes = IFNULL(votes, 0) + votes

Upvotes: 3

John Woo
John Woo

Reputation: 263703

try this, COALESCE or IFNULL.

SET votes = COALESCE(votes, 0) + '$votes'

if the value of votes is null, it will be converted to 0 other wise retain the original value and added it to your $votes.

Upvotes: 2

Related Questions