Named CONSTRAINT benefits

南笙酒味 提交于 2019-12-05 06:10:48

There are significant benefits of giving explicit names to your constraints. Just a few examples:

  1. You can drop them by name.
  2. If you use conventions when choosing the name, then you can collect them from meta tables and process them programmatically.

It seems you are using PostgreSQL and there the difference isn't actually that big.

This is because a system generated name in PostgreSQL is actually somewhat meaningful. But "positive_price" is still easier to understand than "foo_price_check":

Think about which error message is better to understand:
new row for relation "foo" violates check constraint "foo_price_check"
or
new row for relation "foo" violates check constraint "positive_price"

In Oracle this is even worse because a system generated does not contain any hint on what was wrong:
ORA-02290: check constraint (SYS_C0024109) violated
vs.
ORA-02290: check constraint (POSITIVE_PRICE) violated

You don't specify RDBMS. the following points apply to SQL Server and I guess quite likely other RDBMSs too.

You need to know the name of the constraint to drop it, also the name of the constraint appears in constraint violation error messages so giving an explicit name can make these more meaningful (SQL Server will auto generate a name for the constraint that tells you nothing about the intent of the constraint).

Constraints as object in SQL, in the same manner that a PK, FK, Table or almost anything else is. If you give your constraint a name, you can easily drop it if required, say for example during some sort of bulk data import. If you don't give it a name, you can still drop it, however you have to find out the auto-genreated name that SQL will give it.

If your constraint is violated, having its name in the error message helps to debug it and present the error message to the user.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!