jack miao
jack miao

Reputation: 1488

adding condition to mysql json query

I have a simple query like this that go over my mysql records of certain table and gives me jsons out of each record:

SELECT json_object(
  'personId', p.id,
  'formalName', p.name,
  'country', p.country)
FROM person p;

but I formalName can be null, and I wanted to add a condition like

if p.name is null 'NoName' else p.name

is it possible?

Upvotes: 1

Views: 333

Answers (1)

Jorge Campos
Jorge Campos

Reputation: 23361

Yeap change p.name to case when p.name is null then 'NoName' else p.name end at the end your query will be:

SELECT json_object(
  'personId', p.id,
  'formalName', case when p.name is null then 'NoName' else p.name end,
  'country', p.country)
FROM person p;

Upvotes: 2

Related Questions