I have a table ‘Student’, and several attributes – two of which are important in this particular problem. I need to make sure that any student with the classification (grade level) of ‘junior’ has between exactly 55 and 84 hours (credits).
Here’s what I have have so far declaration-wise in Oracle (deleted unnecessary code):
CREATE TABLE Students (
id INTEGER,
name CHAR(10) NOT NULL,
classification CHAR(10) NOT NULL,
hours INTEGER,
gpa NUMBER(3,2) NOT NULL,
mentor INTEGER,
-- IC4:
-- To be classified as a 'junior', a student must have
-- completed between 55 and 84 hours (inclusive).
CONSTRAINT IC4 CHECK (classification != 'junior' AND (hours < 55 AND hours > 84))),
);
Oracle throws the error:
ERROR at line 23: ORA-00922: missing or invalid option
I am certain that I haven’t formatted the constraint correctly, but my professor spent about 3 seconds on declarations and told us to figure it out for ourselves. I know 1-attribute constraints, but I don’t know how to mix and match 2 attributes at the same time. Can someone help me out?
*Essentially in any other code it would look like nested if-statements:
if (classification == "junior") {
if (hours < 55 && hours > 84)
throwSomeError("Foolish!");
}
I just can’t seem to translate that into SQL. My apologies if the spacing in this darn thing is bizarre, I can’t get it to format to save my life.
You have a trailing comma right at the end, and one too many closing brackets:
Unless you’ve cut something out before posting, which may be the case as the error references line 23 (but hopefully not as it’s tricky to see a problem in code you can’t see at all). What you have compiles if that becomes:
But the condition is wrong anyway, as others have pointed out. One way of getting the result I think you want is:
The
ORmeans that thehourscheck is only applied when theclassificationis'junior', and any otherclassificationis not restricted. (If you need different rules for different classifications, have a look at the very similar question Chris Saxon linked to in comments).With some test data:
BETWEENis inclusive, so this is the same as:You might also want a check constraint on
classification, particularly as this constraint is case-sensitive as it stands; or preferably have a separateclassificationtable and have a foreign key constraint on the column in this table. But that’s probably out of your control for this assignment.