How to set two columns in SQL

I create a table, in a table two columns are unique, I mean that columnA and columnB do not have the same value: for example:

Table X
A B
1 2(RIGHT,unique)
2 2(RIGHT, unique)
1 3(RIGHT, not unique)
2 3(RIGHT, not unique)
1 2 (WRONG, not unique)

How to create such a table? many thanks!

create table X 
(
[ID] INTEGER PRIMARY KEY AUTOINCREASE NOT NULL,\
[A] INTEGER,
[B] INTEGER);
+3
source share
2 answers

Create a unique key column:

CREATE TABLE X
(
    ID INTEGER PRIMARY KEY AUTOINCREASE NOT NULL,
    A INTEGER,
    B INTEGER,
    UNIQUE KEY(A, B)
);

INSERT INTO X(A, B) VALUES(1, 2);
INSERT INTO X(A, B) VALUES(2, 2);
INSERT INTO X(A, B) VALUES(1, 3);
INSERT INTO X(A, B) VALUES(2, 3);
INSERT INTO X(A, B) VALUES(1, 2);

The last row will not work, because a combination of a = 1 and b = 2 already exists in the table.

+3
source
CREATE UNIQUE INDEX `my_index_name` ON `my_table` (`col1`,`col2`)
+2
source

Source: https://habr.com/ru/post/1750445/


All Articles