SELECT * FROM (
SELECT DISTINCT ON(codice_fiscale /*, dipartimento*/)
   codice_fiscale AS cf
  /*, dipartimento*/
 , beneficiario_ultimo AS ben
FROM beneficiari_progetti
WHERE COALESCE(codice_fiscale = upper(:cf), :cf IS NULL)
  AND COALESCE(beneficiario_ultimo ILIKE :ben, TRUE)
) tmp