Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active April 24, 2022 21:28
Show Gist options
  • Save vielhuber/5aa5cb9defc2ff364bc86596d04ebdf9 to your computer and use it in GitHub Desktop.
Save vielhuber/5aa5cb9defc2ff364bc86596d04ebdf9 to your computer and use it in GitHub Desktop.
MySQL / PostgreSQL: Concat two strings intelligently #sql

mysql

SELECT CONCAT_WS(
    ' ',
    NULLIF(contract.company_name,''),
    NULLIF(contract.last_name,''),
    NULLIF(contract.first_name,'')
) FROM members;

sql

SELECT CONCAT_WS(
	' ',
	(CASE WHEN COALESCE(company_name,'')='' THEN NULL ELSE company_name END),
    (CASE WHEN COALESCE(first_name,'')='' THEN NULL ELSE first_name END),
	(CASE WHEN COALESCE(last_name,'')='' THEN NULL ELSE last_name END)
) FROM members;

postgres

# concat all existing strings
SELECT trim(array_to_string(array_remove(array_remove(ARRAY[null,'foo',null,'bar',''], null), ''), ', '));

# concat all strings only if every string exists
SELECT 'THIS LINE ONLY SHOWS IF ANY PART IS NOT EMPTY OR NULL' || ' (' || NULLIF(COALESCE('A SUBQUERY THAT COULD BE EMPTY OR NULL',''),'') || ')';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment