Question: I am trying to do a postgres update using if conditions to check if a parameter is empty before attempting to update.

The desired result would be not to update when the parameter is an ampty string.

I cannot seem to figure out the correct way to do this. My first attempt is below:

```
$stmt = $db->prepare("
  UPDATE users SET
    fname = IF(trim(:fname) = '', fname, :fname)
  WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':fname', $fname);
$stmt->execute();

```

and then my second attempt was using:

```
$stmt = $db->prepare("
  UPDATE users SET fname =
    IF
      trim(:fname) =  ''
    THEN
      fname
    ELSE
      :fname
    END IF;
  WHERE username = :username
");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':fname', $fname);
$stmt->execute();

```

What is the correct way of doing this with IF statements?

Answer: 
You are looking for just one matching row in each group, so you can use an aggregation function:

```
SELECT ps.id, ps.identifier, MAX(tn.name) as name
FROM pokemon_species ps JOIN
     pokemon_types pt
     ON ps.id = pt.pokemon_id JOIN
     type_names tn
     ON pt.type_id = tn.type_id
GROUP BY 1
HAVING COUNT(*) = 1
ORDER BY ps.id;

```

Presumably, `pokemon_species.id` is declared as a primary key. That is why you can leave `ps.identifier` out of the `GROUP BY`.
Join after the aggregation:

```
SELECT ps.id,
       ps.identifier,
       tn.name
FROM (
  SELECT id,
         identifier,
  FROM pokemon_species 
  GROUP BY ps.id
  HAVING COUNT(*) = 1
) ps 
  JOIN pokemon_types pt ON ps.id = pt.pokemon_id
  JOIN type_names tn ON pt.type_id = tn.type_id
ORDER BY pokemon_species.id;

```