SQL is over-aggressive about removing parenthesis in check constraints and I find it confusing.
I have a table where I don't want certain columns to have a value if the Active flag is 0.
Example DDL below:
CREATE TABLE [dbo].[Table_1]( [ID] [int] NOT NULL, [Active] [bit] NOT NULL, [Value1] [int] NULL, [Value2] [int] NULL, CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
When I enter this expression for a check constraint:
([Active] = 1) OR ([Value1] IS NULL AND [Value2] IS NULL)
SQL removes the parenthesis around the AND. I guess it knows "AND" has higher precedence than "OR" but I find it confusing.
([Active]=(1) OR [Value1] IS NULL AND [Value2] IS NULL)
I think in this instance SQL has removed too many parenthesis and made the expression harder to read. I have re-written my OR statement using CASE WHEN statements to avoid it re-writing.
There is no question here, perhaps I should report the issue as a feature request / complaint.