April 24th, 2009

How do Constraints Work?, DEFAULT

Posted by admin in P. Table Creation

> DEFAULT is a column constraint in a CREATE TABLE statement and can not be a table constraint.

> When inserting a row, if no value is specified and the DEFAULT column constraint is specified, a default value will be inserted.

> The default value must be the same data type and fit in the length of the column definition.

> If no value is specified after the DEFAULT and NOT NULL in the table definition, numeric columns will default to zeroes and character columns will default to spaces.

> If DEFAULT is not defined and NOT NULL is defined and you insert a row with no data in this column, some RDBMS systems will refuse to insert the row, while other RDBMS systems will give a default value that matches the data type.

          CREATE TABLE SAMPLE_TBL
                (ID       CHAR(12)     NOT NULL PRIMARY KEY,
                 TYPE     CHAR(4)      NOT NULL DEFAULT,
                 NUMB     INTEGER          NULL,
                 NAME     VARCHAR(200)          DEFAULT 'unknown',
                 SIZE     SMALLINT     NOT NULL DEFAULT 7,
                 PRICE    DECIMAL(5,2) NOT NULL DEFAULT 0.00,
                 DATE     DATE                  DEFAULT CURRENT_DATE,
                 TIME     TIME                  DEFAULT CURRENT_TIME,
                 QTY      DECIMAL(4,0)          DEFAULT (5+3)*2);
With an INSERT ROW and no value given:

> ID must have a valid value.

> TYPE will default to spaces.

> NUMB will default to null. The NULL definition is optional by default.

> All other columns will default to the specified default value.

> Access, DB2, and MySQL do not allow arithmetic expressions.

> MySQL only allows a literal as a default. You can not use CURRENT_DATE or CURRENT_TIME.

> Oracle does not have CURRENT_DATE. It has SYSDATE and DEFAULT, which must be before constraints.

> SQL Server does not have DATE or TIME. It only has DATETIME.

Comments are closed.

Sorry, the comment form is closed at this time.