Reputation: 614
I have this INSERT statement and there seems to be trailing spaces at the end of the acct_desc
fields. I'd like to know how to prevent trailing spaces from occurring during my insert statement.
INSERT INTO dwh.attribution_summary
SELECT d.adic,
d.ucic,
b.acct_type_desc as acct_desc,
a.begin_mo_balance as opening_balance,
c.date,
'fic' as userid
FROM fic.dim_members d
JOIN fic.fact_deposits a ON d.ucic = a.ucic
JOIN fic.dim_date c ON a.date_id = c.date_id
JOIN fic.dim_acct_type b ON a.acct_type_id = b.acct_type_id
WHERE c.date::timestamp = current_date - INTERVAL '1 days';
Upvotes: 4
Views: 5329
Reputation: 657912
Use the PostgreSQL trim()
function. There is trim()
, rtrim()
and ltrim()
.
To trim trailing spaces:
...
rtrim(b.acct_type_desc) as acct_desc,
...
If acct_type_desc
is not of type text
or varchar
, cast it to text first:
...
rtrim(b.acct_type_desc::text) as acct_desc,
...
If acct_type_desc
is of type char(n)
, casting it to text
removes trailing spaces automatically, no trim()
necessary.
Upvotes: 6
Reputation: 4928
Besides what others have said, add a CHECK CONSTRAINT
to that column, so if one forgets to pass the rtrim()
function inside the INSERT statement, the check constraint won't.
For example, check trailing spaces (in the end) of string:
ALTER TABLE dwh.attribution_summary
ADD CONSTRAINT tcc_attribution_summary_trim
CHECK (rtrim(acct_type_desc) = acct_type_desc);
Another example, check for leading and trailing spaces, and consecutive white spaces in string middle):
ALTER TABLE dwh.attribution_summary
ADD CONSTRAINT tcc_attribution_summary_whitespace
CHECK (btrim(regexp_replace(acct_type_desc, '\s+'::text, ' '::text, 'g'::text)) = acct_type_desc);
Upvotes: 3
Reputation: 754490
What is the type of acct_desc
?
Upvotes: 2