2

I'm storing a value in a variable featureId and then trying to use that value in my SELECT statement, but postgres seems to be taking the name literally and looking for a column called "featureid". I'm getting an error "ERROR: column "featureid" does not exist LINE 4: featureId,"

My code is below. How can I use the value of the variable in my SELECT statement?

SELECT id INTO featureId FROM tableA WHERE NAME = 'some value';

INSERT INTO tableB (client_id, feature_id, does_have)
  SELECT
  id,
  featureId,
  TRUE
FROM tableA
3
  • Where is the declaration and the rest of the block? Commented May 17, 2019 at 20:57
  • @stickybit there isn't one. I'm just running this piece by piece in the editor at the moment Commented May 17, 2019 at 21:01
  • are you tryng to write a trigger? Commented May 17, 2019 at 21:10

2 Answers 2

4

Without a declared variable your SELECT INTO is the version of SELECT INTO that creates a table. To see it for yourself try:

SELECT id
       INTO featureid
       FROM tablea
       WHERE name = 'some value';

SELECT *
       FROM featureid;

For assigning the value to a variable the variable must be declared. You can use an anonymous DO block.

DO
$$
DECLARE
  featureid tablea.id%TYPE;
BEGIN
  SELECT id
         INTO featureid
         FROM tablea
         WHERE name = 'some value';

  INSERT INTO tableb
              (client_id,
               feature_id,
               does_have)
              SELECT id,
                     featureid,
                     true
                     FROM tablea;
END;
$$
LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

Comments

2

There are few errors on what you're tryng to do:

  • sql is declarative language so you're asking what to do not how to do and this is for this reason that you cannot store variables and some statements like declare and begin-end should be used in trigger and not in a simple query.
  • you are executing two statements: select and insert into and they are executed one after the other, so once again you cannot store a variable.
  • insert into, insert a single record but potentially you're tryng to retrieve more data with your select statement (if NAME is not unique)

if 'some-value' is a known constant and NAME is unique just insert that value in the where clause of the insert into. If you're tryng to insert more data take a look on bulk insert syntax of postgres: bulk insert

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.