Question

We have a Visual Studio solution for our SQL Server 2019 database, and it is stored in a git repo. One table has a couple of check constraints using the BETWEEN operator, like this.

CONSTRAINT chk_FileTbl_MonthlyDate CHECK (MonthlyDate BETWEEN 1 AND 31)

When I used Redgate SQL Compare 14 to compare the repo to the database, it displayed the constraint reformatted with less than and greater than operators, like this.

CONSTRAINT chk_FileTbl_MonthlyDate CHECK (MonthlyDate >= 1 AND MonthlyDate <= 31)

I thought it was a bug/feature in Redgate's software and submitted a ticket for which I am awaiting a response. However, my colleague then used the comparison tool in Visual Studio 2019 and it did the same thing. If we look at the file defining the table, it uses BETWEEN, but both comparison tools show and deploy a change script with the less than/greater than format.

What is causing this behavior? We somewhat recently moved to SQL Server 2019, is it some kind of built-in optimization?

Was it helpful?

Solution

If you write a query and generate an execution plan, you will see that it, too, translates BETWEEN to a pair of >= and <= predicates. These mean the same thing. Redgate is just showing you what SQL Server stored when you created the constraint, not what you typed. And it has nothing to do with SQL Server 2019.

That said, I prefer the two-predicate pattern, and talk about why BETWEEN is bad for date ranges here and here. My opinion is to avoid exceptions, especially when it is just convenient shorthand / syntactic sugar, and especially when it contradicts how SQL Server stores it internally. In other words, if you don't like that scripting yields a different result than your code, change your code and embrace >= AND <=.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top