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

SQL table with primary key over two columns and unique values in both columns

How to create a table in SQL with the following attributes?

  • The table has two columns A and B.
  • The primary key of the table is (A, B).
  • All values in A are unique. Pseudo code: (Count(A) == COUNT(SELECT DISTINCT A)).
  • All values in B are also unique.
CREATE TABLE IF NOT EXISTS myTable(
    A VARCHAR(32) PRIMARY KEY NOT NULL, -- A HAS DISTINCT VALUES
    B VARCHAR(32) NOT NULL              -- B HAS DISTINCT VALUES
);

INSERT INTO myTable VALUES ('A1', 'B1') --> Add value
INSERT INTO myTable VALUES ('A1', 'B2') --> Do not add value
INSERT INTO myTable VALUES ('A2', 'B2') --> Add value
INSERT INTO myTable VALUES ('A3', 'B3') --> Add value
INSERT INTO myTable VALUES ('A4', 'B3') --> Do not add value
INSERT INTO myTable VALUES ('A4', 'B4') --> Add value
INSERT INTO myTable VALUES ('A5', 'B6') --> Add value

>Solution :

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

CREATE TABLE myTable
(
    A VARCHAR(32) NOT NULL,
    B VARCHAR(32) NOT NULL,
    CONSTRAINT PK_AB primary key (A,B),
    CONSTRAINT UQ_A UNIQUE(A),
    CONSTRAINT UQ_B UNIQUE(B)
);

Please note: a table with just 2 columns with both columns in the primary key smells funny.

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