117k views
5 votes
Consider an insurance database schema given below.

Person(driver_id, Name, address)
Car(licenseNo, model, year)
Accident(report_no, date, location)
Owns (driver_id, licenseNo)
Participated (driver_id,licenseNo,report_no,damage_amount)
Written a SQL assertion that would prevent any person from owning more than 10 cars.

User Aquajet
by
8.0k points

2 Answers

1 vote

Final answer:

To prevent a person from owning more than 10 cars in an SQL database, an assertion or a trigger must be used, considering that many RDBMS do not support SQL assertions, and triggers are a common workaround.

Step-by-step explanation:

To enforce a rule in an SQL database that prevents any person from owning more than 10 cars, you can use an assertion. However, it is important to note that many relational database management systems (RDBMS) do not support SQL assertions. Instead, this kind of business logic is often implemented using triggers or application code.

If your RDBMS supports assertions, the SQL assertion could look something like this:

CREATE ASSERTION max_ten_cars_per_person CHECK ((SELECT MAX(car_count) FROM (SELECT driver_id, COUNT(*) AS car_count FROM Owns GROUP BY driver_id) AS car_counts) <= 10);

This assertion ensures that no single driver_id has an associated number of cars greater than 10 in the Owns table.

If SQL assertions are not available, a similar constraint can be achieved using a trigger. Here's an example of how a trigger can prevent the insertion of an eleventh car for a person:

CREATE TRIGGER check_car_limit BEFORE INSERT ON Owns FOR EACH ROW BEGIN SELECT CASE WHEN (SELECT COUNT(*) FROM Owns WHERE driver_id = NEW.driver_id) >= 10 THEN RAISE ABORT 'Person cannot own more than 10 cars' END; END;

This trigger checks the number of cars already owned by a person before allowing a new insertion into the Owns table. If the person already owns 10 cars, the trigger raises an error, preventing the additional car from being registered.

User Scott Jungwirth
by
8.9k points
3 votes

Final answer:

Here's an example of how you could create this SQL assertion to prevent any person from owning more than 10 cars, you can checks the number of cars owned by a person (`driver_id`) whenever a new ownership entry is attempted to be added:

```sql

CREATE ASSERTION max_car_ownership

CHECK (

SELECT COUNT(*)

FROM Owns

WHERE driver_id IN (

SELECT driver_id

FROM Owns

GROUP BY driver_id

HAVING COUNT(*) > 10

)

) <= 0;

```

Step-by-step explanation:

This assertion ensures that for any attempt to insert new ownership data (`Owns` table), the total count of cars owned by a person (`driver_id`) does not exceed 10. If the count exceeds 10, the assertion will prevent the insertion.

Please note that not all database management systems support assertions, so the implementation might vary depending on the specific DBMS you're using. Also, ensure that your DBMS supports the `CREATE ASSERTION` syntax.

User GoFaster
by
7.7k points