E
E
EVOSandru62015-08-25 11:00:27
PostgreSQL
EVOSandru6, 2015-08-25 11:00:27

How to return a default value in a query if SELECT returns NULL or returns nothing for a particular expression?

Good afternoon!
For example, I want the bottom expression to return 0 to me or, say , 1 if the result of the rating expression returns NULL :

SELECT
                m_users.id,
                  ( SUM(mc_rating.name) / COUNT(mc_rating.name)) as rating ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ramil, 2015-08-25
@rshaibakov

There are several solutions in documentation . The choice is yours.

E
egor90, 2015-09-03
@egor90

select coalesce(   ( SUM(mc_rating.name) / COUNT(mc_rating.name) ), 0::integer ) as rating, ...

But I don’t understand, if rating is not null, then there will be 2 columns, and otherwise one?
Try a subquery:
with _rating as ( select
    m_users.id,
    coalesce(   ( SUM(mc_rating.name) / COUNT(mc_rating.name) ), 0::integer ) as rating ....
)
select * from _rating r where r.rating > 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question