SQL Multiple constraints on a single column - sql

I am working with sql server and the table of workers.
I need to add a column "Gender" and apply two constraints : check and default.
So i need to check that they gender is male/female and the default value should be "To be updated"
My query looks like that by it doesn't work:
ALTER TABLE Workers
ADD Gender VARCHAR(6) CHECK (Gender IN ('Male', 'Female'))
DEFAULT 'To be updated'

You don't say what "doesn't work" means, however varchar(6) doesn't accomodate the 13 characters of 'To be updated', and you need to include your default value as an allowable value. It's also a good idea to specifically name the constraints which enables you to easily reference them in future.
alter table Workers add
Gender varchar(13)
constraint GenderCheck check (Gender in ('Male', 'Female','To be updated') )
constraint GenderDefault default ('To be updated');
Working Demo
Also note - specifying not null when adding the column will apply the default to existing rows.

Related

How to add NOT NULL constraint along with default value for the column?

I have a column 'name' in student table. I need to add NOT NULL constraint on this column. But I get SQL error saying cannot add null constraint since the existing rows in the table has null values in the column. How would I add a null constraint along with default value in a single alter statement. Below is my query.
alter table Student alter column name nvarchar NOT NULL;
SQL Server does not make this easy. I think the only way is to set the existing values to the default that you want. Then change the column to have a default value and not null:
-- Get rid of the existing `NULL` values
update students set name = '' where name is null;
-- Add the NOT NULL constraint
alter table students
alter column name varchar(255) not null;
-- Add a default value
alter table students
add constraint df_t_name default '' for name ;
Here is what it looks like in practice.
But I get SQL error saying cannot add null constraint since the existing rows in the table has null values in the column.
Have you tried overwriting the existing NULL values?
You can't have a constraint on a column when existing values would violate that constraint. You need to make your table compliant first.

i feel like i got this wrong

The commission classification column should be able to store integers up to a maximum value of 99 and be named Comm_id. The value of the Comm_id column should be set to a value of 10 automatically if no value is provided when a row is added. The benefits code column should also accommodate integer values up to a maximum of 99 and be named Ben_id.
alter table ACCTMANAGER
add (Comm_id varchar2(99),
Ben_id varchar2(99));
I dont know if this is right
alter table ACCTMANAGER add(Comm_id number(2) default 10, Ben_id number(2));
Basically for number data type you have precision and scale. and if scale is not specified scale is 0 which means no decimal places after the number. number(2) means you can only store up to two digit number here and default keyword set the value automatically if column was not specified.
BTW try using oracle documentation for this homework type of stuff. here is with good examples.
https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#i16209
EDITED
alter table ACCTMANAGER add(Comm_id number(2) default 10 constraint lowchk1 check(comm_id>=0) , Ben_id number(2) constraint lowchk2 check(ben_id>=0));
Sorry I can't check syntax for sure as I don't have Oracle installed at home. I only work at it at office.
#MSStp provided a good answer, but you still need constraints to make sure you don't get bad data in the table (such as negative numbers). If the constraint is that the commission and the benefit columns must contain integers between 0 and 99, and you want to make sure Oracle will not accept an input of 2.2 (which it WILL accept in MS's solution, it will just truncate it to 2 and store 2 in the database), you need to add constraints as Abdul Rehman Sayed suggested in a Comment to your question.
alter table acctmanager
add ( comm_id number(2) default 10
constraint check_comm ( comm_id >= 0 and comm_id = trunc(comm_id) ),
ben_id number(2)
constraint check_ben ( ben_id >= 0 and ben_id = trunc(ben_id) )
)
;
However: Just a thought..... What are comm_id and ben_id? If they are some sort of codes to specific commission and benefit descriptions/levels/whatever, do you really need check constraints? Do you have different tables explaining these codes, where comm_id and ben_id are (or should be) primary keys? In which case you need foreign key constraints, NOT check constraints?
ALTER TABLE ACCTMANGER ADD(Comm_id NUMBER(2) DEFAULT 10 NOT NULL, Ben_id NUMBER(2));
After that, you can see that the table is altered.
To see the Output write this:
DESC ACCTMANAGER;
You will see the whole table with the updated column.

How do you modify the default to accept Y or N not just Y in SQL

I'm trying to modify the default in a column on an existing table but it is not working. I have researched in other sites but it's not working.
ALTER TABLE STOREREPS
MODIFY (COMM DEFAULT ('Y', 'N'));
where my default is set to just Y.
I am using Oracle 11g SQL Developer.
You can only have one default value. The default value is used when you INSERT a row into the table and don't specify a value for the column. You can add a CHECK constraint to ensure that only 'Y' or 'N' is allowed, though; that is probably what you are seeking.
Subject to variations per DBMS (now identified as Oracle), you could write something like:
ALTER TABLE STOREREPS
MODIFY (COMM DEFAULT 'Y'),
ADD CONSTRAINT check_comm_y_n CHECK (COMM IN ('Y', 'N'));
In a CREATE TABLE statement, that might be:
CREATE TABLE StoreReps
(
…
Comm CHAR(1) NOT NULL DEFAULT 'Y'
CONSTRAINT check_comm_y_n CHECK (Comm IN ('Y', 'N')),
…
);
but the exact syntax varies by DBMS.

Multiple constraints on a single column

I want to ensure that only the values 'Expert', 'Average' or 'Adequate' are entered into the levelOfExpertise column of this table, however whenever I do try an enter one of those values, it returns an error saying the value entered is too short. Here is the create table query for this particular table. The the column I am referring to is levelOfExpertise:
CREATE TABLE MusicianInstrument
(
musicianNo varchar(5) not null
CONSTRAINT MI_PK1 REFERENCES Musician(musicianNo),
instrumentName varchar(50) not null
CONSTRAINT MI_PK2 REFERENCES Instrument(instrumentName),
levelOfExpertise varchar(50),
CONSTRAINT levelOfExpertise CHECK (levelOfExpertise = 'Expert', 'Adequate', 'Avergage'),
PRIMARY KEY(musicianNo,instrumentName)
);
Any ideas how I can ensure only those three values (Expert, Adequate or Average) can be entered?
Thanks
Use the IN operator
CHECK (levelOfExpertise IN ('Expert','Adequate','Avergage'))
Try to change your CHECK constraint as following:
CONSTRAINT levelOfExpertise CHECK (levelOfExpertise IN ('Expert','Adequate','Avergage'))
I suppose that you use sql server as RDBMS.

Can I add a not null column without DEFAULT value

Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'test' cannot be added to non-empty table 'shiplist' because it does not satisfy these conditions.
If YES, please let me know the syntax, if No please specify the reason.
No, you can't.
Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.
The simplest way to do this is create the column with a default and then remove the default.
ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn
Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.
Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.
No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have
It's easy to create a DEFAULT at the same time, and then immediately drop it.
I use this approach to insert NOT NULL column without default value
ALTER TABLE [Table] ADD [Column] INT NULL
GO
UPDATE [Table] SET [Column] = <default_value>
ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
No.
Just use empty string '' (in case of character type) or 0 (if numeric), etc as DEFAULT value
No you cannot. But you can consider to specify the default value to ('')
No, you can't, as SQL Server, or any other database engines will force this new column to be null for existing rows into your data table. But since you do not allow a NULL, you are required to provide a default value in order to respect your own constraint. This falls under great sense! The DBE will not extrapolate a value for non-null values for the existing rows.
#Damien_The_Unbeliever's comment ,
Is it adding computed column? Neither question nor answer implied anything like that. In case of computed column the error states:
"Only UNIQUE or PRIMARY KEY constraints can be created on computed columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require that computed columns be persisted"
OK, if to continue this guessing game, here is my script illustrating the adding of "NOT NULL" column in one "ALTER TABLE" step:
CREATE TABLE TestInsertComputedColumn
(
FirstName VARCHAR(100),
LastName CHAR(50)
);
insert into TestInsertComputedColumn(FirstName,LastName)
select 'v', 'gv8';
select * from TestInsertComputedColumn;
ALTER TABLE TestInsertComputedColumn
ADD FullName As FirstName + LastName PERSISTED NOT NULL;
select * from TestInsertComputedColumn;
--drop TABLE TestInsertComputedColumn;
I used below approach it worked for me
Syntax:
ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Example:
ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO