integrity Constraints on a table.

Posted by Dinesh on Stack Overflow See other posts from Stack Overflow or by Dinesh
Published on 2010-05-07T09:12:37Z Indexed on 2010/05/07 9:18 UTC
Read the original article Hit count: 201

See this sample schema

Passenger(id PK, Name)

Plane(id  PK, capacity, type);

Flight(id PK, planeId FK(Plane), flightDate, StartLocation, destination)


CREATE TABLE Reservation(PassengerId, flightId,
        PRIMARY KEY (passengerId, flightId),
        FOREIGN KEY (passengerId) REFERENCES Passenger,
        FOREIGN KEY (flightId) REFERENCES Flight);

I need to define an integrity constraint that enforces the restriction that the number of passengers on a plane cannot exceed the plane’s capacity.

I have tried and achieved so far is this.

CREATE TABLE Reservation(
    passengerId INTEGER,  
    flightId    INTEGER,
        PRIMARY KEY (passengerId, flightId),
        FOREIGN KEY (passengerId) REFERENCES Passenger,
        FOREIGN KEY (flightId) REFERENCES Flight,
        Constraint check1 
            check(Not Exists(select * from Flight s, (select count(*) as totalRes from Reservation group by flightId) t
where t.totalRes  > s.capacity ) )            
 ); 

I am not sure i am doing in right way or not.

Any suggestions?

© Stack Overflow or respective owner

Related posts about sql

Related posts about check-constraints