In relation Person (SSN, State, Name), add a tuple-based check: if a
person’s State is NY, then the first three digits of his SSN has to be
between ‘050’ and ‘134’. (Hint: use LEFT function in SQL).
CREATE TABLE Person (
SSN INT PRIMARY KEY,
State CHAR(50),
Name CHAR(100),
CHECK (
SELECT LEFT (SSN, 3) AS FirstThreeDigits, SSN FROM Person,
WHERE Person.State == ‘NY’) between '050' and between '134'
);
I am not comfortable with the CHECK condition here. I am not sure if this is the right way doing conditional check. Can someone please verify this? If not, how do we do a conditional check?
We need this:
if state == 'NY', perform CHECK
Do we need a trigger? I was thinking that if a new insert / update occurs, check the value. But the question doesn’t ask that.
Ok so its generic but DDL typically isn’t but lets use the doc on SQL Server CHECK Constraints as a guide anyway
Note that the above example from the docs is not a SELECT statement but and expression. This means all you need to do is come up with a expression that returns TRUE
when all of the following are true
Or
Remembering that you can Group a set of logical expressions in a Parens
e.g.
It shouldn’t be too hard