2

For example, I have to program an enrolment table which has:

  1. enrolment_id
  2. academic_period
  3. results
  4. student_id
  5. subject

I want to enforce to make sure that a student can't enroll in a subject more than once in a specific academic period. So, the constraint shall involve student_id, subject, and academic period columns.

I'm still unsure how do I make this happen. Any help?

gbn
  • 422,506
  • 82
  • 585
  • 676
nfnmy
  • 157
  • 1
  • 4
  • 14

4 Answers4

14

Add a unique constraint to your table:

ALTER TABLE yourtable ADD CONSTRAINT constraintname UNIQUE (student_id, subject, academic_period)
Maximilian Mayerl
  • 11,253
  • 2
  • 33
  • 40
3

Create a unique constraint on academic_period, student_id, subject
I'll let you work out the actual SQL

Note: this is correctly your natural key: enrolment_id is a surrogate added at implementation time because of the database architecture. It isn't mandated in any design or modelling process

Community
  • 1
  • 1
gbn
  • 422,506
  • 82
  • 585
  • 676
1

Add a unique constraint. From here:

To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons
 (
 P_Id int NOT NULL,
 LastName varchar(255) NOT NULL,
 FirstName varchar(255),
 Address varchar(255),
 City varchar(255),
 CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
 )

(Modify the above for the column(s) you need to set as unique)

David
  • 72,686
  • 18
  • 132
  • 173
0

You would just get the amount of rows returned from this example query:

SELECT COUNT(*) FROM enrollment WHERE student_id = 'XYZ' AND subject = 'ABC' AND academic_period = 'DEF'

If the amount of rows returned is greater than 0, they have already been enrolled in that subject in the academic period.

Marcus Recck
  • 5,075
  • 2
  • 16
  • 26
  • This can return 0 falsely because of concurrency effects, especially when using InnoDB which uses MVCC – gbn May 03 '12 at 13:56