Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLSTATE[22P02]: Invalid text representation

I'm using Postgresql and PHP 5.3.x with PDO to access the DB.

I have this the SQL query (stripped down version), with a placeholder for PDO to fill in:

INSERT INTO t_articles (a_article_id) VALUES (?) RETURNING a_id

I want a_article_id to be either a number, like 5, or else it should be the result of the subquery:

((SELECT max(a_article_id) FROM t_articles) + 1)

However, PDO says:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "(SELECT max(a_article_id) FROM t_articles) + 1"

And I've tried to set the subquery as the default value, but it is not allowed apparently:

ERROR:  cannot use sub query in default expression

How can I insert the result of this sub query (or what can be done to achieve the same result)?

like image 288
conradkleinespel Avatar asked Nov 14 '25 18:11

conradkleinespel


1 Answers

You'd have to use INSERT...SELECT for that:

insert into t_articles (a_article_id)
select max(a_article_id) + 1
from t_articles
returning id

Or if you don't need contiguous values for a_article_id, use a sequence for it:

  1. Create a sequence, we'll call it article_id_sequence.

    -- Get the current max(a_article_id)+1 to use instead of FIRST_VAL below
    create sequence article_id_sequence
    start FIRST_VAL
    owned by t_articles.a_article_id;
    
  2. Set the default value for t_articles.a_article_id to nextval('article_id_sequence').

    alter table t_articles
    alter column a_article_id
    set default nextval('article_id_sequence');
    
  3. Use the default value when inserting:

    insert into t_articles (a_article_id)
    values (default)
    returning id;
    
like image 175
mu is too short Avatar answered Nov 17 '25 07:11

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!