2

There is a table in my postgres database that contains 4 digit years in a string format concat with each other -

rollno | year
-----------------------------------
00001  | 201220132014
-----------------------------------
00002  | 2013201420152016
-----------------------------------
00003  | 2015
-----------------------------------

I have above data in my postgres table, I want my data to be separated by comma as below example :

rollno | year
-----------------------------------
00001  | 2012,2013,2014
-----------------------------------
00002  | 2013,2014,2015,2016
-----------------------------------
00003  | 2015
-----------------------------------
1
  • 4
    Fix your design. Normalize your tables instead of looking for complicated queries Commented Jan 12, 2017 at 5:28

2 Answers 2

1

You can use the regex (\d)(?=(\d{4})+$) with \1, as replacement.

update yourTable
set year = regexp_replace(year, '(\d)(?=(\d{4})+$)', '\1,', 'g')

However, this query is actually taking you in the wrong direction, because it results in having CSV data in your year column. Instead, each year should ideally be in a separate record to keep your database normalized.

Sign up to request clarification or add additional context in comments.

5 Comments

No it does not make it comma separated still. It just return the same string
I tested this locally on my Postgres and it works. What type is your year column? Is it numeric or text?
Its character varying
It runs for me without any problems, I cannot help you further.
@Curious: Tim's solution works, see here: rextester.com/SYOP26824 If it doesn't work for you then you probably forgot to tell some details.
1

Try this

update tbl1
set vl = t.yr
from (
    select id
        ,string_agg(y, ',') yr
    from (
        select id
            ,unnest(regexp_split_to_array(vl, E '(?=(....)+$)')) y
        from tbl1
        ) s
    group by id
    ) t
where t.id = tbl1.id

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.