I'm using Oracle SQL and I was wondering whether I can use a sub-query inside a CHECK constraint when I am creating a new table. Please consider the following example:
Suppose I want to create a table called EnrollsIn and it has two attributes - student and course. student is a string that holds an unique student ID and the course attribute holds a string of course code.
CREATE TABLE EnrollsIn (
student char(8) PRIMARY KEY,
course char(7),
-- Insert constraint here (Constraint is written below)
);
INSERT INTO EnrollsIn VALUE ('12345678', 'COMP200');
INSERT INTO EnrollsIn VALUE ('12345678', 'COMP300');
INSERT INTO EnrollsIn VALUE ('12345678', 'COMP400');
INSERT INTO EnrollsIn VALUE ('12345678', 'MATH100'); -- This violates the constraint written below!
Now, I want this table to have a constraint that a single student can only enroll in maximum of 3 courses. In other words, the following query should always have the value of enrollCount <= 3 for each student:
-- I want the value "enrollCount" always <= 3 for all students
SELECT student, count(*) as enrollCount FROM EnrollsIn GROUP BY student;
Am I allowed to use this sub-query when defining the CHECK constraint inside the CERATE TABLE EnrollsIn statement? If so, how can I define this constraint?