iam create a table using below command in postgresql.
CREATE TABLE someTable (
id serial primary key,
col1 int NOT NULL,
col2 int NOT NULL,
unique (col1, col2)
);
then am execute 2 insert statements.
insert into someTable (col1,col2) values(1,11),(1,12);
its working
insert into someTable (col1,col2) values(1,13),(1,14),(1,11);
got error (key(col1,col2)=(1,11) is already exist.
But i need to avoid only duplicate pairs. How it will be possible ?
iam try this with
PostgreSQL 9.5.0 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit and PostgreSQL 9.3 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit
but i got error
i need ot put like this after executing two statements.
(1,11),(1,12),(1,13),(1,14)
When you define a primary key or a unique constraint for a table, PostgreSQL automatically creates a corresponding UNIQUE index. In this statement, the employee_id is the primary key column and email column has a unique constraint, therefore, PostgreSQL created two UNIQUE indexes, one for each column.
When you add a UNIQUE constraint to a column or a group of columns, PostgreSQL will automatically create a unique index on the column or the group of columns. The following statement creates a new table named person with a UNIQUE constraint for the email column.
Using the query above we can only insert unique ingredients. If we try to insert an ingredient that’s already in Postgres gives us back an error. ERROR: duplicate key value violates unique constraint “ingredients_ingredient_key” DETAIL: Key (ingredient)= (paprika) already exists.
If you define a UNIQUEindex for two or more columns, the combined values in these columns cannot be duplicated in multiple rows. PostgreSQL treats NULL as distinct value, therefore, you can have multiple NULLvalues in a column with a UNIQUEindex.
You can do this using insert . . . select
:
insert into someTable(col1, col2)
select col1, col2
from (select 1 as col1, 13 as col2 union all
select 1, 14 union all
select 1, 11
) t
where not exists (select 1
from someTable st
where st.col1 = t.col1 and st.col2 = t.col2
);
That is, filter the values out before the insert
.
EDIT:
As a-horse-with-no-name points out, you can also write this as:
insert into someTable(col1, col2)
select col1, col2
from (values (1, 13), (1, 14), (1, 11)
) as t(col1, col2)
where not exists (select 1
from someTable st
where st.col1 = t.col1 and st.col2 = t.col2
);
I tend to use the union all
approach because not all databases support this use of the values()
statement.
using postgresql 9.5 (latest release)
use query like this
insert into someTable (col1,col2) values(1,13),(1,14),(1,11) ON CONFLICT DO NOTHING;
it will avoid duplication without any extra line of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With