HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Set column to only accept negative values

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columnacceptnegativevaluesonlyset

Problem

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

It's SQL Server 2014 Azure.

Solution

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.

Code Snippets

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

Context

StackExchange Database Administrators Q#167709, answer score: 15

Revisions (0)

No revisions yet.