0

I was wondering how to put a constraint on a column when making the table. How would the create statement look if I want to say something like, make a table called name with column size, and size has to be greater than 10.

CREATE TABLE name(size int);

Where do i put the constraint?

3
  • I am using sql server Commented Mar 12, 2014 at 14:37
  • @poncha What's the syntax error in the CREATE TABLE statement? Commented Mar 12, 2014 at 14:42
  • 1
    by just doing "google" you should have find an answer or at least some direction if you are new to SQL. Commented Mar 12, 2014 at 14:46

3 Answers 3

3

You can include a constraint in your declaration right after you have specified the column name, like so:

CREATE TABLE name(size int CHECK (size > 10));

Sign up to request clarification or add additional context in comments.

2 Comments

OP asked for a string check, not an integer check.
"make a table called name with column size, and size has to be greater than 10." is what OP said. Not exactly clear if he means the column called 'size' or size of the string
1

To create a minimum size, you would use the check (link) constraint. Additionally, you would have to use the len() method to verify a string is long enough.

Example:

CREATE TABLE Persons
(
P_Id int NOT NULL,
Name varchar(255) CHECK (len(Name) >= 10),
Address varchar(255),
City varchar(255)
)

Comments

1

Just because I've encountered more headaches than is necessary with system-named constraints, here's how to do it and also name the constraint in the process:

create table Persons (
   size int,
   constraint [CK_Persons_Size] check ((size > 10))
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.