PostGreSQL: Update from sub query Syntax


Given my table has the following example
how do I run an update command to set the year column

CREATE TABLE my_table(
 string TEXT,
 year character_ varying(2) 

INSERT INTO my_table (string) VALUES ('30NOV17foobar');

Open in new window

This is what I've got

UPDATE my_table SET year = (SELECT SUBSTRING(string FROM 6 FOR 2) AS year FROM my_table)

Open in new window

I get error "more than one row returned by a subquery used as expression"

baring typos on here the sub query returns the year

Ideally the year column should be type INTEGER but that involves CASTing from text to INTEGER
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pawan KumarDatabase ExpertCommented:
I think you need this.

Please try this -

UPDATE my_table SET year = CAST( SUBSTRING(string FROM 6 FOR 2) AS INT )

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:

I had to use the code bellow because the  SUBSTRING didn't always return a 2 digit value due to string being in different formats

 year character_ varying(2) 

UPDATE my_table SET year = SUBSTRING(string FROM 6 FOR 2)

Open in new window

I now need to identify which rows in year are non numbers

SELECT * FROM  my_table WHERE  year NOT LIKE '%[0-9]%'

Open in new window

Doesn't work
trevor1940Author Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.