Can I make SQL sub queries in Check constraint ?
I've a post
table with columns id, owner
I've another table action
with columns user_id, post_id
Table user
with columns id
post_id -> post.id
and user_id -> user.id
also post.owner -> user.id
Now I want to constraint post(post_id).id != user_id
on table action
How is that possible ?
Sub-queries are not allowed in this context. Only scalar expressions are allowed.
The syntax for enabling a check constraint in SQL Server (Transact-SQL) is: ALTER TABLE table_name WITH CHECK CHECK CONSTRAINT constraint_name; table_name. The name of the table that you wish to enable the check constraint.
Check constraints are limited to Boolean operations (e.g., =, >=, <=, or <>), though they may include any SQL2003 predicate, such as IN or LIKE. Check constraints may be appended to one another (when checking a single column) using the AND and OR operators.
I think create table as ... is the only DDL that will allow "sub-queries".
It is not supported to look beyond the current row in a CHECK constraint.
http://www.postgresql.org/docs/9.1/interactive/sql-createtable.html says:
A check constraint specified as a column constraint should reference that column's value only, while an expression appearing in a table constraint can reference multiple columns.
Currently, CHECK expressions cannot contain subqueries nor refer to variables other than columns of the current row.
There are good reasons for this restriction, but if you like to juggle flaming torches while riding a unicycle through heavy traffic, you can subvert the restriction using functions. The situations in which this will not come back to bite you are rare; you would be much safer to enforce the invariant in trigger code instead.
http://www.postgresql.org/docs/9.1/interactive/triggers.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With