SQL : unique values across two columns - sql

Is there a constraint for values not being unique taking in consideration two columns, ex -
id | secondid
+---------------+
3 | 4
4 | 5
id | secondid
+---------------+
3 | 4
5 | 4
id | secondid
+---------------+
4 | 4
4 | 4
All the above cases are not okay, as 4 occurs twice in either id or secondid but something like
id | secondid
+---------------+
1 | 3
2 | 4
is okay as all the values in both the columns are unique, is there any way for me to achieve this without using any packages in postgresql?

You can do this with a combination of an exclusion constraint and a check constraint. The check constraint is needed to prevent duplicates within one row.
create table t (
id int,
id2 int,
check (id <> id2),
exclude using gist ( (array[id, id2]) with &&)
);
The exclusion constraint operates by checking the specified operator never returns "true" for the column in the "new" row and all rows already in the table. It does not check values within the current row, which is why the check constraint is also needed.
Here is a db<>fiddle.

You want a unique constraint that works on the two columns as if these were just one column. I think this is not possible directly. (Others may correct me.)
What you can do is create another table
create table check_unique_id (id int primary key);
and fill it via a trigger. I.e. every time you insert a row in your table, the trigger creates two rows in the check_unique_id table. If an ID occurs twice that other table will raise the exception.

Related

Postgresql: Unique constraint over Union of 2 columns

I have the following tables:
TRANSACTIONS
id | amount
------------------
1 | 100
2 | -100
3 | 250
4 | -250
TRANSACTION_LINKS
id | send_tx | receive_tx
---------------------------
1 | 2 | 1
2 | 4 | 2
The send_tx and receive_tx columns in the transaction links table use foreign keys pointing to the ID of the transactions table.
This is how I create the transaction links table
CREATE TABLE IF NOT EXISTS transaction_links
(
id BIGSERIAL PRIMARY KEY,
send_id INT NOT NULL UNIQUE REFERENCES transactions(id) ON DELETE
RESTRICT,
receive_id INT NOT NULL UNIQUE REFERENCES transactions(id) ON DELETE
RESTRICT
);
I want to create a unique constraint over both send_tx and receive_tx, meaning that if transaction id 1 is found in the receive_tx column, then
no other transaction link can have the receiving_tx = 1
no other transaction link can have the sending_tx = 1
I know that I can have a unique constraint on each column separately, but that only solves my first problem
EDIT:
essentially, if I insert (1,2) into transaction links, then inserting (1,3) or (3,1) or (4,2) or (2,4) should all be rejected
Also, in my design, the transactions table contains many more columns than what is shown here, I've only included the amount for simplicity's sake.
You can use an exclusion constraint which only requires a single index:
alter table transaction_links
add constraint check_tx
exclude using gist ( (array[send_id, receive_id]) with &&);
The && operator is the "overlaps" operator for arrays - which means "have elements in common, regardless of the order of the elements in the array. In this case the constraint prevents to insert any row where any value of (send_id, receive_id) appears in some other row of the table (regardless of the column).
However, you need the intarray extension for that.
Online example: https://rextester.com/QOYS23482

duplicate key value violates unique constraint with on conflict is not working

I am trying to use on conflict with unique on multiple fields. I have this structure.
|---------------------|------------------|
| id | uuid |
|---------------------|------------------|
| name | string |
|---------------------|------------------|
| field_a | uuid |
|---------------------|------------------|
| field_b | uuid |
|---------------------|------------------|
| field_c | uuid |
|---------------------|------------------|
field_a,field_b,field_c are unique and field_b can be NULL.
This is my query:
INSERT INTO table (field_a, field_b,field_c, name)
values ('434d1d67-df03-4310-b3eb-93bf1c6e319e',
'd3a3745e-ad97-4fcd-1fed-26bb406dc265',
'd5a4232e-ad56-6ecd-5fed-25bb106dc114')
on conflict(field_a,field_b,field_c)
do update
set name = 'abc'
If I try this with same query again it works. It updates on conflict. But when I use null like this:
INSERT INTO
table (field_a, field_b,field_c, name)
values ('434d1d67-df03-4310-b3eb-93bf1c6e319e',
null,
'd5a4232e-ad56-6ecd-5fed-25bb106dc114')
on conflict(field_a,field_b,field_c)
do update
set name = 'abc'
This does not work. This will add new row in my table. To prevent adding new row I created an index and set NULL values like this
CREATE
UNIQUE INDEX uidx_uniq ON table USING btree (
(COALESCE(field_a, '00000000-0000-0000-0000-000000000000'::uuid)),
(COALESCE(field_a, '00000000-0000-0000-0000-000000000000'::uuid)),
(COALESCE(field_a, '00000000-0000-0000-0000-000000000000'::uuid)))
This does not allow adding new value in db if any exists with null but on conflict does not work with this it gives me Error:
duplicate key value violates unique constraint "uidx_uniq"
How can I resolve this with null?
As the documentation says:
Null values are not considered equal.
So there is no conflict if one of the values is NULL.
You cannot use the unique index you created with the ON CONFLICT clause, because you can only use unique constraints there. Unique constraints cannot be defined on expressions, only on columns.
Perhaps you should use a different value that NULL so model what you mean. NULL means “unknown” in SQL, so PostgreSQL's interpretation makes sense.
I think you also want a filtered unique index:
CREATE UNIQUE INDEX uidx_uniq2 ON table (field_a, field_c)
WHERE field_b IS NULL;
You'll need to check both indexes for conflicts in ON CONFLICT.

Validate whether value in one table is the same as in related table - performance

Let's say I have two tables and I'm doing all the operations in .NET Core 2 Web API.
Table A:
Id,
SomeValue,
TeamName
Table B:
Id,
Fk_Id_a (references Id in table A),
OtherValue,
TeamName
I can add and get records from table B indepedently.
But for every record in Table B TeamName has to be the same as for it's corresponidng Fk_Id_a in Table A.
Assume these values comes in:
{
"Fk_Id_a": 3,
"SomeValue": "test val",
"TeamName": "Super team"
}
Which way would be better to check it in terms of performance? 1ST way requires two connections, when 2nd requires storing some extra keys etc.
1ST WAY:
get record from Table A for Fk_Id_a (3),
check if TeamName is the same as in coming request (Super team),
do the rest of the logic
2ND WAY:
using compound foreign keys and indexes:
TableA has alternate unique key (Id, TeamName)
TableB has foreign compound key (Fk_Id_a, TeamName) that references TableA (Id, TeamName)
SQL SCRIPT TO SHOW:
ALTER TABLE Observation
ADD UNIQUE (Id, PowelTeamId)
GO
ALTER TABLE ObservationPicturesId
ADD FOREIGN KEY(ObservationId, PowelTeamId)
REFERENCES Observation(Id, PowelTeamId)
ON DELETE CASCADE
ON UPDATE CASCADE
EDIT: Simple example how the tables might look like. TeamName has to be valid for FK referenced value in Table A.
Table A
ID | ObservationTitle | TeamName
---------------------------------------
1 | Fire damage | CX_team
2 | Water damage | CX_team
3 | Wind damage | Dd_WP3
Table B
ID | PictureId | AddedBy | TeamName | TableA_ID_FK
-----------------------------------------------------
1 | Fire | James | CX_team | 1
2 | Water | Andrew | CX_team | 1
3 | Wind | John | Dd_WP3 | 3
Performance wise, the 2nd option would be faster because there is no comparison to check (the foreign key will force that they match when inserting, updating or deleting) when selecting the rows from the table. It would also make a unique index on table A.
That being said, there is something very fishy about the structure you mention. First of all why is the TeamName repeated in table B? If a row in table B is "valid" only when the TeamName match, then you should enforce that no row should be inserted with a different TeamName, throught the ID foreign key (and not actually storing the TeamName value). If there are records on table B that represent another thing rather than the entity that is linked to table A then you should split it onto another table or just update the foreign key column when the team matches and not always.
The issue is that you are using a foreign key as a partial link, making the relationship valid only when an additional condition is true.

How to update rows of two tables that have foreign key restrictions

I have two tables: one is foreign reference table lets say table a and other one is the data table lets say table b.
Now, when I need to change the data in table b, but I get restricted by table a.
How can I change "rid" in both tables without getting this message?
"ERROR: insert or update on table "table a" violates foreign key
constraint "fk_boo_kid" SQL state: 23503
Detail: Key (kid)=(110) is not present in table "table b".
Example query to update both tables:
UPDATE table b table a SET rid = 110 WHERE rid =1
table b
+-----+-------+-------+
| rid | ride | qunta |
+-----+-------+-------+
| 1 | car | 1 |
| 2 | bike | 1 |
+-----+-------+-------+
table a
+-----+-----+------------+
| kid | rid | date |
+-----+-----+------------+
| 1 | 1 | 20-12-2015 |
| 2 | 2 | 20-12-2015 |
+-----+-----+------------+
In Postgres you can use a writeable CTE to update both tables in a single statement.
Assuming this table setup:
create table a (rid integer primary key, ride text, qunta integer);
create table b (kid integer primary key, rid integer references a, date date);
The CTE would be:
with new_a as (
update a
set rid = 110
where rid = 1
)
update b
set rid = 110
where rid = 1;
As (non-deferrable) foreign keys are evaluated on statement level and both the primary and foreign key are changed in the same statement, this works.
SQLFiddle: http://sqlfiddle.com/#!15/db6d1/1
you can not update/delete primary key in table B, because the primary key is used in table A.
you can delete primary key in table B, IF >>
you must delete the row in table A which is used primary key table B.
you can delete the row in table B
you have to change both manual
SET session_replication_role = 'replica';
UPDATE table a SET rid=110 WHERE rid=1 ;
UPDATE table b SET rid=110 WHERE rid=1 ;
SET session_replication_role = 'origin';
This is too long for a comment.
You should really explain why you want to change ids into something else. Primary keys really should be considered immutable, so they identify rows both within a table and over time.
If you do need to change them for some reason, then define proper foreign key constraints for the tables in question. Then define the foreign keys to be on update cascade. This will "cascade" changes to all affected changes when a primary key changes.

Inserting 2 rows, each to different tables where one row refrences the other's primary key

Hello folks
Checkout this scenario
Table 1 columns -> | table_1_id (pkey) | some_column | comments |
Table 2 columns -> | table_2_id (pkey) | some_other_column | table_1_id (fkey) | comments |
All primary keys are of type serial or auto number.
The 3rd column on Table 2 is an fk that references Table 1's primary key.
I would like to insert rows into both programmaticaly (from a c++ app)
Do i have to insert to table one then SELECT-query the entry's primary key then insert the Table 2 row with the pkey result?
Is there a more efficient way of handling this? Say using almost 2 queries?
I would suggest looking http://wiki.postgresql.org/wiki/FAQ
The site is a useful resource to go through to get familiar with PostgreSQL
Specifically, the section How do I get the value of a SERIAL insert?
The simplest way is to retrieve the
assigned SERIAL value with RETURNING.
Using the example table in the
previous question, it would look like
this:
INSERT INTO person (name) VALUES
('Blaise Pascal') RETURNING id;
You can also call nextval() and use that value in the INSERT, or call currval() after the INSERT.
If you don't need the table_1_id value in your application, you can skip retrieving it completely:
INSERT INTO table_1(cols...) VALUES(vals...)
INSERT INTO table_2(table_1_id, cols...) VALUES(currval('table_1_table_1_id_seq'), vals...)