Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Postgres, how do you insert possible values for a particular column?

I have a table name ar for column operation in it I can allow only specific values (‘C’, ‘R’, ‘RE’, ‘M’, ‘P’). I have added a check constraint for it.

Requirement:
I need to insert 1 million records in the table but operation column has a constraint that only specific values are allowed. I am using generate_series() to generate values which generates random values and throws error. How can I avoid the error and insert 1 million record with only the required values (‘C’, ‘R’, ‘RE’, ‘M’, ‘P’) in column named operation.

CREATE TABLE ar (
  mappingId TEXT,
  actionRequestId integer,
  operation text,
  CONSTRAINT chk_operation CHECK (operation IN ('C', 'R', 'RE', 'M', 'P'))
);
INSERT INTO ar (mappingId, actionRequestId, operation)
SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer,
       substr(md5(random()::text), 1, 10)
FROM generate_series(1, 1000000);
ERROR: new row for relation "ar" violates check constraint "chk_operation"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do a cross join with the allowed values:

INSERT INTO ar (mappingid, actionrequestid, operation)
SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer, 
       o.operation
FROM generate_series(1, 1000000 / 5)
   cross join ( 
     values ('C'), ('R'), ('RE'), ('M'), ('P')
   ) as o(operation);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading