create table test
(
id varchar2(10) check( length(trim(id)) > 0),
primary key(id)
)
insert into test values (' '); -- this works
I expected this check constraint to stop this insert. But, it gets inserted none the less. Why ?
Problem is TRIM(' ')
returns NULL
and LENGTH(NULL)
also gives NULL
(not 0)
Try NVL(LENGTH(TRIM(' ')), 0) > 0
or
Try TRIM(ID) IS NOT NULL
Snippet stating that constraints can return null aka 'unknown' and considered to be NOT VIOLATING the constraint. Only a return of false violates a constraint. At least as per Oracle 12c
null > 0
evaluates to UNKNOWN. In query conditions, UNKNOWN is treated as "the same as" FALSE. Not so in constraints, however. In constraints, UNKNOWN is treated the same as TRUE. This is a very general rule, not special to the OP's constraint.
trim(' ')
, suggests that you may be familiar with strings (in C, for example), and with empty strings, and with "empty string" not being the same as null
(for example in the SQL Standard, and in some SQL dialects), but you are not aware that - idiotically - in Oracle the empty string is treated the same as null
. This will cause a lot of difficulties for you if you are coming from a different dialect; you will have to learn to live with it, and to be surprised many times before you get really used to it.
Explanation for what you saw:
If str
is made up entirely of spaces, then trim(str)
is the empty string.
Oracle treats the "empty string" the same as null
(of varchar2
data type, when that matters), in flagrant violation of the SQL standard. Oracle is not even consistent in this - there are (very few) exceptions where the empty string is, in fact, seen as "empty string" (for example, in concatenations).
By definition, the length of null
is null
(in particular, not zero).
In SQL, a condition like null > 0
evaluates to unknown
(in the three-valued logic needed to accommodate null
in such conditions).
In check constraints unknown
is treated the same as true
. This is different from the treatment in other conditions (in SQL statements - in where
clauses, join conditions etc.), where unknown
is treated the same as false
. This is documented, for example, here: https://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm - see the first paragraph in the Check Constraints section.
The correct solution to your problem:
Checking if something is null should be done DIRECTLY, with the is null
or is not null
conditions. Don't use length
for that.
Like this:
check( trim(id) is not null )
trim(id)
as the primary key? Are you going to usetrim(id)
everywhere in your queries and other statements? Will foreign keys point toid
or totrim(id)
? Etc. Seems like the spaces should be trimmed before saving in the table.