3

I'm trying to set a default value when my attribute comes up null in the database:

case categories.rental_price_percentage when null then '15.0' else categories.rental_price_percentage end rental

However, the replacement value isn't taking hold when I hit a null value (the rest is working though), it only displays null:

{
 id: "3",
 category_name: "Chairs",
 rental: null
}

How can I get the default value in and working?

1 Answer 1

4

WHEN NULL in a simple CASE expression (it's not a statement) will never match because that would require, in your case, categories.rental_price_percentage = NULL to be true. But the result of comparison operations like =, >, ... against NULLs are NULL i.e. not true -- on only one or both sides, so even NULL = NULL is not true.

To check if an expression evaluates to NULL IS NULL is used.

So you could use a searched CASE expression:

CASE
  WHEN categories.rental_price_percentage IS NULL THEN
    15.0
  ELSE
    categories.rental_price_percentage
END rental

But replacing NULLs is such a common task, that there exists a function to do that, coalesce(). It returns the first of the arguments it gets passed, that is not NULL.

So in your case you could simply use:

coalesce(categories.rental_price_percentage, 15.0) rental

Note that I also removed the single quotes around 15.0 as it's presumably meant as a numeric value, not a string.

Sign up to request clarification or add additional context in comments.

7 Comments

What if I need it to remain in the case expression? I have the else set up because the user is able to change the value from default; for instance, I could set it to 50% in the settings, and the value will render fine.
@Boucherie: So? You can change it in the coalesce() call too.
Do I have to change the whole structure of the expression? Please keep in mind that I normally work in ActiveRecord and am a bit out of my depth here.
@Boucherie: The question was about SQL. I don't know about ActiveRecord but since you apparently can inject raw SQL, as you did with your CASE expression, you can do the same with the coalesce(). Unless there's probably an ActiveRecord way of doing this. But that would be another question then.
Understood, I was only trying to convey that I needed a bit more explanation to your last comment.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.