Default constraint not being enforced - tsql

Given the following table definition:
CREATE TABLE ControlledSubstances.NationalDrugCode
(
NationalDrugCodeID INT NOT NULL
,NationalDrugCode VARCHAR(20) NOT NULL
,Product VARCHAR(100)
,Ingredient VARCHAR(500)
,ClassID VARCHAR(50)
,Class VARCHAR(50)
,DrugEnforcementAgencyClassID VARCHAR(50)
,DrugEnforcementAgencyClass VARCHAR(50)
,GenericDrug VARCHAR(50)
,Form VARCHAR(50)
,Drug VARCHAR(50)
,StrengthPerUnit NUMERIC(6,2)
,UnitOfMeasure VARCHAR(50)
,ConversionFactor NUMERIC(4,2)
,LongOrShortActing VARCHAR(50)
,IsPreventionForStates BIT NOT NULL
)
;
ALTER TABLE ControlledSubstances.NationalDrugCode
ADD CONSTRAINT PK_ControlledSubstances_NationalDrugCode PRIMARY KEY (NationalDrugCodeID)
,CONSTRAINT DF_ControlledSubstances_NationalDrugCode_IsPreventionForStates DEFAULT 0 FOR IsPreventionForStates
;
CREATE UNIQUE INDEX UQ_ControlledSubstances_NationalDrugCode_NationalDrugCode ON ControlledSubstances.NationalDrugCode (NationalDrugCode);
Why would I be receiving an error on insert for the column I defined as NOT NULL and created a default constraint of 0? I know I can handle the logic in the insert statement to not pass in NULL values, but I use this logic in multiple tables and have never gotten an error before. The error I receive is:
Cannot insert the value NULL into column 'IsPreventionForStates', table 'Staging.ControlledSubstances.NationalDrugCode'; column does not allow nulls. INSERT fails.

This will happen if you explicitly provide NULL as its value. The default constraint only kicks in when you don't supply a value at all, or when you use the DEFAULT keyword:
For example, if NationalDrugCodeID and IsPreventionForStates were your only two columns in the table (for illustration), this will fail:
INSERT INTO NationalDrugCode(NationalDrugCodeID, IsPreventionForStates) VALUES (5, NULL);
But either of these would work:
INSERT INTO NationalDrugCode(NationalDrugCodeID) VALUES (5);
INSERT INTO NationalDrugCode(NationalDrugCodeID, IsPreventionForStates) VALUES (5, DEFAULT);
In the edge case where you need ALL columns to have default values inserted, you can use:
INSERT INTO NationalDrugCode DEFAULT VALUES;

Related

Postgres violates not null constraint, even when there isn't one

Hey I have a Postgres database that has a Schema with
CREATE TABLE Mentor (
mentor_ID serial unique,
person_ID serial not null unique,
career_history varchar(255) not null,
preferred_communication varchar(50) not null,
mentoring_preference varchar(50) not null,
linked_in varchar(100) not null,
capacity int not null,
feedback_rating int,
feeback_comment varchar(255),
PRIMARY KEY (mentor_ID),
CONSTRAINT fk_person FOREIGN KEY (person_ID) REFERENCES Person(person_ID)
);
CREATE TABLE Mentee(
mentee_ID integer not null unique,
mentor_ID serial references Mentor(mentor_ID),
person_ID serial not null unique,
study_year int,
motivation varchar(50),
interests varchar(255),
random_match boolean default false,
PRIMARY KEY (mentee_ID),
CONSTRAINT fk_person FOREIGN KEY (person_ID) REFERENCES Person(person_ID)
);
With this, i expect to be able to enter null values for mentor_ID in my database but when I enter the query
insert into mentee(mentee_ID, mentor_ID, person_ID) VALUES (12313, null, 1)
I get the violation
ERROR: null value in column "mentor_id" of relation "mentee" violates not-null constraint
I was wondering how I could make it so I can insert null values for mentor_ID? I dont have it as not null in the table but it still says violating not null constraint.
Thank you
Because serial is not null.
serial is...
CREATE SEQUENCE tablename_colname_seq AS integer;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
Note the integer not null. This is because serial is to be used for primary keys, not foreign keys. Foreign keys are always assigned, they don't need to auto increment.
Use a plain integer.
mentor_ID integer references Mentor(mentor_ID)
Same for your other foreign keys.
Notes:
identity is the SQL standard way to do auto incremented primary keys.
You don't need to declare primary keys as unique, primary keys are already unique.
Unless there's a specific reason to constrain the size of a text field, use text. varchar and text only use the necessary amount of space for each row. "foo" will take the same amount of space in varchar(10) as in varchar(255). For example, there's no particular reason to limit the size of their linked in nor motivation.

MySQL Error 1136:Column count does not match value count at row 1?

CREATE TABLE IF NOT EXISTS actores(
id_actor INT NOT NULL,
nombre VARCHAR(45) NOT NULL,
nacionalidad VARCHAR(45),
nombre_personaje VARCHAR(45),
PRIMARY KEY(id_actor)
)ENGINE=InnoDB;
INSERT INTO actores (nombre, nacionalidad)
VALUES ('Will smith' 'Americano');
You are missing a comma separating the values you want to insert.
VALUES ('Will smith', 'Americano');
You should change the definition for the field id_actor too to use auto-increment. Otherwise, you will need to specify an id for every insertion.
ALTER TABLE `actores`
CHANGE COLUMN `id_actor` `id_actor` INT(11) NOT NULL AUTO_INCREMENT ;

What is the code for a T-SQL check constraint?

I want to add a check clause to this table so that:
IF a transaction enters a value for the diastolicBloodPressure
THEN the transaction must also insert a value for the systolicBloodPressure.
CREATE TABLE "Constraint-BloodPressure".Patient
(
patientNr int NOT NULL,
diastolicBloodPressure smallint,
systolicBloodPressure smallint,
CONSTRAINT Patient_PK PRIMARY KEY(patientNr)
)
Is this correct?
CONSTRAINT CHK_BloodPressure CHECK (diastolicBloodPressure >0 AND systolicBloodPressure >0 )
You did not specify, whether your table would accept NULL-values and how you would deal with them.
Due to the kind of data, my suggestion was this:
CREATE TABLE dbo.TestCheck
(
patientNr INT NOT NULL CONSTRAINT PK_TestCheck PRIMARY KEY
,diastolicBloodPressure smallint NOT NULL
,systolicBloodPressure smallint NOT NULL
,CONSTRAINT chk_TestCheck_MustEnterBoth CHECK(diastolicBloodPressure BETWEEN 0 AND 250 AND systolicBloodPressure BETWEEN 0 AND 250)
);
--The table will not accept NULL-values and it will force the entered values to keep within realistic borders.
--Instead of smallint you might use tinyint, which is bordered between 0 and 255 by definition.
--Try the following:
INSERT INTO dbo.TestCheck VALUES(1,100,110);
GO
INSERT INTO dbo.TestCheck VALUES(2,100,NULL);
GO
INSERT INTO dbo.TestCheck VALUES(3,NULL,NULL);
GO
INSERT INTO dbo.TestCheck VALUES(4,-1,1000);
GO
SELECT * FROM dbo.TestCheck;
--Only the first insert will succeed, all the other attempts fill fail
--Clean-Up Carefull with real data...
GO
DROP TABLE dbo.TestCheck;
Not sure what database system you are using. On SQL Server 2014 I am require specify "NULL" or "NOT NULL". So my create table statement with the check constraint and insert statements looks like this...
IF OBJECT_ID('tempdb.dbo.#Patient', 'U') IS NOT NULL
DROP TABLE #Patient;
CREATE TABLE #Patient
(
patientNr INT NOT NULL
, diastolicBloodPressure SMALLINT NULL
, systolicBloodPressure SMALLINT NULL
, CONSTRAINT Patient_PK
PRIMARY KEY (patientNr)
, CHECK ((
diastolicBloodPressure IS NOT NULL
AND systolicBloodPressure IS NOT NULL
)
OR (
diastolicBloodPressure IS NULL
AND systolicBloodPressure IS NULL
)
)
);
INSERT INTO #Patient VALUES (1, NULL, NULL);
INSERT INTO #Patient VALUES (2, 120, NULL);
INSERT INTO #Patient VALUES (3, NULL, 80);
INSERT INTO #Patient VALUES (4, 120, 80);
The first and last insert statements work and the middle two fail.
If you want to force both fields to have a value, then you need to check for null values. If you don't, then your current check will allow entry of just the patientNbr or just one value.
CREATE TABLE dbo.Patient
(
patientNr int NOT NULL,
diastolicBloodPressure smallint,
systolicBloodPressure smallint,
CONSTRAINT Patient_PK PRIMARY KEY(patientNr),
CONSTRAINT CHK_BloodPressure CHECK (ISNULL(diastolicBloodPressure, 0) > 0 AND ISNULL(systolicBloodPressure, 0) > 0 )
);
GO
-- Valid
INSERT INTO dbo.Patient VALUES (1, 120, 80);
GO
-- Invalid
INSERT INTO dbo.Patient VALUES (2, 120, 0);
GO
-- Invalid
INSERT INTO dbo.Patient VALUES (3, 0, 80);
GO
-- Invalid
INSERT INTO dbo.Patient (patientNr, diastolicBloodPressure) VALUES (4, 120);
GO
-- Invalid
INSERT INTO dbo.Patient (patientNr) VALUES (5);
GO

Access database, Sql query , Error "Syntax error in DROP TABLE or DROP INDEX."

This is the query , running this in C#.
n getting above error
"DROP TABLE IF EXISTS `NATIONAL_ID_ISSUANCE_CENTER`;
CREATE TABLE `NATIONAL_ID_ISSUANCE_CENTER` (
`ID` INTEGER NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(100),
`APPLICATION_ID` INTEGER,
`STATUS` INTEGER,
`CREATED_BY` INTEGER,
`UPDATED_BY` INTEGER,
`CREATED_DATE` DATETIME,
`UPDATED_DATE` DATETIME,
`THIRD_PARTY_ID` INTEGER,
`PROVINCE_ID` INTEGER,
INDEX (`APPLICATION_ID`),
PRIMARY KEY (`ID`),
INDEX (`PROVINCE_ID`),
INDEX (`THIRD_PARTY_ID`)
)"
You can't put an IF statement inside Drop and Create statements. Anytime you want to drop a table that you're not sure exists, use the following:
IF(OBJECT_ID('[Database].[Schema].[TableName]') is not null)
BEGIN
DROP TABLE [Database].[Schema].[TableName];
END;
Please note you should replace [Database], [Schema], and [TableName] with the appropriate database, schema, and table names, respectively.

Postgres before insert trigger using sequence from another table

Using Postgres, what I would like to achieve is to be able to have many different instrument types, with corresponding [TYPE].instrument tables, which all have a unique ID in the table, but also reference a unique ID in the instrument.master table. I have the following:
create schema instrument
CREATE TABLE instrument.type (
id smallserial NOT NULL,
name text not null,
code text not null,
CONSTRAINT pk_instrument_type PRIMARY KEY (id)
);
ALTER TABLE instrument.type ADD CONSTRAINT unq_instrument_type_code UNIQUE(code);
ALTER TABLE instrument.type ADD CONSTRAINT unq_instrument_type_name UNIQUE(name);
insert into instrument.type (name, code) values ('futures', 'f');
CREATE TABLE instrument.master (
id serial NOT NULL,
type smallint not null references instrument.type (id),
timestamp timestamp with time zone not null,
CONSTRAINT pk_instrument_master PRIMARY KEY (id)
);
CREATE TABLE futures.definition (
id smallserial NOT NULL,
code text not null,
CONSTRAINT pk_futures_definition PRIMARY KEY (id)
);
ALTER TABLE futures.definition ADD CONSTRAINT unq_futures_definition_code UNIQUE(code);
insert into futures.definition (code) values ('ED');
CREATE TABLE futures.instrument (
id smallserial NOT NULL,
master serial not null references instrument.master (id),
definition smallint not null references futures.definition (id),
month smallint not null,
year smallint not null,
CONSTRAINT pk_futures_instrument PRIMARY KEY (id),
check (month >= 1),
check (month <= 12),
check (year >= 1900)
);
ALTER TABLE futures.instrument ADD CONSTRAINT unq_futures_instrument UNIQUE(definition, month, year);
CREATE OR REPLACE FUNCTION trigger_master_futures()
RETURNS trigger AS
$BODY$
BEGIN
insert into instrument.master (type, timestamp)
select id, current_timestamp from instrument.type where code = 'f';
NEW.master := currval('instrument.master_id_seq');
RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
create trigger trg_futures_instrument before insert on futures.instrument
for each row
execute procedure trigger_master_futures();
I then test with:
insert into futures.instrument (definition, month, year)
select id, 3, 2015 from futures.definition where code = 'ED';
Everything works almost as I would like it to. The only issue is that somehow, instrument.master.id ends up being one more than futures.instrument.master. I am not sure what I need to do to achieve the behavior I want, which is that whenever an entry is inserted into futures.instrument, an entry should be inserted into instrument.master, and the id entry of the latter should be inserted into the master entry of the former. I actually think it should have failed since the foreign key relationship is violated somehow.
As it turns out, everything was correct. The issue was that in futures.instrument, the type of the master column is serial, and it should have been int.