How do I set the default value for a column?

16,201

Solution 1

Basic MySQL Alter Table command

If the column doesn't exist:

alter table Mystery add column BEST_SELLER enum('N','Y') default 'N';

and if column exists:

alter table Mystery alter column BEST_SELLER set default 'N';

Solution 2

I am adding a second answer because of your response to my first answer. This answer applies since:

  1. You are using Oracle, and
  2. You have already created the table, so you need to use "ALTER TABLE" syntax.

Please find enclosed the following:

alter table
    mystery
modify
    BEST_SELLER char(1) DEFAULT 'N'

Please modify the type char(1) to whatever the column actually is. After running this query to correct the table, you will need to issue a second query to update the existing rows, such as:

UPDATE 
    mystery 
SET 
    BEST_SELLER = 'N' 
WHERE 
       BEST_SELLER = '' 
    OR BEST_SELLER IS NULL

Hope this helps.

Share:
16,201
Michael
Author by

Michael

Updated on June 15, 2022

Comments

  • Michael
    Michael almost 2 years

    Note the table below. I am wanting to set the default value for the newly created BEST_SELLER column to "N".
    How do I go about doing that?

    Create Table Mystery
    (Book_Code Char(4) Primary Key,
     Title Varchar2(40),
     Publisher_Code Char(2),
     Price Number(4,2))