0

I just built this new conditional query for pulling either a first_name AND last_name OR company_name based on the display_as value:

Select If(`display_as` = 'individual',
    CONCAT(first_name, ' ', last_name)
   ,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1

The problem is, if the user has a first_name value only and no value for last_name, nothing is returned at all.

How can I fix this?

Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
Joe Shmoe
  • 27
  • 5
  • This happens because any operation involving a NULL and a NOT NULL value results to NULL, with the exception of IFNULL and COALESCE, which are used to address the issue by providing a default value in case of NULL. The answers given are typical examples of the functions usage. – Manos Anastasiadis Aug 08 '19 at 06:39

3 Answers3

1

use this query instead.

$sql = "Select If(`display_as` = 'individual',
    CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, ''))
   ,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1";
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
1

try this one:

Select
    If( `display_as` = 'individual',
        CONCAT(coalesce(first_name, ''), ' ', coalesce(last_name, ''))
       ,`company_name`) as name
FROM `{$this->table}`
WHERE `unique_id` = ?
LIMIT 1
Y.K.
  • 682
  • 4
  • 10
1

I would recommend writing this as:

select (case when display_as = 'individual' 
             then concat_ws(' ', first_name, last_name)
             else company_name
        end) as name 
from `{$this->table}` 
where unique_id = ?
limit 1;  -- probably not needed

Notes:

  • case is the standard SQL construct for conditional logic. if() is a bespoke MySQL extension.
  • concat_ws() elegantly handles NULL values in the names. It simply ignores the the value rather than returning NULL.
  • Backticks are not required everywhere. They just make the query harder to write and read.
  • If your unique_id is really unique, you don't need LIMIT 1.
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786