2

I have the following CREATE View statement where I am concatenating a couple fields. It grabs the 1st 100 characters of the first field, then appends an integer field

  CREATE OR REPLACE VIEW $"schema_1"."tbl_225_customid" AS 
  SELECT tbl_225.id,
  ("substring"((field_2)::text, 0, 100)::text) ||  ' (' || "field_1" || ')' as fullname
  FROM schema_1.tbl_225;

This works fine when there is data in field_2, however, when field_2 is null, the view shows NULL instead of just the integer part of the expression.

I tried wrapping this in a coalesce statement like this, but it throws an error.

   CREATE OR REPLACE VIEW $"schema_1"."tbl_225_customid" AS 
   SELECT tbl_225.id,
   COALESCE(("substring"((field_2)::text, 0, 100)::text),'') ||  ' (' || "field_1" || ')' as fullname
   FROM schema_1.tbl_225;

How do I write the concat string such that, if field_2 is null, it will use '' for that and still result in value?

1
  • Sample data and desired results would be helpful. Commented May 4, 2020 at 19:54

2 Answers 2

1

I would recommend simply using string function concat_ws() for this: it ignores null value by design, so you just don't need to worry about them:

select 
    tbl_225.id,
    concat_ws('', substring(field_2::text, 0, 100), ' (' || field_1 || ')') as fullname
from schema_1.tbl_225;
Sign up to request clarification or add additional context in comments.

Comments

0

Use coalesce():

SELECT tbl_225.id,
        COALESCE(substring(field_2::text, 0, 100) , '') ||  coalesce(' (' || "field_1" || ')', '') as fullname
FROM schema_1.tbl_225;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.