Restrict varchar() column to specific values?
Have you already looked at adding a check constraint
on that column which would restrict values? Something like:
CREATE TABLE SomeTable
(
Id int NOT NULL,
Frequency varchar(200),
CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)
Restrict a column of any type to specific values?
You can use this for any data type that supports IN
. So it works for strings, numbers, and date/time values.
Restricting a column to accept only 2 values
You need a check constraint.
ALTER TABLE [TableName] ADD CONSTRAINT
my_constraint CHECK (PatientType = 'Admitted' OR PatientType = 'OPD')
You need to check if it works though in MySQL in particular as of today.
Seems it does not work (or at least it did not a few years ago).
MySQL CHECK Constraint
CHECK constraint in MySQL is not working
MySQL CHECK Constraint Workaround
Not sure if it's fixed now.
If not working, use a trigger instead of a check constraint.
MySQL restricting the value of a MySQL field (allow one specific value and multiple others.)?
If you use null
instead of false
to indicate that a user is not an owner, then you can use a unique index to provide this restriction because in MySQL unique indexes allow multiple null values. Obviously, you need to make the is_owner
field nullable for this to work.
Otherwise, this control is better placed in the application layer, than in the database. In the database you can use a trigger to check this condition and prevent extra owner records to be set by raising an sql error.
In Postgres, how do you restrict possible values for a particular column?
You could add a CHECK CONSTRAINT:
ALTER TABLE distributors
ADD CONSTRAINT check_types
CHECK (element_type = 'lesson' OR element_type = 'quiz');
Although IMO the cleaner option would be to create an ENUM
:
CREATE TYPE element_type AS ENUM ('lesson', 'quiz');
Related Topics
Activerecord Find_Each Combined with Limit and Order
Sql: Two Select Statements in One Query
Script Entire Database SQL-Server
SQL Query to Show Gaps Between Multiple Date Ranges
SQL Query If Parameter Is Null Select All
Should I Use the Cascade Delete Rule
Is There Any Query for Cassandra as Same as SQL:Like Condition
How to Increment Integer Columns Value by 1 in SQL
SQL Row_Number() Function in Where Clause
What Does a (+) Sign Mean in an Oracle SQL Where Clause
How Do Null Values Affect Performance in a Database Search
Update Query Using Subquery in SQL Server