Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit SQL Server column to a list of possible values

How do I put a constraint on a column so that it can only contain the following values? What do you call this type of constraint?

Allowed values: "yes", "no" or "maybe" Column Data Type: nvarchar(5) DBMS: SQL Server 2008 
like image 707
Dean Avatar asked Aug 16 '12 06:08

Dean


People also ask

How do I restrict column values in SQL Server?

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.

How do I limit a column in SQL?

EDIT: For SQL Server, replace LIMIT @num with TOP @num before the UNION ALL in each query and replace the DEFAULT with = . You can also have a second line to declare the @num as a string and use the PERCENT keyword, but only in SQL Server as neither MySQL nor Oracle supports it.

How do I limit results in SQL Server?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

How do I limit the number of entries in SQL?

The SQL LIMIT clause restricts how many rows are returned from a query. The syntax for the LIMIT clause is: SELECT * FROM table LIMIT X;. X represents how many records you want to retrieve. For example, you can use the LIMIT clause to retrieve the top five players on a leaderboard.


2 Answers

you can use a CHECK constraint

ALTER TABLE <table> ADD CONSTRAINT chk_val CHECK (col in ('yes','no','maybe')) 

MSDN link

like image 106
Joe G Joseph Avatar answered Sep 21 '22 18:09

Joe G Joseph


Yes, check a constraint is it what you need. You can declare check constraint at the table declaration:

CREATE TABLE test(     _id BIGINT PRIMARY KEY NOT NULL,     decision NVARCHAR(5),     CHECK (decision in ('yes','no','maybe')) ); 
like image 25
I159 Avatar answered Sep 20 '22 18:09

I159