4

Is there anyway to change a column data type so that it will accept only negative values?

It's SQL Server 2014 Azure.

Paul White
  • 94,921
  • 30
  • 437
  • 687
Easy987us
  • 83
  • 1
  • 2
  • 5

2 Answers2

15
CREATE TABLE t ( n INTEGER NOT NULL CHECK (n < 0) );

works in most RDBMS I know.

Edit: A comment by @IMSop prompts me to specify why I wrote “most RDMS I know:” it is well known (and very unfortunate) that CHECK constraints aren’t honored by MySQL. In MySQL, you have to use triggers instead. Another option is to switch to MariaDB.

Dario
  • 748
  • 4
  • 13
4

This can be achieved (at least in Sql Server) by using a CHECK constraint.

From the above post:

CHECK constraints enforce domain integrity by limiting the values that are accepted by one or more columns. You can create a CHECK constraint with any logical (Boolean) expression that returns TRUE or FALSE based on the logical operators. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range. The logical expression would be the following: salary >= 15000 AND salary <= 100000.

Scott Hodgin - Retired
  • 24,062
  • 2
  • 29
  • 52