I have to make oracle constraints that checks if username is minimum 3 and maximum 10 lowercase letters.
I have used
constraint usernameSMALLCASE check (
REGEXP_Like(username,'^[a-z]{10}$') or
REGEXP_Like(username,'^[a-z]{9}$') or
REGEXP_Like(username,'^[a-z]{8}$') or
REGEXP_Like(username,'^[a-z]{7}$') or
REGEXP_Like(username,'^[a-z]{6}$') or
REGEXP_Like(username,'^[a-z]{5}$') or
REGEXP_Like(username,'^[a-z]{4}$') or
REGEXP_Like(username,'^[a-z]{3}$')
)
However, it is not working.
Somehow, putting $ is causing problem. But I have to put $ to make sure end of the end of line char is also small case.
Your code should work if your column is declared correctly. But you can drastically simplify it:
constraint usernameSMALLCASE check ( REGEXP_Like(username, '^[a-z]{3,10}$') )
Obviously there are other methods besides regular expressions for handling this. However, you have started down the regular expression route and it is simple enough using one.
If you insist on a fixed length column, you can express this as:
constraint usernameSMALLCASE check ( REGEXP_Like(username, '^[a-z]{3,10} *$') )
Create constraint for
username = lower(username) and length(username) > 3
The max length you can enforce by data type
username VARCHAR2(10 CHAR) NOT NULL
Note, regular expression ^[a-z]{3,10}$ is not fully reliable, see Character Class '[: :]' in Regular Expressions
A non-working example is this one:
ALTER SESSION SET NLS_SORT = XSPANISH;
BEGIN
IF REGEXP_LIKE('ch', '^[a-d]$') THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE('FALSE');
END _IF;
END;
Returns TRUE (despite h is not between a-d) because ch in traditional Spanish is considered as one sorting character.
I think a 100% reliable constraint would be like this:
REGEXP_LIKE(TRANSLATE(username, 'abcdefghijklmnopqrstuvwxyz', '**************************'), '^\*{3,10}$')
AND username NOT LIKE '%*%'
Related
I have another Question comming up, while solving some problems with postgreSQL. Is there any option, to check (in a check statement), if a varchar() contains an upper case character?
(I want that my table only holds Strings with at least one upper case letter.)
Thats how my table look:
CREATE TABLE test(
id integer PRIMARY KEY,
code varchar(255) not null,
CHECK ((char_length(code) >= 10) && check for upperCase?)
);
Does anyone have a tip how to solve this?
Regards,
Lukas
Make sure there are at least one non-lower case character:
CHECK ((char_length(code) >= 10) and code <> lower(code))
One method is a regular expression:
CHECK ((char_length(code) >= 10) and code ~ '[A-Z]')
I am having a problem with a check constraint in Oracle SQL Developer with Oracle 11g Express Edition.
I want to check if my postal code which is stored as CHAR just contains numbers and no other signs.
Tried various possibilities but nothing worked...
PLZ VARCHAR(5) NOT NULL
ADD CONSTRAINT TC_PLZ CHECK (PLZ LIKE '[0-9][0-9][0-9][0-9][0-9]')
Thanks and best regards,
Michael
Use regexp_like():
ADD CONSTRAINT TC_PLZ CHECK ( regexp_like(PLZ, '^[0-9]{5}$') )
Oracle -- like most databases -- only supports the ANSI standard wildcards in LIKE. These are % for zero or more characters and _ for exactly one character.
Regular expressions are much more powerful (although generally slower).
This might be a bit more efficient:
ADD CONSTRAINT TC_PLZ CHECK (translate(PLZ, '0123456789', '000000000') = '00000')
although I would go with the regular expression for clarity.
If you want to use regular expression patterns you need to use a regex function in the CHECK constraint. This will work:
create table t23 (
PLZ VARCHAR(5) NOT NULL
, CONSTRAINT TC_PLZ CHECK (regexp_LIKE(plz, '^[0-9]{5}$'))
);
Although there's no need for regex; here's an alternative implementation:
create table t42 (
PLZ NUMBER(5,0) NOT NULL
, CONSTRAINT T42_PLZ CHECK (length(plz)=5)
);
It's good practice to store numeric values using the correct datatype.
Check out this LiveSQL demo.
As #MT0 points out, the numeric implementation is not correct if a valid value can start with a leading zero. My purist data modeller persona states that values which must be a fixed number of digits should start at 10000 (for five digit values). However, I must admit I know of one system that did permit leading zeroes in a "numeric" field; they compounded this by allowing variable level values, which meant code 0300 identified something different from 00300. What larks!
In my table I have a column that is a code of 6 digits.
myCode CHAR(6) PRIMARY KEY CHECK ( SUBSTRING ( myCode ,1 ,1) >='0' AND
SUBSTRING ( myCode ,1 ,1) <= '9' AND ...#for all positions
Is there another method faster then this one ?
Using regex:
CREATE TABLE tabq(myCode CHAR(6) PRIMARY KEY CHECK (myCode ~'^([0-9]{6})$') );
If you just want to identify records which do not match this pattern, you could try:
SELECT *
FROM tabq
WHERE myCode !~ '^\\d{6}$';
Rextester Demo
Simpler:
mycode ~ '\d{6}'
\d is the class shorthand for digits.
Do not escape \ with another \ unless you are running with the long outdated standard_conforming_strings = off. See:
Insert text with single quotes in PostgreSQL
No parentheses needed.
And you don't even need ^ and $ to anchor the expression to begin and end (even if that doesn't hurt) while using char(6). A rare use case where the data type is not complete nonsense. See:
Best way to check for "empty or null value"
Any downsides of using data type "text" for storing strings?
Shorter strings are blank-padded and don't pass the CHECK constraint.
Longer string don't pass the length specification of the type char(6).
(But careful! An explicit cast like '1234567'::char(6) silently truncates.)
CREATE TABLE tbl (mycode char(6) PRIMARY KEY CHECK (mycode ~ '\d{6}'));
I would still advise not to use the outdated type char(6). Odd behavior in corner cases. Use text instead. Then you actually need ^ and $ in the regexp expression:
CREATE TABLE tbl (mycode text PRIMARY KEY CHECK (mycode ~ '^\d{6}$'));
dbfiddle here
You commented (really a new question):
and what about that digits inside has to be distinct?
Enforcing unique digits in the string is not as simple. If you have the additional module intarray installed, there is an elegant solution with sort() and uniq():
CREATE TEMP TABLE tbl3 (
mycode varchar(6) PRIMARY KEY
, CONSTRAINT chk_6_distinct_digits
CHECK (cardinality(uniq(sort(string_to_array(mycode, NULL)::int[]))) = 6)
);
I'm creating a database, and I would like to limit one of the table's fields to contain no more than 50 words but I'm not sure what is the way to create this constraint....?
You can add a CHECK constraint to your column. The question is, how do you define 'a word'?
In a rather simplistic approach we could assume that words are 'split' by spaces. In MSSQL you'd then have to add a check like this:
ALTER TABLE [myTable] ADD CONSTRAINT [chk_max_words] CHECK (Len(Replace([myField], N' ', N'')) > (Len([myField]) - 3))
When you try to insert or update a record and put the [myField] to 'test' it would pass, but if you set it to 'test test test test' it will fail because the number of spaces is 3 and our check will not let that pass.
Off course this approach is far from perfect. It does not consider double spaces, trailing spaces, etc...
From a practical point of view you probably want to write a function that counts the number of words according to your (elaborate) rules and then use that in the check.
ALTER TABLE [myTable] ADD CONSTRAINT [chk_max_words] CHECK (dbo.fn_number_of_words([myField] <= 3)
I have a column, say PROD_NUM that contains a 'number' that is left padded with zeros. For example 001004569. They are all nine characters long.
I do not use a numeric type because the normal operation on numbers do not make sense on these "numbers" (For example PROD_NUM * 2 does not make any sense.) And since they are all the same length, the column is defined as a CHAR(9)
CREATE TABLE PRODUCT (
PROD_NUM CHAR(9) NOT NULL
-- ETC.
)
I would like to constrain PROD_NUM so it can only contain nine digits. No spaces, no other characters besides '0' through '9'
REGEXP_LIKE(PROD_NUM, '^[[:digit:]]{9}$')
You already received some nice answers on how to continue on your current path. Please allow me to suggest a different path: use a number(9,0) datatype instead.
Reasons:
You don't need an additional check constraint to confirm it contains a real number.
You are not fooling the optimizer. For example, how many prod_num's are "BETWEEN '000000009' and '000000010'"? Lots of character strings fit in there. Whereas "prod_num between 9 and 10" obviously selects only two numbers. Cardinalities will be better, leading to better execution plans.
You are not fooling future colleagues who have to maintain your code. Naming it "prod_num" will have them automatically assume it contains a number.
Your application can use lpad(to_char(prod_num),9,'0'), preferably exposed in a view.
Regards,
Rob.
(update by MH) The comment thread has a discussion which nicely illustrates the various things to consider about this approach. If this topic is interesting you should read them.
Works in all versions:
TRANSLATE(PROD_NUM,'123456789','000000000') = '000000000'
I think Codebender's regexp will work fine but I suspect it is a bit slow.
You can do (untested)
replace(translate(prod_num,'0123456789','NNNNNNNNNN'),'N',null) is null
Cast it to integer, cast it back to varchar, and check that it equals the original string?
In MSSQL, I might use something like this as the constraint test:
PROD_NUM NOT LIKE '%[^0-9]%'
I'm not an Oracle person, but I don't think they support bracketed character lists.
in MS SQL server I use this command:
alter table add constraint [cc_mytable_myfield] check (cast(myfield as bigint) > 0)
Not sure about performance but if you know the range, the following will work.
Uses a CHECK constraint at the time of creating the DDL.
alter table test add jz2 varchar2(4)
check ( jz2 between 1 and 2000000 );
as will
alter table test add jz2 varchar2(4)
check ( jz2 in (1,2,3) );
this will also work
alter table test add jz2 varchar2(4)
check ( jz2 > 0 );