64

Is there a way to set a SQL constraint for a numeric field that min value should be 1234 and max value should be 4523?

5 Answers 5

69

SQL Server syntax for the check constraint:

create table numbers (
    number int not null
        check(number >= 1234 and number <= 4523),
    ...
)

create table numbers (
    number int not null,
    check(number >= 1234 and number <= 4523),
    ...
)

create table numbers (
    number int not null,
    constraint number_range_check
        check(number >= 1234 and number <= 4523),
    ...
)
Sign up to request clarification or add additional context in comments.

3 Comments

The link bellow really helped me: technet.microsoft.com/en-us/library/ms179491.aspx.
Why would you check for Not Null, when there is a constraint that indirectly takes care of it? Am I missing something?
To add a constraint to an existing column: ALTER TABLE Tbl ADD CONSTRAINT ChkTable_Field CHECK (Field BETWEEN 1234 AND 4523).
21
CREATE TABLE WhatEver
(
    ...
    NumericField INTEGER NOT NULL CHECK(NumericField BETWEEN 1234 AND 4523),
    ...
);

Note that 'BETWEEN AND' provides a range inclusive of the quoted limit values.

Comments

4

If you are using SQL Server, you want to use a CHECK constraint like this:

CREATE TABLE foo (
  someint INT NOT NULL CHECK (someint >= 1234 AND someint <= 4523)
)

Comments

2

FYI

When you need a constraint for a range of values:

ALTER TABLE package_subscription ADD CONSTRAINT check_discount_amount CHECK (discount_amount BETWEEN 0.0000 AND 1.0000);

1 Comment

Are those constraints inclusive or exclusive?
1

If you are using SQL Server by means of SQL Server Management Studio, the most convenient way to add a Check Constraint is to right click the Constraints folder in the tree view (Object Explorer) and then, from the popup menu, select New Constraint.

A Check Constraint windows pops up with a new empty constraint named CK_tableName*

You can edit such a proposed name, and insert the code of the check constraint in the Expression field.

Then the new constraint appears in the Constraint folder (after you select the folder and hit the refresh icon) in Object Explorer and you can edit it right clicking it and selecting Modify from the popup menu.

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.