Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL constraint minvalue / maxvalue?

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?

like image 814
Shimmy Weitzhandler Avatar asked Nov 15 '09 05:11

Shimmy Weitzhandler


People also ask

How do you set a minimum and maximum value in SQL?

To ask SQL Server about the minimum and maximum values in a column, we use the following syntax: SELECT MIN(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; When we use this syntax, SQL Server returns a single value. Thus, we can consider the MIN() and MAX() functions Scalar-Valued Functions.

How to add number constraint in SQL?

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.

How do you SELECT a minimum value in SQL?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.


2 Answers

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),     ... ) 
like image 88
yfeldblum Avatar answered Sep 19 '22 17:09

yfeldblum


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.

like image 40
Jonathan Leffler Avatar answered Sep 17 '22 17:09

Jonathan Leffler