Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting a column to accept only 2 values

I have a column called "Patient Type" in a table. I want to make sure that only 2 values can be inserted in to the column , either opd or admitted, other than that, all other inputs are not valid.

Below is an example of what I want

enter image description here

How do I make sure that the column only accepts "opd" or "admitted" as the data for "Patient Type" column.

like image 762
Troller Avatar asked Jan 18 '14 08:01

Troller


People also ask

How do I restrict a column value in SQL?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

Which query can be used for restricting values in design column?

The CHECK constraint restricts values that can be entered into a table. It can contain search conditions similar to a WHERE clause. It can reference columns in the same table.

How do I restrict column values in MySQL?

MySQL CONSTRAINT is used to define rules to allow or restrict what values can be stored in columns. The purpose of inducing constraints is to enforce the integrity of a database. MySQL CONSTRAINTS are used to limit the type of data that can be inserted into a table.

How will you limit a user to see only few columns in a table?

You can right click on the views folder and choose the option New View..., that will give you a designer. For the permissions, you need to go to the Users folder inside of the Security folder and right click on the user and go to Properties and choose the permissions in the Securables page.


3 Answers

I'm not a MySQL dev, but I think this might be what you're looking for. ENUM

like image 125
MarkD Avatar answered Oct 13 '22 13:10

MarkD


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.

like image 24
peter.petrov Avatar answered Oct 13 '22 11:10

peter.petrov


While creating the table use Enum as data type for patientType column. Create table [tablename](firstname varchar(size),[othercolumns],patientType ENUM('OPD','Admitted'))

like image 3
Ubi Avatar answered Oct 13 '22 12:10

Ubi