How to create column with default and required values? - sql

I'm trying this code but I'm getting this error message: An expression of non-boolean type specified in a context where a condition is expected, near ','.
ALTER TABLE customers
ADD active int
DEFAULT (1)
CONSTRAINT chk_active
CHECK (0,1);
Thanks in advance!

When defining a check constraint you have to actually refer to the column name, i.e. CHECK (Active IN (0,1) instead of just CHECK (0, 1). So your syntax would be
ALTER TABLE Customers ADD
active INT DEFAULT (1)
CONSTRAINT chk_active CHECK (Active IN (0,1));
It is also probably a good idea to name your default constraint, and include the table name in the constraint name so that you don't conflict with similar constraints on other tables:
ALTER TABLE Customers ADD
Active INT CONSTRAINT DF_Customers__Active DEFAULT (1)
CONSTRAINT CHK_Customers__Active CHECK (Active IN (0,1));
However, it would seem more appropriate to have a not null bit column so the check constraint is not required:
ALTER TABLE Customers ADD Active BIT NOT NULL CONSTRAINT DF_Customers__Active DEFAULT(1);

ALTER TABLE customers
ADD active int
GO
ALTER TABLE customers
ADD CONSTRAINT [DF_active ] DEFAULT (1) FOR active
GO
ALTER TABLE customers
ADD CONSTRAINT [chk_active] CHECK (active>=0 AND active <=1)
I would suggest you do it like this. Also always conside adding a name to your constraint.
As a facut, why don't u use active as bit column so you won't need the CHECK constraint.

try this
ALTER TABLE Customers ADD
active INT DEFAULT (1)
CONSTRAINT chk_active CHECK (Active IN (0,1));

Related

Using a 'not in' query inside of a check constraint in SQL

I have two tables, one of student and one of staff that look as such:
create table student (
id int not null primary key
)
create table staff (
id int not null primary key
)
I want the id in each to be unique. I know this isn't how it should be in production but I'm just trying to see why my check constraint doesn't work and I'm using a simpler example to explain.
I then alter the tables to include the check as follows:
alter table student add constraint not_staff check (id not in (select id from staff))
alter table staff add constraint not_student check (id not in (select id from student))
These checks seem to be invalid.
My question is whether we're allowed to have these kinds of SQL statements inside of a check constraint. If so, why is the above constraint invalid and how would I go about fixing it.
Thanks!
You can't use queries in a check constraint in Db2. Refer to the description of the CREATE TABLE statement.
CHECK (check-condition)
Defines a check constraint. The search-condition must be true or unknown for every row of the table.
search-condition
The search-condition has the following restrictions:
...
The search-condition cannot contain any of the following (SQLSTATE 42621):
Subqueries
The easiest way to achieve your goal is not to create constraints, but create a sequence and use it in before triggers on both tables.

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.

PL/SQL constraint: Always one record in a table

Im trying to add a constraint to a table so that there can only be one record in the table.
This is the code I already have:
ALTER TABLE CONFIG
ADD CONSTRAINT always_one
CHECK (count(*)= 1);
And this is the error I'm getting
ALTER TABLE CONFIG
ADD CONSTRAINT always_one CHECK (count(*)= 1)
Error report -
SQL Error: ORA-00934: group function is not allowed here
00934. 00000 - "group function is not allowed here"
*Cause:
*Action:
How does this work?
You can use already proposed solution with adding unique constraint on column
alter table config add constraint always_one check (pk_col=1);
this however allows inserting more than one row in case pk_col is null in second inserted row. So you need to handle this by adding a NOT NULL constraint as well
ALTER TABLE config
ADD CONSTRAINT notnulc CHECK (pk_col IS NOT NULL) ;
To prevent deleting this row, you should probably create before delete trigger as follows
create or replace trigger trg_ONLYONE before delete ON CONFIG
DECLARE
C NUMBER;
BEGIN
SELECT COUNT(*) INTO C FROM CONFIG;
if (C=1) THEN
RAISE_APPLICATION_ERROR (-20011, 'TOO FEW ROWS');
END IF;
END;
Futher options are: instead of check constraints mentioned above is CREATE BEFORE INSERT trigger, or instead of NOT NULL and UNIQUE CONSTRAINT make pk_col PRIMARY KEY
Just create a unique index on a column in the table, and add a constraint that the value of this column must be a certain value.
eg.
CREATE UNIQUE INDEX one_val ON config(pk_col);
ALTER TABLE CONFIG
ADD CONSTRAINT always_one
CHECK (pk_col = 1);
If all of your other columns could be any value, you may need to just add this additional column, and give it a default value.

Adding column with primary key in existing table

I am trying to add primary key to newly added column in existing table name Product_Details.
New Column added: Product_Detail_ID (int and not null)
I am trying add primary key to Product_Detail_ID (please note: there are no other primary or foreign key assigned to this table)
I am trying with this query but getting error.
ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)
GO
Error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Product\_Details' and the index name 'pk\_Product\_Detils'. The duplicate key value is (0).
Am I missing something here? I am using SQL Server 2008 R2. I would appreciate any help.
If you want SQL Server to automatically provide values for the new column, make it an identity.
ALTER TABLE Product_Details DROP COLUMN Product_Detail_ID
GO
ALTER TABLE Product_Details ADD Product_Detail_ID int identity(1,1) not null
GO
ALTER TABLE Product_Details
add CONSTRAINT pk_Product_Detils_Product_Detail_ID primary key(Product_Detail_ID)
GO
In mysql, I was able to achieve with following query
ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key
Add Primary Key to First Position
ALTER TABLE table_name
ADD column_name INT PRIMARY KEY AUTO_INCREMENT FIRST;
Reference: Stack Overflow | Tech On The Net
You are getting the error because you have existing data that does not fullfill the constraint.
There are 2 ways to fix it:
clean up the existing data before adding the constraint
add the constraint with the "WITH NOCHECK" option, this will stop sql server checking existing data, only new data will be checked
ALTER TABLE Jaya
ADD CONSTRAINT no primary key(No);
here Jaya is table name,
no is column name,
ADD CONSTRAINT is we giving the primary key keyword
If you want to add a new column say deptId to the existing table say department then you can do it using the below code.
ALTER TABLE department ADD COLUMN deptID INT;
it will create your new column named deptID.
now if you want to add constraint also along with new column while creating it then you can do it using the below code. In the below code I am adding primary key as a constraint. you can add another constraint also instead of primary key like foreign key, default etc.
ALTER TABLE department ADD COLUMN deptID INT NOT NULL ADD CONSTRAINT PRIMARY KEY(deptID);
k. friend
command:
sql> alter table tablename add primary key(col_name);
ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);

Command for adding a default constraint

There appears to be at least two ways to add a default constraint using straight T-SQL. Am I correct that the only difference between the two below is that the second method specifically creates a name for the constraint, and the first method has one generated by SQL Server?
ALTER TABLE [Common].[PropertySetting] ADD DEFAULT ((1)) FOR [Active];
ALTER TABLE [Common].[PropertySetting] ADD CONSTRAINT [DF_PropertySetting_Active) DEFAULT ((1)) FOR [Active];
Pretty much, yes for an ALTER TABLE
You can add a columnn with default in one step for CREATE or ALTER too.
ALTER TABLE dbo.TableName
ADD bar varchar(100) CONSTRAINT DF_Foo_Bar DEFAULT ('bicycle');
ALTER TABLE dbo.TableName
ADD bar varchar(100) DEFAULT ('bicycle');
As you noted, the system generates a name if one is not supplied. CONSTRAINT constraint_name is optional says MSDN. The same applies to any column or table CONSTRAINT
If the column was already created, and you only want to add a (named) DEFAULT constraint, then use:
ALTER TABLE dbo.TableName
ADD CONSTRAINT DF_Foo_Bar DEFAULT 'bicycle' FOR FieldName;
To have the system generate the DEFAULT constraint name (which will be of the form DF_{TableName}_{Column}_{8RandomChars}, e.g. DF_TableName_FieldName_12345678) then omit the CONSTRAINT <name> part, like so:
ALTER TABLE dbo.TableName
ADD DEFAULT 'bicycle' FOR FieldName;