Question

I am learning triggers in PostgreSQL.

I have created a trigger function update_name():

CREATE OR REPLACE FUNCTION update_name()
RETURNS trigger AS
$BODY$
BEGIN
    NEW.name := "ankit";
    RETURN NEW;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION update_name()
  OWNER TO postgres;

My table user_table is:

CREATE TABLE user_table (
  name character varying(20) NOT NULL,
  password character varying(20),
  email character varying(20),
  gender character varying(20),
  phone bigint,
  CONSTRAINT user_table_pkey PRIMARY KEY (name)
);

and the trigger for the table is :

CREATE TRIGGER "change-name"
BEFORE INSERT OR UPDATE
  ON user_table
  FOR EACH ROW
  EXECUTE PROCEDURE update_name();

when I am inserting data to my table using query:

INSERT INTO user_table(name, password, email, gender, phone)
VALUES ('aa', '9874', 'poi@ka.in', 'male', 8978987896);

I've got the error:

ERROR:  column "ankit" does not exist
LINE 1: SELECT "ankit"
               ^
QUERY:  SELECT "ankit"
CONTEXT:  PL/pgSQL function update_name() line 3 at assignment

********** Error **********

ERROR: column "ankit" does not exist
SQL state: 42703
Context: PL/pgSQL function update_name() line 3 at assignment

What am I doing wrong?

Was it helpful?

Solution

This is about PostgreSQL syntax. I removed irrelevant references to pgAdmin from the question.

In Postgres, literal values (constants) are enclosed in single quotes: 'value'.
Double quotes are reserved for identifiers but optional as long as it consists of legal, lower-case letters: "Odd Name" vs. odd_name.

This is also the SQL standard. Start by reading the chapter "Lexical Structure" in the manual.

OTHER TIPS

The ERROR has gone by changing just:

NEW.name := "ankit";

to

NEW.name := 'ankit';

Why is it so???

CREATE OR REPLACE FUNCTION update_name()
RETURNS trigger AS
$BODY$
    BEGIN
     RAISE NOTICE 'RECORD IS INSERTED %',NEW.name;
            INSERT INTO user_table VALUES("ankit",NEW.password,NEW.email,NEW.gender,NEW.phone);
            RETURN NEW;
        end if;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION update_name()
  OWNER TO postgres;

Try this out this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top