23 April 2014

Not Null Constraint -- Constraints

By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed or that column.

A NULL is not the same as any data; rather, it represents unknown data.

Example:

For example, the following SQL creates a new table called CUSTOMERS and adds five columns, three of which, ID and NAME and AGE, specify not to accept NULLs:

CREATE TABLE CUSTOMERS (
       ID   INT              NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE INT              NOT NULL,
       ADDRESS CHAR (25) ,
       SALARY   DECIMAL (18, 2),       
       PRIMARY KEY (ID)
);
 
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to SALARY column in Oracle and MySQL, you would write a statement similar to the following:


ALTER TABLE CUSTOMERS
   MODIFY SALARY DECIMAL (18, 2) NOT NULL;

Creating Not Null Constraint using Sql server Management Studio
If you prefer to interact with SQL Server using GUI tools, you may also create a NOT NULL constraint using SQL Server Management Studio. 
  • Open SQL Server Management Studio.
  • Expand the Tables folder of the database where you wish to create the constraint.
  • Right-click the table where you wish to addthe constraint and click Design.
  • Check the NOT NULL checkbox for the column(s) that you wish to have NOT NULL constraint(s)

No comments:

Post a Comment