Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict a column value in SQLite / MySQL

Tags:

I would like to restrict a column value in a SQL table. For example, the column values can only be "car" or "bike" or "van". My question is how do you achieve this in SQL, and is it a good idea to do this on the DB side or should I let the application restrict the input.

I also have the intention to add or remove more values in the future, for example, "truck".

The type of Databases I am using are SQLite and MySQL.

like image 461
Maro Avatar asked Jun 16 '11 04:06

Maro


People also ask

How do I create a constraint in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

Is SQLite safer than MySQL?

Security and Ease of Setup – SQLite vs MySQL SQLite does not have an inbuilt authentication mechanism. The database files can be accessed by anyone. However, MySQL comes with a lot of inbuilt security features.

How do I add a check constraint in MySQL workbench?

Here I want to create 2 CHECK constraint before the record insert to the database. ALTER TABLE SubjectEnrollment ADD CONSTRAINT register CHECK (register <= classSize AND register >=0), ADD CONSTRAINT available CHECK (available <= classSize AND available >= 0);


1 Answers

Add a new table containing these means of transport, and make your column a foreign key to that table. New means of transport can be added to the table in future, and your column definition remains the same.

With this construction, I would definitively choose to regulate this at the DB level, rather than that of the application.

like image 88
NGLN Avatar answered Oct 28 '22 05:10

NGLN