SQL constraint to exclude certain values? - sql

Is there an sql constraint that enables you to disallow certain values in a column?
e.g.
ALTER TABLE foo
ADD COLUMN code TEXT NOT NULL UNIQUE DISALLOW '<GENERATE>'
;
s.t. <GENERATE> could be used safely in the application to indicate that the value should be generated before persisting without risking its accidentally being pushed to DB?

You need a check constraint:
ALTER TABLE foo
ADD COLUMN code TEXT NOT NULL UNIQUE;
alter table foo
add constraint disallow_generate
check (code <> '<GENERATE>');
If you want to disallowed multiple values, use a NOT IN condition:
alter table foo
add constraint disallow_generate
check (code not in ('<GENERATE>', '<GENERATED>', 'foo');

You could use Check Constraints.
eg:
ALTER TABLE foo
ADD COLUMN code TEXT NOT NULL UNIQUE CHECK (code <> '<GENERATE>');

Related

Modify SQL column field to be nullable, if I added constraint do I need to remove constraint as well?

I altered a table with the following script
ALTER TABLE TABLENAME ADD [flagField] CHAR(1) DEFAULT 'N' NOT NULL;
ALTER TABLE TABLENAME ADD CONSTRAINT XCK6_tablename CHECK([flagField] in ('Y', 'N'));
If I want to reverse this script to change that field in the table to allow a nullable state, do I need to remove the constraint before making the field nullable?
so if I run
ALTER TABLE TABLENAME ALTER COLUMN fieldFlag CHAR(1) NULL
will that be fine as is or should I also remove the constraint?
You only have to make the field NULLable.
The logic for constraints differs from the logic for WHERE and CASE WHEN conditions. For WHERE and CASE WHEN, NULL results are treated the same as false.
CHECK is instead validating the data. It accepts as valid anything that is not explicitly false. So, there is no need to include NULL checking in the constraint.
If you did, the correct logic would be:
CHECK (flagField in ('Y', 'N') or flagField is null)
Here is a db<>fiddle illustrating that the behavior is as described above.

How to create CHECK constraints in Informix?

I need to create validations in my fields (columns) in Informix tables. Inside SQL Server, the names are CHECK (for example: CHECK (Age>=18))
How to create in Informix, or, what's the similar syntax in Informix?
If you want add check constraint you could do it in two ways:
1) The next example adds a new unit_price column to the items table and includes a check constraint to ensure that the entered value is greater than 0:
ALTER TABLE items
ADD (unit_price MONEY (6,2) CHECK (unit_price > 0));
2) To create a constraint that checks values in more than one column, use the ADD CONSTRAINT clause. The following example builds a constraint on the column that was added in the previous example. The check constraint now spans two columns in the table.
ALTER TABLE items ADD CONSTRAINT CHECK (unit_price < total_price);
Have a look at the doc

PL/SQL constraint: Always one record in a table

Im trying to add a constraint to a table so that there can only be one record in the table.
This is the code I already have:
ALTER TABLE CONFIG
ADD CONSTRAINT always_one
CHECK (count(*)= 1);
And this is the error I'm getting
ALTER TABLE CONFIG
ADD CONSTRAINT always_one CHECK (count(*)= 1)
Error report -
SQL Error: ORA-00934: group function is not allowed here
00934. 00000 - "group function is not allowed here"
*Cause:
*Action:
How does this work?
You can use already proposed solution with adding unique constraint on column
alter table config add constraint always_one check (pk_col=1);
this however allows inserting more than one row in case pk_col is null in second inserted row. So you need to handle this by adding a NOT NULL constraint as well
ALTER TABLE config
ADD CONSTRAINT notnulc CHECK (pk_col IS NOT NULL) ;
To prevent deleting this row, you should probably create before delete trigger as follows
create or replace trigger trg_ONLYONE before delete ON CONFIG
DECLARE
C NUMBER;
BEGIN
SELECT COUNT(*) INTO C FROM CONFIG;
if (C=1) THEN
RAISE_APPLICATION_ERROR (-20011, 'TOO FEW ROWS');
END IF;
END;
Futher options are: instead of check constraints mentioned above is CREATE BEFORE INSERT trigger, or instead of NOT NULL and UNIQUE CONSTRAINT make pk_col PRIMARY KEY
Just create a unique index on a column in the table, and add a constraint that the value of this column must be a certain value.
eg.
CREATE UNIQUE INDEX one_val ON config(pk_col);
ALTER TABLE CONFIG
ADD CONSTRAINT always_one
CHECK (pk_col = 1);
If all of your other columns could be any value, you may need to just add this additional column, and give it a default value.

How to add unique column in sybase?

I have a sybase db table in which i need to add a new column.
The conditions: The column must not allow nulls and be unique.
what is the alter table sql to achieve this?
EDIT:
It is a varchar type column.Yes the table as of now is empty, but when filled it is ensured that unique values would be filled in.
I tired executing
alter table Test add Name varchar not null unique
i get error saying default value must be specified as not null is given.
but i want to add unique constraint so do i really need to specify default?
thanks
Unique values are specified as part of an index on the column, not in the column definition itself.
Try:
alter table Test add Name varchar not null
create unique index index_name_unique on Test (Name)
The ASE reference manual can help with more detail.
Once a table has been created Sybase ASE does not allow addition of NOT NULL column directly unless a default is specified for the column. However, if the table is still empty you can do the following -
First add the new column as a NULL column to the table using alter table command -
alter table Test add Name varchar(100) null
Once this has been done, try modifying the same column Name in the table Test using the alter table script -
alter table Test modify Name varchar(100) NOT NULL
and you will see that you are able to modify the Name column to a NOT NULL column using these steps. This is because at this time Sybase server checks as there is no data in the table hence the NOT NULL constraint is not checked and the column is made NOT NULL. Hence, we are able to skip the default constraint.
In case there would have been some data already present in the table Test, then we need to add one more step in between steps 1 and 2 which will add default values to the existing rows in the table. This can be done via a script for previous data and then following the step 2.
To make the column only allow unique values for the column you need to add a unique key constraint using the following syntax -
alter table Test add constraint UK1 unique(Name)

SQL: Create new column with default, unique value

I have added a new column, called Ordinal, to a table called Activity. The problem is that I gave it a UNIQUE constraint, set it to allow NULL (though this I won't want in the end.. I just needed to set it to that to get a little farther with the script), and did not give it a default value. I'm now running a RedGate SQL Compare script that was generated by comparing this table to a version of the Activity table that does not have the column. But I'm getting the following error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'iwt.Activity' and the index name 'IX_Activity'. The duplicate key value is (1).
So based on my research, it's trying to create a unique key constraint on the Ordinal column, but NULL is not unique. So my next step was to give it a unique value of 1 just to let the script pass. But 1 isn't going to be unique either. So, finally, my question:
Preferably in SQL Server Management Studio, how do I set a column as having a unique default value? Isn't that what I would need to create this constraint?
Thanks.
try this:
NULL will be the first constraint when you create the column.
UNIQUE will be as add constraint, you should add the second constraint.
they can run on this order with no problem (tested):
--first constraint
alter table Table_Name
add Column_Name int null
--second constraint
alter table Table_Name
add constraint Constraint_Name unique (Column_Name)
In my example :
PaymentGatewayHash is column
Cart is a table
--first query
alter table Cart
add PaymentGatewayHash NVARCHAR(20) null
--second query
CREATE UNIQUE INDEX PaymentGatewayHashUnique
ON Cart (PaymentGatewayHash)
WHERE PaymentGatewayHash IS NOT NULL
I just tested that :D