Why doesn't SQL Optimizer use my constraint? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Single year column and multiple weeks columns into single year/week column with PIVOTValidate a column to accept only certain age limit from birthdate given using check constraintNull Values in a CASE statementSelect Into removes IDENTITY property from target tableSQL 2005 Unused proceduresInvestigating errors from strange queryStatistics update with automatic sampling messes up density vector and histogramWhy we need to optimize CONTAINED IN clause of FOR_SYSTEM TIME using check constraint?Understanding why a query is slowGenerate SQL Table DDL from a View

Why do early math courses focus on the cross sections of a cone and not on other 3D objects?

Do any jurisdictions seriously consider reclassifying social media websites as publishers?

Most bit efficient text communication method?

How to react to hostile behavior from a senior developer?

Sum letters are not two different

Converted a Scalar function to a TVF function for parallel execution-Still running in Serial mode

Performance gap between vector<bool> and array

Find 108 by using 3,4,6

How much damage would a cupful of neutron star matter do to the Earth?

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?

Time to Settle Down!

Why is it faster to reheat something than it is to cook it?

Selecting user stories during sprint planning

Is CEO the "profession" with the most psychopaths?

How to install press fit bottom bracket into new frame

What would you call this weird metallic apparatus that allows you to lift people?

Drawing without replacement: why is the order of draw irrelevant?

How can I reduce the gap between left and right of cdot with a macro?

Trademark violation for app?

What initially awakened the Balrog?

How were pictures turned from film to a big picture in a picture frame before digital scanning?

How to write this math term? with cases it isn't working

Is there hard evidence that the grant peer review system performs significantly better than random?

How do living politicians protect their readily obtainable signatures from misuse?



Why doesn't SQL Optimizer use my constraint?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Single year column and multiple weeks columns into single year/week column with PIVOTValidate a column to accept only certain age limit from birthdate given using check constraintNull Values in a CASE statementSelect Into removes IDENTITY property from target tableSQL 2005 Unused proceduresInvestigating errors from strange queryStatistics update with automatic sampling messes up density vector and histogramWhy we need to optimize CONTAINED IN clause of FOR_SYSTEM TIME using check constraint?Understanding why a query is slowGenerate SQL Table DDL from a View



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5















I want to create a table with a NOT NULL bool column.

I use TINYINT with CHECK constraint BETWEEN 0 and 1. The constraint is new and thus trusted



Now I would expect that SQL optimizer now knows that this column can only be 0 and 1 so when I write query col >= 2 I will see Constant Scan in actual execution plan (like when I would when check for NULL or SELECT TOP (0)



But this is not the case, it opts for the table Scan. Do I also need to have index on this column?



In my test below I use TINYINT with CHECK constraint. User Defined Type based on TINYINT with bound RULE and good old BIT.



GO
CREATE TYPE dbo.myBool
FROM [INT] NOT NULL
GO

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
go

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'
GO


DROP TABLE IF EXISTS dbo.RuleTest
CREATE TABLE dbo.RuleTest
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED
, oldSchoolBool TINYINT NOT NULL CHECK (oldSchoolBool BETWEEN 0 AND 1)
, customBool dbo.myBool NOT NULL
, myBit BIT NOT NULL
)

;WITH tally (n)
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS a(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS b(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS c(n)

)
INSERT INTO dbo.RuleTest
(oldSchoolBool, customBool, myBit)
SELECT
ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
FROM tally t

SET STATISTICS IO ON;

SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool IS NULL


SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2

go
SELECT * FROM dbo.RuleTest rt
WHERE rt.customBool >=2
go
SELECT * FROM dbo.RuleTest rt
WHERE rt.myBit >= 2

SET STATISTICS IO OFF;


I see one Constant Scan for the NULL check and 3 table scans for the rest.










share|improve this question






















  • If you want to use as a boolean type then why tinyint in sql server, you may use BIT datatype.

    – Learning_DBAdmin
    9 hours ago











  • This is theoretical, also there can be reasons for not using a bit, like calculations or aggregations.

    – Zikato
    9 hours ago

















5















I want to create a table with a NOT NULL bool column.

I use TINYINT with CHECK constraint BETWEEN 0 and 1. The constraint is new and thus trusted



Now I would expect that SQL optimizer now knows that this column can only be 0 and 1 so when I write query col >= 2 I will see Constant Scan in actual execution plan (like when I would when check for NULL or SELECT TOP (0)



But this is not the case, it opts for the table Scan. Do I also need to have index on this column?



In my test below I use TINYINT with CHECK constraint. User Defined Type based on TINYINT with bound RULE and good old BIT.



GO
CREATE TYPE dbo.myBool
FROM [INT] NOT NULL
GO

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
go

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'
GO


DROP TABLE IF EXISTS dbo.RuleTest
CREATE TABLE dbo.RuleTest
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED
, oldSchoolBool TINYINT NOT NULL CHECK (oldSchoolBool BETWEEN 0 AND 1)
, customBool dbo.myBool NOT NULL
, myBit BIT NOT NULL
)

;WITH tally (n)
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS a(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS b(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS c(n)

)
INSERT INTO dbo.RuleTest
(oldSchoolBool, customBool, myBit)
SELECT
ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
FROM tally t

SET STATISTICS IO ON;

SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool IS NULL


SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2

go
SELECT * FROM dbo.RuleTest rt
WHERE rt.customBool >=2
go
SELECT * FROM dbo.RuleTest rt
WHERE rt.myBit >= 2

SET STATISTICS IO OFF;


I see one Constant Scan for the NULL check and 3 table scans for the rest.










share|improve this question






















  • If you want to use as a boolean type then why tinyint in sql server, you may use BIT datatype.

    – Learning_DBAdmin
    9 hours ago











  • This is theoretical, also there can be reasons for not using a bit, like calculations or aggregations.

    – Zikato
    9 hours ago













5












5








5


1






I want to create a table with a NOT NULL bool column.

I use TINYINT with CHECK constraint BETWEEN 0 and 1. The constraint is new and thus trusted



Now I would expect that SQL optimizer now knows that this column can only be 0 and 1 so when I write query col >= 2 I will see Constant Scan in actual execution plan (like when I would when check for NULL or SELECT TOP (0)



But this is not the case, it opts for the table Scan. Do I also need to have index on this column?



In my test below I use TINYINT with CHECK constraint. User Defined Type based on TINYINT with bound RULE and good old BIT.



GO
CREATE TYPE dbo.myBool
FROM [INT] NOT NULL
GO

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
go

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'
GO


DROP TABLE IF EXISTS dbo.RuleTest
CREATE TABLE dbo.RuleTest
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED
, oldSchoolBool TINYINT NOT NULL CHECK (oldSchoolBool BETWEEN 0 AND 1)
, customBool dbo.myBool NOT NULL
, myBit BIT NOT NULL
)

;WITH tally (n)
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS a(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS b(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS c(n)

)
INSERT INTO dbo.RuleTest
(oldSchoolBool, customBool, myBit)
SELECT
ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
FROM tally t

SET STATISTICS IO ON;

SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool IS NULL


SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2

go
SELECT * FROM dbo.RuleTest rt
WHERE rt.customBool >=2
go
SELECT * FROM dbo.RuleTest rt
WHERE rt.myBit >= 2

SET STATISTICS IO OFF;


I see one Constant Scan for the NULL check and 3 table scans for the rest.










share|improve this question














I want to create a table with a NOT NULL bool column.

I use TINYINT with CHECK constraint BETWEEN 0 and 1. The constraint is new and thus trusted



Now I would expect that SQL optimizer now knows that this column can only be 0 and 1 so when I write query col >= 2 I will see Constant Scan in actual execution plan (like when I would when check for NULL or SELECT TOP (0)



But this is not the case, it opts for the table Scan. Do I also need to have index on this column?



In my test below I use TINYINT with CHECK constraint. User Defined Type based on TINYINT with bound RULE and good old BIT.



GO
CREATE TYPE dbo.myBool
FROM [INT] NOT NULL
GO

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
go

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'
GO


DROP TABLE IF EXISTS dbo.RuleTest
CREATE TABLE dbo.RuleTest
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED
, oldSchoolBool TINYINT NOT NULL CHECK (oldSchoolBool BETWEEN 0 AND 1)
, customBool dbo.myBool NOT NULL
, myBit BIT NOT NULL
)

;WITH tally (n)
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS a(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS b(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) AS c(n)

)
INSERT INTO dbo.RuleTest
(oldSchoolBool, customBool, myBit)
SELECT
ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
,ABS(CHECKSUM(NewId())) % 2
FROM tally t

SET STATISTICS IO ON;

SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool IS NULL


SELECT * FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2

go
SELECT * FROM dbo.RuleTest rt
WHERE rt.customBool >=2
go
SELECT * FROM dbo.RuleTest rt
WHERE rt.myBit >= 2

SET STATISTICS IO OFF;


I see one Constant Scan for the NULL check and 3 table scans for the rest.







t-sql sql-server-2016






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 11 hours ago









ZikatoZikato

1947




1947












  • If you want to use as a boolean type then why tinyint in sql server, you may use BIT datatype.

    – Learning_DBAdmin
    9 hours ago











  • This is theoretical, also there can be reasons for not using a bit, like calculations or aggregations.

    – Zikato
    9 hours ago

















  • If you want to use as a boolean type then why tinyint in sql server, you may use BIT datatype.

    – Learning_DBAdmin
    9 hours ago











  • This is theoretical, also there can be reasons for not using a bit, like calculations or aggregations.

    – Zikato
    9 hours ago
















If you want to use as a boolean type then why tinyint in sql server, you may use BIT datatype.

– Learning_DBAdmin
9 hours ago





If you want to use as a boolean type then why tinyint in sql server, you may use BIT datatype.

– Learning_DBAdmin
9 hours ago













This is theoretical, also there can be reasons for not using a bit, like calculations or aggregations.

– Zikato
9 hours ago





This is theoretical, also there can be reasons for not using a bit, like calculations or aggregations.

– Zikato
9 hours ago










1 Answer
1






active

oldest

votes


















9














Query 2



The issue is Auto parameterization not trivial plan. Contradiction detection happens as part of simplification before the trivial plan stage (see the Optimization Pipeline diagram here).



In your case the constant 2 gets replaced with a tinyint parameter @1 rather than the literal 2 - as this parameter could have the value 0 or 1 it wouldn't be valid for the query optimiser to assume the check constraint contradicts this.



You can use the following query to get a trivial plan that does use the contradiction detection (the 1=1 prevents the Auto parameterization).



SELECT * 
FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2 and 1=1


enter image description here



Query 3



Rules have been discouraged/deprecated for about 20 years. 2000 BOL describes them as




a backward-compatibility feature ... CHECK constraints are the
preferred, standard way




The CREATE RULE topic states




Rules do not apply to data already existing in the database at the
time the rules are created




So I imagine these are never trusted by the query optimiser as it is possible to do the following and have data that does not adhere to the rule



CREATE TYPE dbo.myBool FROM [INT] NOT NULL

GO

CREATE TABLE dbo.RuleTest
(
customBool dbo.myBool NOT NULL
)

INSERT INTO dbo.RuleTest VALUES (10)

go

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
GO

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'


Whilst technically it might be possible to maintain a trusted rule concept analogous to trusted constraints I don't believe this exists.



Query 4



You need to add a redundant check constraint on CHECK (myBit BETWEEN 0 AND 1) or equivalent if you want it to do this contradiction detection. Even though a not nullable bit can only hold those two values you don't get this contradiction detected without that






share|improve this answer

























  • I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

    – Zikato
    6 hours ago











  • @MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

    – Zikato
    6 hours ago











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f235172%2fwhy-doesnt-sql-optimizer-use-my-constraint%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









9














Query 2



The issue is Auto parameterization not trivial plan. Contradiction detection happens as part of simplification before the trivial plan stage (see the Optimization Pipeline diagram here).



In your case the constant 2 gets replaced with a tinyint parameter @1 rather than the literal 2 - as this parameter could have the value 0 or 1 it wouldn't be valid for the query optimiser to assume the check constraint contradicts this.



You can use the following query to get a trivial plan that does use the contradiction detection (the 1=1 prevents the Auto parameterization).



SELECT * 
FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2 and 1=1


enter image description here



Query 3



Rules have been discouraged/deprecated for about 20 years. 2000 BOL describes them as




a backward-compatibility feature ... CHECK constraints are the
preferred, standard way




The CREATE RULE topic states




Rules do not apply to data already existing in the database at the
time the rules are created




So I imagine these are never trusted by the query optimiser as it is possible to do the following and have data that does not adhere to the rule



CREATE TYPE dbo.myBool FROM [INT] NOT NULL

GO

CREATE TABLE dbo.RuleTest
(
customBool dbo.myBool NOT NULL
)

INSERT INTO dbo.RuleTest VALUES (10)

go

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
GO

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'


Whilst technically it might be possible to maintain a trusted rule concept analogous to trusted constraints I don't believe this exists.



Query 4



You need to add a redundant check constraint on CHECK (myBit BETWEEN 0 AND 1) or equivalent if you want it to do this contradiction detection. Even though a not nullable bit can only hold those two values you don't get this contradiction detected without that






share|improve this answer

























  • I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

    – Zikato
    6 hours ago











  • @MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

    – Zikato
    6 hours ago















9














Query 2



The issue is Auto parameterization not trivial plan. Contradiction detection happens as part of simplification before the trivial plan stage (see the Optimization Pipeline diagram here).



In your case the constant 2 gets replaced with a tinyint parameter @1 rather than the literal 2 - as this parameter could have the value 0 or 1 it wouldn't be valid for the query optimiser to assume the check constraint contradicts this.



You can use the following query to get a trivial plan that does use the contradiction detection (the 1=1 prevents the Auto parameterization).



SELECT * 
FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2 and 1=1


enter image description here



Query 3



Rules have been discouraged/deprecated for about 20 years. 2000 BOL describes them as




a backward-compatibility feature ... CHECK constraints are the
preferred, standard way




The CREATE RULE topic states




Rules do not apply to data already existing in the database at the
time the rules are created




So I imagine these are never trusted by the query optimiser as it is possible to do the following and have data that does not adhere to the rule



CREATE TYPE dbo.myBool FROM [INT] NOT NULL

GO

CREATE TABLE dbo.RuleTest
(
customBool dbo.myBool NOT NULL
)

INSERT INTO dbo.RuleTest VALUES (10)

go

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
GO

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'


Whilst technically it might be possible to maintain a trusted rule concept analogous to trusted constraints I don't believe this exists.



Query 4



You need to add a redundant check constraint on CHECK (myBit BETWEEN 0 AND 1) or equivalent if you want it to do this contradiction detection. Even though a not nullable bit can only hold those two values you don't get this contradiction detected without that






share|improve this answer

























  • I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

    – Zikato
    6 hours ago











  • @MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

    – Zikato
    6 hours ago













9












9








9







Query 2



The issue is Auto parameterization not trivial plan. Contradiction detection happens as part of simplification before the trivial plan stage (see the Optimization Pipeline diagram here).



In your case the constant 2 gets replaced with a tinyint parameter @1 rather than the literal 2 - as this parameter could have the value 0 or 1 it wouldn't be valid for the query optimiser to assume the check constraint contradicts this.



You can use the following query to get a trivial plan that does use the contradiction detection (the 1=1 prevents the Auto parameterization).



SELECT * 
FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2 and 1=1


enter image description here



Query 3



Rules have been discouraged/deprecated for about 20 years. 2000 BOL describes them as




a backward-compatibility feature ... CHECK constraints are the
preferred, standard way




The CREATE RULE topic states




Rules do not apply to data already existing in the database at the
time the rules are created




So I imagine these are never trusted by the query optimiser as it is possible to do the following and have data that does not adhere to the rule



CREATE TYPE dbo.myBool FROM [INT] NOT NULL

GO

CREATE TABLE dbo.RuleTest
(
customBool dbo.myBool NOT NULL
)

INSERT INTO dbo.RuleTest VALUES (10)

go

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
GO

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'


Whilst technically it might be possible to maintain a trusted rule concept analogous to trusted constraints I don't believe this exists.



Query 4



You need to add a redundant check constraint on CHECK (myBit BETWEEN 0 AND 1) or equivalent if you want it to do this contradiction detection. Even though a not nullable bit can only hold those two values you don't get this contradiction detected without that






share|improve this answer















Query 2



The issue is Auto parameterization not trivial plan. Contradiction detection happens as part of simplification before the trivial plan stage (see the Optimization Pipeline diagram here).



In your case the constant 2 gets replaced with a tinyint parameter @1 rather than the literal 2 - as this parameter could have the value 0 or 1 it wouldn't be valid for the query optimiser to assume the check constraint contradicts this.



You can use the following query to get a trivial plan that does use the contradiction detection (the 1=1 prevents the Auto parameterization).



SELECT * 
FROM dbo.RuleTest rt
WHERE rt.oldSchoolBool >=2 and 1=1


enter image description here



Query 3



Rules have been discouraged/deprecated for about 20 years. 2000 BOL describes them as




a backward-compatibility feature ... CHECK constraints are the
preferred, standard way




The CREATE RULE topic states




Rules do not apply to data already existing in the database at the
time the rules are created




So I imagine these are never trusted by the query optimiser as it is possible to do the following and have data that does not adhere to the rule



CREATE TYPE dbo.myBool FROM [INT] NOT NULL

GO

CREATE TABLE dbo.RuleTest
(
customBool dbo.myBool NOT NULL
)

INSERT INTO dbo.RuleTest VALUES (10)

go

CREATE RULE dbo.R_Bool AS @value BETWEEN 0 AND 1
GO

EXEC sys.sp_bindrule @rulename = N'R_Bool'
, @objname = N'myBool'


Whilst technically it might be possible to maintain a trusted rule concept analogous to trusted constraints I don't believe this exists.



Query 4



You need to add a redundant check constraint on CHECK (myBit BETWEEN 0 AND 1) or equivalent if you want it to do this contradiction detection. Even though a not nullable bit can only hold those two values you don't get this contradiction detected without that







share|improve this answer














share|improve this answer



share|improve this answer








edited 4 hours ago

























answered 6 hours ago









Martin SmithMartin Smith

64.4k10173259




64.4k10173259












  • I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

    – Zikato
    6 hours ago











  • @MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

    – Zikato
    6 hours ago

















  • I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

    – Zikato
    6 hours ago











  • @MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

    – Zikato
    6 hours ago
















I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

– Zikato
6 hours ago





I've tested it and it returns constant scan for the oldSchoolBool, but not the other two (custom type and bit), any reason why? It goes for both your condition )1=1 and Brent's (1 = (SELECT 1))

– Zikato
6 hours ago













@MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

– Zikato
6 hours ago





@MarinSmith Rules are the stuff of the myths, but very much real on some production servers. And the Bit?

– Zikato
6 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Database Administrators Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f235172%2fwhy-doesnt-sql-optimizer-use-my-constraint%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр