Is a DEFAULT constraint an actual constraint? - sql

In SQL I see several types of constraints, like PRIMARY KEY. NOT NULL, FOREIGN KEY, etc. But I stumbled on DEFAULT constraints now and I'm confused.
What does it prevent to happen? Will any query fail to adhere by it?
If no query will ever fail because of a DEFAULT constraint, is it really a constraint?
Thank you.
A confused developer

if a column is Not NULL
Like
CREATE TABLE mytable (val int NOT NULL)
and you try
INSERT NTO mytable VALUES (NULL)
You will get an error, as te database can't replace the NULL with a DEFAULT value, because it doesn't exist.
so it constraints the INSERT INTO

Check if the following answer helps you understanding about DEFAULT constraint.
https://stackoverflow.com/a/1213316/7056491

If a column has a DEFAULT constraint and the INSERT or UPDATE statement doesn’t provide the value for that column, MySQL will use the default value specified in the DEFAULT constraint.
So for table:
CREATE TABLE Defaults (
Age int,
Gender varchar(255) DEFAULT 'Female'
);
You can Insert:
INSERT INTO Defaults (`Age`) VALUES ('4');
Age will be 4, and Gender will be 'Female'.
The DEFAULT constraint does not RESTRICT the addition of any value nor does it enforce a rule like the other constraints, but it does provide proper predefined values to keep domain integrity intact.

Related

Naming a default constraint

I'm trying to create a default constraint here, but the system is generating a weird name for it. If I want to name it df_MY_TABLE_GUID or something, how could I specify that name be used?
ALTER TABLE MY_TABLE
ADD MY_GUID uniqueidentifier NOT NULL
CONSTRAINT uq_MY_TABLE_GUID UNIQUE (MY_TABLE_GUID)
DEFAULT NEWID() WITH VALUES
Just specify the constraint name with the full syntax, like the UNIQUE in your example:
ALTER TABLE MY_TABLE ADD MY_GUID UNIQUEIDENTIFIER NOT NULL
CONSTRAINT uq_MY_TABLE_GUID UNIQUE (MY_TABLE_GUID)
CONSTRAINT df_MY_TABLE_GUID DEFAULT NEWID() WITH VALUES ;
As a matter of routine, I always prefer and encourage to always name every single constraint I create, for the sake of easy reference latter on.

Modify SQL column field to be nullable, if I added constraint do I need to remove constraint as well?

I altered a table with the following script
ALTER TABLE TABLENAME ADD [flagField] CHAR(1) DEFAULT 'N' NOT NULL;
ALTER TABLE TABLENAME ADD CONSTRAINT XCK6_tablename CHECK([flagField] in ('Y', 'N'));
If I want to reverse this script to change that field in the table to allow a nullable state, do I need to remove the constraint before making the field nullable?
so if I run
ALTER TABLE TABLENAME ALTER COLUMN fieldFlag CHAR(1) NULL
will that be fine as is or should I also remove the constraint?
You only have to make the field NULLable.
The logic for constraints differs from the logic for WHERE and CASE WHEN conditions. For WHERE and CASE WHEN, NULL results are treated the same as false.
CHECK is instead validating the data. It accepts as valid anything that is not explicitly false. So, there is no need to include NULL checking in the constraint.
If you did, the correct logic would be:
CHECK (flagField in ('Y', 'N') or flagField is null)
Here is a db<>fiddle illustrating that the behavior is as described above.

Why Is "NOT NULL" not a constraint?

If I want to add a PRIMARY KEY to an existing column table :
ALTER TABLE table_name
ADD CONSTRAINT column_name_PK PRIMARY KEY (column_name);
Now, If I want to add a NOT NULL to an existing column table :
ALTER TABLE table_name
ALTER column column_name INTEGER(or other data type) NOT NULL;
Isn't NOT NULL a constraint ?
Why for a PRIMARY KEY is ADD CONSTRAINT
and for a NOT NULL is not ADD CONSTRAINT but ALTER COLUMN ?
To my eyes, NOT NULL is also a kind of constraint..
Specifying NOT NULL means 'the column must have a value'. It only means that some value must be present, but it says nothing about what those values should be. Note that in SQL terms, NULL itself is not a value but it is the absence of a value.
A CONSTRAINT on the other hand is a rule for the allowed values. You can even have a constraint on NULL columns, and then such a CONSTRAINT for the allowed values is enforced only if a non-NULL value is present.
You can just use NOT NULL inline when you declare the parameter. Like this:
CREATE TABLE People
(
ID INT NOT NULL,
Name NVARCHAR(100) NOT NULL,
Notes NVARCHAR(MAX) NULL
)
Think of it as the NULL or NOT NULL actually being part of the type declaration. A field that can hold an Integer and also can hold a NULL is a different type than one that can hold an Integer but never a NULL.
Consider
create type IntegerIsSometimesNull from integer null
create type IntegerIsNeverNull from integer not null
go
create table DifferentType ( N IntegerIsSometimesNull,
I IntegerIsNeverNull )
Here we see that NULL and NOT NULL are actually a part of the type declaration.
Consider also that these fields require a different amount of space in the database.
To my eyes, NOT NULL is also a kind of constraint..
Yes. Data Types, NULL-ness, CHECK CONSTRAINTS, and FOREIGN KEY constraints are all concerned with defining the "domain" of the column. A "domain" is the set of possible values for a column, and is a fundamental concept of the relational model.
In most RDBMS systems domains are implemented by a combination of data types and constraints.

Why can primary key column be empty in SQLite?

I have a table with only 1 primary column (nvarchar), as in the designer, it's marked as primary key and not allow nulls. But by somehow, there is a row in that table with the key value being empty, it's of course not null and doesn't duplicate with any other rows in the primary key column and there isn't any conflict or violation occurring.
However as far as I know, that kind of value (empty) is not allowed for a primary column in SQL Server. I wonder if there is any option to turn on to make it work properly. Or I have to check the value myself through CHECK constraint or right in C# code (before updating).
Your help would be highly appreciated. Thanks!
"Empty-string" is a string with length of zero. It is NOT NULL, so it doesn't violate a null check. It most certainly IS an allowed value for a character-based primary key column in SQL Server. If the empty string value is not allowed by the business, a check constraint would be the best way to implement this as a business rule. That way, clients which might not know about the rule can't violate it.
This code runs without violations in SQL Server, I just tested it just to be sure.
create table TestTable (
myKey varchar(10) primary key,
myData int
)
GO
insert TestTable
select '', 1

SQL Server, can't insert null into primary key field?

I'm about ready to rip my hair out on this one. I'm fairly new to MS SQL, and haven't seen a similar post anywhere.
When I try to do a statement like this:
INSERT INTO qcRawMatTestCharacteristic
VALUES(NULL, 1,1,1,1,1,1,1,'','','', GETDATE(), 1)
I get the following:
Cannot insert the value NULL into
column 'iRawMatTestCharacteristicId',
table
'Intranet.dbo.qcRawMatTestCharacteristic';
column does not allow nulls. INSERT
fails.
I understand the error, but the null value is for my my primary field with an int data type.
Any ideas!?
Primary keys in any relational database are not allowed to be NULL - it's one of the main, fundamental characteristics of a primary key.
See: SQL by Design: how to Choose the primary key
Never Null
No primary key value can be null, nor can you do anything to
render the primary key null. This is
an inviolate rule of the relational
model as supported by ANSI, of
relational database management system
(RDBMS) design, and of SQL Server.
UPDATE: ok, so you want an "auto-increment" primary key in SQL Server.
You need to define it as an INT IDENTITY in your CREATE TABLE statement:
CREATE TABLE dbo.YourTable(ID INT IDENTITY, col1 INT, ..., colN INT)
and then when you do an INSERT, you need to explicitly specify the columns to insert, but just don't specify the "ID" column in that list - then SQL Server will handle finding the proper value automagically:
INSERT INTO dbo.YourTable(col1, col2, ..., colN) -- anything **except** `ID`
VALUES(va1l, val2, ..., valN)
If you want to do this after having created the table already, you can do so in the SQL Server Management Studio's table designer:
Primary Key fields cannot contain null values in MS SQL. If you want to populate a SQL table and dont know what to enter for a integer based primary key field then set the pk to an Identity field. Also when specifying Insert statements its wise to use the column mapping portion of the insert statment for example:
Insert into (field1, field2, field3)
values
(value1, value2, value3)
The reason for this is it insures that the column order is what you developed for as a SQL administrator can modify column order. It also allows you to insert a row with an identity Primary key with out specifying the value of the Primary Key Example
CREATE TABLE [dbo].[foo](
[fooid] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
CONSTRAINT [PK_foo] PRIMARY KEY
(
[fooid] ASC
)
now my insert statement is simple
Insert into foo (name)
values
("John")
the result in the table would be
1, "John"
You probably don't have (you forgot to add) autoincrement set on your integer primary key.
Primary keys shouldnt accept null value.Why you are inserting null values to a primary key field ?Primary key field should have a non-nullable,unique value which will make each of your record in the table unique
you can use 0 instead of null for only 1 unique row, null is not possible for PK. Or you can omit PK and use and auto increament PK field
Assuming you have an autoincrement field for your primary Key you'll need to include the field list on your insert and not put a value for that field e.g.
INSERT INTO qcRawMatTestCharacteristic
(Answer1,Answer2,...SomeDateField)
VALUES(1,1,1,1,1,1,1,'','','', GETDATE(), 1)
I'm assuming your real issue is that you're not sure how to write an insert statement so that the PK is auto populated correct? You need to name the fields you're setting values for, it looks like you're trying to set all of them but just exclude the PK field like so:
INSERT INTO someTable
(fieldName1, fieldName2)
VALUES(1,1)
Where sometable is a table with three fields. PK, fieldName1, and fieldName2. You also need to make sure that the identity property on the PK field is set to true.
if you have an identity column, you don't need to specify it in the insert statement.
INSERT INTO qcRawMatTestCharacteristic
VALUES(1,1,1,1,1,1,1,'','','', GETDATE(), 1)
However, if you have a primary key that isn't an identity column, then you do need to specify it, because otherwise it'll try to insert a null and primary keys by default are non-nullable.