How can I define a composite primary key in SQL?

SqlPrimary KeyComposite Primary-Key

Sql Problem Overview


How can I define a composite primary key consisting of two fields in SQL?

I am using PHP to create tables and everything. I want to make a table name voting with fields QuestionID, MemeberID, and vote. And the Composite primary key consists of the fields QuestionID and MemberID.

How should I do this?

Sql Solutions


Solution 1 - Sql

Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:

CREATE TABLE voting (
  QuestionID NUMERIC,
  MemberID NUMERIC,
  PRIMARY KEY (QuestionID, MemberID)
);

The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:

SELECT * FROM voting WHERE QuestionID = 7

it will use the primary key's index. If however you do this:

SELECT * FROM voting WHERE MemberID = 7

it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.

If necessary, add an index on the other:

CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);

Solution 2 - Sql

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

Solution 3 - Sql

QuestionID will be the primary key in your case. You can use MemberID as a candidate key (indexing will be on this) as one member may answer multiple Questions. The other way around will not make sense.

Syntax:

CREATE TABLE SAMPLE_TABLE  
(COL1 integer,  
COL2 integer,  
COL3 integer,  
PRIMARY KEY (COL1, COL2));  

Solution 4 - Sql

In Oracle database we can achieve like this.

CREATE TABLE Student(
  StudentID Number(38, 0) not null,
  DepartmentID Number(38, 0) not null,
  PRIMARY KEY (StudentID, DepartmentID)
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZeeshan RangView Question on Stackoverflow
Solution 1 - SqlcletusView Answer on Stackoverflow
Solution 2 - SqlJustinView Answer on Stackoverflow
Solution 3 - SqlVivek GuptaView Answer on Stackoverflow
Solution 4 - SqlMinhajuddin KhajaView Answer on Stackoverflow