PostGreSQL: Update from sub query Syntax

Hi

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

CREATE TABLE my_table(
 id SERIAL PRIMARY KEY,
 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
LVL 1
trevor1940Asked:
Who is Participating?
 
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 )
0
 
trevor1940Author Commented:
Hi,

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
0
 
trevor1940Author Commented:
Thanx
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.