Archive for August, 2008

Creating Constraints in Oracle

Posted in Oracle, SQL, pl/sql, programming with tags , , on August 11, 2008 by Joey

Constraints define conditions about a database that must remain true. They are used to ensure data integrity. Commonly used constraints are primary key constraints, foreign key constraints, and unique constraints. Constraints are also used to enforce non-null column values.

A constraint is typically defined as part of the table definition as is created using something similar to the following syntax:

CREATE TABLE ORDERS (
ORDER_ID NUMBER(7) NOT NULL,
PRODUCT_ID NUMBER(7) NOT NULL,
PRODUCT_NAME VARCHAR2(100) NOT NULL,
CONSTRAINT ORDER_ID_PK
PRIMARY KEY(ORDER_ID),
CONSTRAINT PRODUCTS_PRODUCT_ID_FK
FOREIGN KEY(PRODUCT_ID)
REFERENCES PRODUCTS(PRODUCT_ID)
)

The preceding table definition creates two constraints: one for the primary key on the ORDER_ID column; and one for the PRODUCT_ID column foreign key.

Constraints can also be created on a table using the ALTER TABLE syntax, as follows:

ALTER TABLE ORDERS
ADD CONSTRAINT PRODUCTS_PRODUCT_ID_FK
FOREIGN KEY(PRODUCT_ID)
REFERENCES PRODUCTS(PRODUCT_ID)

Oracle varchar2 Data Type

Posted in Oracle, pl/sql on August 5, 2008 by Joey

The Oracle varchar2 data type allows for the storage of up to 4000 bytes of character data. It can be defined for a column as follows:

MyColumn varchar2(100) DEFAULT ‘MyString’ NOT NULL;

Note that the varchar data type is now deprecated in Oracle as it’s usage has become a synonym for varchar2, although this may change in future versions.