Syntax error with if column on exist with primary key - sql

I want to add a column which's also a primary key if it doesn't already exist on the table. If I do a simple
ALTER TABLE webinars_identities ADD COLUMN IF NOT EXISTS id uuid
It will work but if I do
ALTER TABLE webinars_identities ADD COLUMN IF NOT EXISTS id uuid PRIMARY KEY DEFAULT uuid_generate_v4();
It says it skips the alter table, but for some reason crashes right after:
NOTICE: column "id" of relation "webinars_identities" already exists, skipping
ERROR: multiple primary keys for table "webinars_identities" are not allowed
My original working query was
ALTER TABLE webinars_identities id uuid PRIMARY KEY DEFAULT uuid_generate_v4();
But this is not repeatable without error.
What am I doing wrong here ?

Handle it using duplicate_column exception and issue a notice, because someone rightly said that errors should never pass silently.
DO $body$
BEGIN
ALTER TABLE atable ADD COLUMN id int primary key; --DEFAULT uuid_generate_v4()
EXCEPTION
WHEN duplicate_column THEN
RAISE NOTICE 'ERROR: %,%',SQLSTATE,SQLERRM;
END $body$;
This will work the first time and does not fail on all following attempts, but gives you a message. All other errors if found in your statement will be raised as exceptions.
NOTICE: ERROR: 42701,column "id" of relation "atable" already exists
DO

Try this.
DO $$ BEGIN TABLE atable ADD COLUMN IF NOT EXISTS id int primary key ; exception when others then null ; END$$;

It's a bug in postgres https://www.postgresql.org/message-id/13277.1566920001%40sss.pgh.pa.us
Will be fixed in v13.0, hopefully.

Related

Why is the column not altering when I try to convert it to UUID?

I have a primary key column in my SQL table in PostgreSQL named "id". It is a "bigseries" column. I want to convert the column to a "UUID" column. It entered the below command in the terminal:
alter table people alter column id uuid;
and
alter table people alter column id uuid using (uuid_generate_v4());
but neither of them worked.
In both tries I got the error message
ERROR: syntax error at or near "uuid"
LINE 1: alter table people alter column id uuid using (uuid_generate...
What is the correct syntax?
First of all uuid_generate_v4() is a function which is provided by an extension called uuid-ossp. You should have install that extension by using;
CREATE EXTENSION uuid-ossp;
Postgresql 13 introduced a new function which does basically the same without installing extension. The function is called gen_random_uuid()
Suppose that we have a table like the one below;
CREATE TABLE people (
id bigserial primary key,
data text
);
The bigserial is not a real type. It's a macro which basically creates bigint column with default value and a sequence. The default value is next value of that sequence.
For your use case, to change data type, you first should drop the old default value. Then, alter the type and finally add new default value expression. Here is the sample:
ALTER TABLE people
ALTER id DROP DEFAULT,
ALTER id TYPE uuid using (gen_random_uuid() /* or uuid_generate_v4() */ ),
ALTER id SET DEFAULT gen_random_uuid() /* or uuid_generate_v4() */ ;
CREATE TABLE IF NOT EXISTS people (
id uuid NOT NULL CONSTRAINT people_pkey PRIMARY KEY,
address varchar,
city varchar(255),
country varchar(255),
email varchar(255),
phone varchar(255)
);
This is the correct syntax to create table in postgres SQL, it's better to do these constraints at beginning to avoid any error.
For using alter command you would do the following:
ALTER TABLE customer ADD COLUMN cid uuid PRIMARY KEY;
Most of errors that you could find while writing command either lower case or undefined correct the table name or column.

Postgres breaking null constraint on a serial column

I have a table that I create independently, the primary key is set with the serial type and a sequence applied to the table, but when I try to insert a value a NULL CONSTRAINT error is thrown and the return looks like null was passed, am I missing something in the INSERT statement?
SQL for table generation:
DROP TABLE IF EXISTS public."Team" CASCADE;
CREATE TABLE public."Team" (
"IdTeam" serial PRIMARY KEY,
name text NOT null,
CONSTRAINT "pKeyTeamUnique" UNIQUE ("IdTeam")
);
ALTER TABLE public."Team" OWNER TO postgres;
DROP SEQUENCE IF EXISTS public."Team_IdTeam_seq" CASCADE;
CREATE SEQUENCE public."Team_IdTeam_seq"
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public."Team_IdTeam_seq" OWNER TO postgres;
ALTER SEQUENCE public."Team_IdTeam_seq" OWNED BY public."Team"."IdTeam";
SQL for insert :
INSERT INTO public."Team" (name) values ('Manchester Untited');
The returning error:
ERROR: null value in column "IdTeam" violates not-null constraint
DETAIL: Failing row contains (null, Manchester Untited).
SQL state: 23502
I am baffled. Why are you trying to define your own sequence when the column is already defined as serial?
Second, a primary key constraint is already unique. There is no need for a separate unique constraint.
Third, quoting identifiers just makes the code harder to write and to read.
You can just do:
DROP TABLE IF EXISTS public.Team CASCADE;
CREATE TABLE public.Team (
IdTeam serial PRIMARY KEY,
name text NOT null
);
INSERT INTO public.Team (name)
VALUES ('Manchester Untited');
Dropping the sequence causes the default definition for the IdTeam column to be dropped. After recreating the sequence you will have to recreate the default definition.

How to create a conditional trigger

I have a table with an id as auto incremented primary key and another id.
CREATE TABLE tester (
"id" integer PRIMARY KEY AUTOINCREMENT,
"refId" integer DEFAULT 0
);
refId should be able to either be 0 (the default) or reference id if refId > 0 (i.e. act as foreign key).
Now I need two constraints:
A row should only be deletable if its id is not used (referenced?) by any other row's refId
A row should only be deletable if its refId is 0.
From what I have understood, I need to create a trigger that checks for these constraints before a DELETE event happens. And depending on refId's value either abort the delete action or allow it.
However, I have a hard time understanding the syntax for this and how to do a conditional check. But what I have so far (in mind!) is concerning 1.):
CREATE TRIGGER no_delete_if_inuse
BEFORE DELETE ON tester
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'cannot delete because of foreign key violation')
WHERE (SELECT "refId" FROM tester WHERE "refId" = OLD."id") IS NOT NULL;
END;
And concerning 2.)
CREATE TRIGGER no_delete_if_ref
BEFORE DELETE ON tester
FOR EACH ROW BEGIN
IF OLD."refId" > 0 THEN RAISE(ABORT, "cannot delete tester because it refers to an existing tester");
END;
Does this make sense and is valid?
I am totally not sure, to me it does but well, I am all noob.
Also as a last question, can I alternatively combine this into a single trigger? For example would this be a valid query:
CREATE TRIGGER no_delete_if_inuse
BEFORE DELETE ON tester
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'cannot delete because of foreign key violation')
WHERE (SELECT "refId" FROM tester WHERE ("refId" = OLD."id" OR "refId" > 0) ) IS NOT NULL;
END;
You can define a foreign key referring to the same table. Use null instead of 0 for rows without a reference:
create table tester(
id int primary key,
refid int references tester,
check (id <> refid)
);
insert into tester values
(1, null),
(2, null),
(3, 1),
(4, 3);
You need a trigger to ensure that a row which references another one cannot be deleted.
create or replace function before_delete_on_tester()
returns trigger language plpgsql as $$
begin
if old.refid is not null then
raise exception
'Cannot delete: (id)=(%) references (id)=(%)', old.id, old.refid;
end if;
return old;
end $$;
create trigger before_delete_on_tester
before delete on tester
for row execute procedure before_delete_on_tester();
Test:
delete from tester where id = 1;
ERROR: update or delete on table "tester" violates foreign key constraint "tester_refid_fkey" on table "tester"
DETAIL: Key (id)=(1) is still referenced from table "tester".
delete from tester where id = 4;
ERROR: Cannot delete from tester. (id)=(4) references (id)=(3)
CONTEXT: PL/pgSQL function before_delete_on_tester() line 4 at RAISE
In Postgres you have to define a trigger function. Read more:
Overview of Trigger Behavior
Trigger Procedures
Create Trigger

Why is trigger not fired on every single row when using "insert select" or "merge"

I defined a BEFORE INSERT trigger for a table and it works as expected for single INSERTstatements, but not for INSERT ... SELECT nor MERGE statements.
These are my database objects (simplified):
CREATE TABLE "COMPANY" (
"ID" NUMBER NOT NULL,
"NAME" VARCHAR(100)
);
CREATE TABLE "EMPLOYEE" (
"ID" NUMBER NOT NULL,
"COMPANY_ID" NUMBER NOT NULL
);
CREATE UNIQUE INDEX "EMPLOYEE_PK" ON "EMPLOYEE" ("ID");
CREATE SEQUENCE "EMPLOYEE_SEQUENCE";
CREATE TRIGGER "BI_EMPLOYEE" BEFORE INSERT ON "EMPLOYEE"
REFERENCING NEW AS newrow FOR EACH ROW BEGIN ATOMIC
IF newrow.id IS NULL THEN
SET newrow.id = NEXT VALUE FOR employee_sequence;
END IF;
END;
If single INSERTstatements are executed, everything works as expected, the ÌD is fetched from the sequence. But if I execute something like
INSERT INTO employee (company_id) SELECT id FROM company;
the I get an error:
integrity constraint violation: unique constraint or index violation: "EMPLOYEE_PK"
which could propably mean that it tries to insert the same key from the sequence twice.
I'm using the latests version 2.3.2 of HSQLDB.
Because triggers are set based, not row based.
See details here

Why does this 'modify table' statement fail?

I'm trying to add a 'not null' constraint to a column in Oracle 9.
ALTER TABLE user_roles modify group_id varchar2(36 char) set not null;
However, the operation fails with an odd error:
Error report:
SQL Error: ORA-12987: cannot combine drop column with other operations
12987. 00000 - "cannot combine drop column with other operations"
*Cause: An attempt was made to combine drop column with other
ALTER TABLE operations.
*Action: Ensure that drop column is the sole operation specified in
ALTER TABLE.
Any ideas why this is failing?
Remove set:
ALTER TABLE user_roles modify group_id varchar2(36 char) not null
And yes, Oracle's errors can be very misleading.
It turns out the syntax of the above statement is wrong. It should be:
ALTER TABLE user_roles modify group_id varchar2(36 char) not null;
Still, the presence of an erroneous 'set' leads to a very odd error!
I'm trying to add a 'not null'
constraint to a column in Oracle 9.
If you are really trying jsut to make the column NOT NULL (i.e. you don't want to change the datatype at the same time) you just need to
ALTER TABLE user_roles modify not null;