DEV Community

Dan Croak
Dan Croak

Posted on • Edited on • Originally published at dancroak.com

1

Postgres concat_ws() function

Postgres provides a concat_ws() string function with this signature:

concat_ws(sep text, str "any" [, str "any" [, ...] ])
Enter fullscreen mode Exit fullscreen mode

Consider a schema where the projects.second_user_id and project.third_user_id columns can be NULL:

              Table "public.projects"
     Column     |            Type        | Nullable |
----------------+------------------------+-----------
 id             | bigint                 | not null |
 name           | character varying(255) | not null |
 lead_user_id   | bigint                 | not null |
 second_user_id | bigint                 |          |
 third_user_id  | bigint                 |          |

                Table "public.users"
     Column     |            Type        | Nullable |
----------------+------------------------+-----------
 id             | bigint                 | not null |
 initials       | character varying(255) | not null |
Enter fullscreen mode Exit fullscreen mode

Consider a query to get the "team" for a project by each user's initials:

SELECT
  projects.name,
  concat_ws(' / ', u1.initials, u2.initials, u3.initials) AS team
FROM
  projects
  LEFT JOIN users u1 ON u1.id = projects.lead_user_id
  LEFT JOIN users u2 ON u2.id = projects.second_user_id
  LEFT JOIN users u3 ON u3.id = projects.third_user_id
GROUP BY
  projects.name,
  team
ORDER BY
  projects.name ASC;
Enter fullscreen mode Exit fullscreen mode

Example output:

     name     |     team    
-------------------+--------------
Private Beta  | AB / CD
SLA           | EF / GH / IJ
Treasury Ops  | KL
(3 rows)

Time: 1 ms
Enter fullscreen mode Exit fullscreen mode

Using concat_ws() instead of concat() avoids ugly output like AB / / CD.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay