Postgres: generate IDs automatically - sql

Objective: Have postgres generate ids automatically
CREATE TABLE user_privilege (
id bigint NOT NULL,
name character varying(255) NOT NULL,
version integer
);
CREATE TABLE
INSERT INTO user_privilege (name, version) values ('XYZ', 1);
ERROR: null value in column "id" violates not-null constraint
ALTER TABLE user_privilege ALTER COLUMN id SET DEFAULT nextval('user_privilege_id_seq'::regclass);
ERROR: relation "user_privilege_id_seq" does not exist
Thanks!
EDIT:
I want to keep my id as bigint as all other tables have id as bigint.

You need to use either SERIAL or BIGSERIAL, not BIGINT.
CREATE TABLE user_privilege (
id BIGSERIAL NOT NULL,
It's not clear whether your table has a PRIMARY KEY or UNIQUE constraint. But it should.

You have to create the sequence at first:
CREATE SEQUENCE user_privilege_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
and after you can use it:
ALTER TABLE ONLY user_privilege ALTER COLUMN id SET DEFAULT nextval('user_privilege_id_seq'::regclass);
Here is the create sequence documentation

Related

Postgres Alter ID Start With?

I have an PostgreSQL SQL for creating table. Sometimes i need to TRUNCATE this table. but after this ID primary key, don't start with initial or desired starting value. my question is that how can i restart primary key (id) to desired starting value.
CREATE TABLE IF NOT EXISTS "binance_rules" (
"id" int8 GENERATED ALWAYS AS IDENTITY (START WITH 100100100000),
"THPARS_DATI" timestamp DEFAULT NULL,
"THPARS_LIST" varchar(10) check ("THPARS_LIST" in ('yes','no')) DEFAULT NULL,
"THPARS_PRIO" INT DEFAULT NULL,
PRIMARY KEY ("id")
);
any sql example will be appreciated.
You can alter the table column to restart the counting:
alter table binance_rules alter column id restart;
Here is a db<>fiddle.

POSTGRESQL. Insert or update on table violates foreign key constraint

I am new in Posgresql. I have 5 tables and I am trying to INSERT properties to tables. When I tried to Insert 2nd time, I have this error in 'pgadmin'.
ERROR: insert or update on table "question" violates foreign key constraint "question_id_difficulty_fkey" DETAIL: Key (id_difficulty)=(9) is not present in table "difficulty". SQL state: 23503.
my schema is here
id SERIAL PRIMARY KEY,
name varchar
);
CREATE TABLE question (
id SERIAL PRIMARY KEY,
text varchar,
correct_answer varchar,
incorrect_answer1 varchar,
incorrect_answer2 varchar,
incorrect_answer3 varchar,
id_difficulty SERIAL REFERENCES difficulty(id),
id_category SERIAL REFERENCES category (id),
id_creator SERIAL REFERENCES game (id)
);
CREATE TABLE difficulty (
id SERIAL PRIMARY KEY,
name varchar
);
CREATE TABLE category (
id SERIAL PRIAMRY KEY,
name varchar
);
CREATE TABLE user (
id SERIAL PRIMARY KEY,
name varchar
)
You would need a corresponding entry in the difficulty table with an id of 9, so that a referencing id_difficulty column in the question table.
For example, if your difficulty table contained:
id | name
----+----------------
1 | easy
2 | reasonable
3 | difficult
4 | very difficult
5 | impossible
You could only set id_difficulty for rows in the question table to one of those id values. If you set 6, or 12 or anything other than 1 to 5, it would fail because the values are constrained by the values in the foreign key.
The id_difficulty, id_category and id_creator columns shouldn't be using serial, so these should have their defaults dropped:
ALTER TABLE question ALTER COLUMN id_difficulty DROP DEFAULT;
ALTER TABLE question ALTER COLUMN id_category DROP DEFAULT;
ALTER TABLE question ALTER COLUMN id_creator DROP DEFAULT;
Postgres now recommends using generated always as instead of serial. If you do this, then the types will align much more simply:
CREATE TABLE question (
id int generated always as identity PRIMARY KEY,
text varchar,
correct_answer varchar,
incorrect_answer1 varchar,
incorrect_answer2 varchar,
incorrect_answer3 varchar,
id_difficulty int REFERENCES difficulty(id),
id_category int REFERENCES category (id),
id_creator int REFERENCES game (id)
);
CREATE TABLE difficulty (
id int generated always as identity PRIMARY KEY,
name varchar
);
This makes what is happening much clearer. The data type for a foreign key reference needs to match the data type of the primary key. Postgres knows that serial is really int. But using generated always, it is obvious that they are the same.
In addition, generated always as is more consistent with standard SQL.

How to add unique constraint in postgres on two columns where value of one column is `true`

I have a table in which I need unique EmpId. Duplicate is when there are more than one entry with same EmpId where isDeleted = false
CREATE TABLE someTable (
id serial primary key,
EmpId character varying(15) NOT NULL,
EmpName character varying(15),
isDeleted boolean,
unique (EmpId , isDeleted )//where isDeleted is false
)
There is no constraint of that kind, but you can create a partial unique index (unique constraints are implemented with unique indexes under the hood):
CREATE UNIQUE INDEX ON sometable (empid) WHERE NOT isdeleted;
That will do exactly what you want.
i think for this, you can't use UNIQUE constraint but need to create a custom function
CREATE FUNCTION check_empID(varchar, boolean) RETURNS BOOLEAN
AS
// your implementation
then use it with CHECK constraint
CREATE TABLE someTable (
id serial primary key,
EmpId character varying(15) NOT NULL,
EmpName character varying(15),
isDeleted boolean,
CONSTRAINT ck_active_emp CHECK (check_empID(EmpId, isDeleted))
)
since the function will use the table, then you can create the table without the constraint so you can create and test your function. then alter the table to add the constraint later

Oracle - How do I create a table that has an autoincrementing unique key for the ID

This is the first time that I've use oracle SQL and I'm having a problem creating tables with a unique key.
I don't understand why this auto-incrementing id is not working:
ID BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
The next question I have is why I am getting an error in each of my statements:
ORA-00922: missing or invalid option
Here is my code:
--
-- Sequence for aout incrment
--
CREATE SEQUENCE IF NOT EXISTS AUTO_INC_SEQ
START WITH 1
INCREMENT BY 1;
--
-- Table Person
--
CREATE TABLE IF NOT EXISTS FITNESS_PERSON
(
ID NUMBER NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR NOT NULL,
LAST_NAME VARCHAR NOT NULL,
NICK_NAME VARCHAR NOT NULL,
DATE_BIRTH DATE NOT NULL,
PASSWORD VARCHAR NOT NULL,
CONSTRAINT UNIQUE(NICK_NAME)
);
--
-- Table BMR
--
CREATE TABLE IF NOT EXISTS FITNESS_BMR
(
ID NUMBER NOT NULL PRIMARY KEY,
VALUE FLOAT NOT NULL,
VALUE_DATE DATE NOT NULL
);
--
-- M:N for BMR and Person
--
CREATE TABLE IF NOT EXISTS FITNESS_BMR_PERSON
(
BMR_ID NUMBER NOT NULL,
PERSON_ID NUMBER NOT NULL,
FOREIGN KEY(BMR_ID) REFERENCES FITNESS_BMR(ID),
FOREIGN KEY(PERSON_ID) REFERENCES FITNESS_PERSON(ID),
CONSTRAINT BMR_PER PRIMARY KEY(BMR_ID, PERSON_ID)
);
What's the right way to do this (create a table and with an auto-incrementing key that is unique).
You can use a table, a sequence to generate unique ID values and a trigger.
For example:
Table:
CREATE Table FITNESS_BMR
(
ID NUMBER NOT NULL PRIMARY KEY,
VALUE FLOAT NOT NULL,
VALUE_DATE DATE NOT NULL
);
Sequence: create sequence t1_seq start with 1 increment by 1 nomaxvalue;
Trigger:
CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON FITNESS_BMR
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT t1_seq.nextval INTO :NEW.ID FROM dual;
END;
/

Alter a table column with auto increment by 1 in derby

I have created a table in derby Netbeans and now i realize that i need to make a column as auto incremented by 1 which is a primary key. How can i do so? I tried the following code but was in vain.
ALTER TABLE ISSUERECIPT ALTER IRCODE SET INCREMENT BY 1;
Do i need to create the table once again or can it be possible some other way?
I have found an alternate solution, i dropped the column from the database (thanks vels4j) added the column once again from the netbeans derby UI as shown below:
To alter the column to be auto-generated, the code is
ALTER TABLE ISSUERECIPT ALTER IRCODE SET INCREMENT BY 1;
BUT the column must already be defined with the IDENTITY attribute (as written in this documentation).
In most cases (assuming that you too), the primary key column is not set as IDENTITY. Therefore, you may intend to alter the column to IDENTITY, but that is impossible.
The only way is to drop the table and create it again, as written here.
ALTER TABLE ISSUERECIPT ADD IRCODE INTEGER NOT NULL primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
I guess could do the things for you
Check this
ALTER TABLE ISSUERECIPT
ALTER IRCODE INTEGER NOT NULL
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1);
If your table is empty, Try this
ALTER TABLE DROP PRIMARY KEY your_primaryKeyContrainName ;
ALTER TABLE ISSUERECIPT DROP COLUMN IRCODE ;
ALTER TABLE ISSUERECIPT ADD COLUMN
IRCODE PRIMARY KEY INTEGER NOT NULL
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1);
See Also : Derby ALTER TABLE Syntax
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
The ALTER TABLE statement cannot add an IDENTITY column to a table
If your table is empty or is not in production. drop table and create again, example:
DROP TABLE CUSTOMER;
CREATE TABLE CUSTOMER
(CUSTOMER_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY
1),
FIRSTNAME VARCHAR(100) NOT NULL,VARCHAR(100),
PREFERRED_ID INTEGER,
CONSTRAINT primary_key PRIMARY KEY (CUSTOMER_ID)
);
Try this :
alter table ISSUERECIPT modify column IRCODE int(4) auto_increment
Recreate the table again see example below:
CREATE TABLE students
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(24) NOT NULL,
address VARCHAR(1024),
CONSTRAINT primary_key PRIMARY KEY (id)
) ;