Oracle is one of the most popular relational databases at present. Its table creation is relatively complicated, but as long as you understand the rules and follow the correct methods, you can easily create a table that meets the requirements. Let's introduce in detail how Oracle creates tables.
Before creating a table in Oracle, you first need to determine the table name and its field names, which will affect future database operations. (Note: Oracle is case-insensitive, please choose the spelling format according to the actual situation)
Creating table structure refers to defining the fields of the table, Type, length and constraints. In Oracle, you can use the following statement to create a simple table:
CREATE TABLE 表名( 字段1 数据类型(长度) [约束条件], 字段2 数据类型(长度) [约束条件], ... 字段n 数据类型(长度) [约束条件] );
Or use the following statement:
CREATE TABLE 表名( 字段1 数据类型, 字段2 数据类型, ... 字段n 数据类型, CONSTRAINT 约束名1 约束条件(列名), CONSTRAINT 约束名2 约束条件(列名) );
Among them, the data type and length are required fields, and the following are commonly used data types:
Constraints refer to restrictions on data. The following are commonly used constraints:
For example, create a table named students, containing three fields: id, name and gender, where id is the primary key, name is a string type with a length of 20, and gender is a string type. The length is 1 and cannot be empty. You can use the following statement to create it:
CREATE TABLE students( id NUMBER(10) PRIMARY KEY, name VARCHAR2(20) NOT NULL, gender CHAR(1) NOT NULL );
In the process of creating a table, you can add multiple constraints , used to limit the correctness of data. The following are some examples of constraints:
CONSTRAINT pk_students PRIMARY KEY(id)
CONSTRAINT uk_students UNIQUE(name)
CONSTRAINT fk_students FOREIGN KEY(dept_id) REFERENCES departments(dept_id)
CONSTRAINT ck_students_gender CHECK(gender IN ('M', 'F'))
After defining the structure and constraints of the table, you can start creating the table. In the SQLPLUS environment, you can enter the following statement to create a table:
SQL> CREATE TABLE students( 2 id NUMBER(10) PRIMARY KEY, 3 name VARCHAR2(20) NOT NULL, 4 gender CHAR(1) NOT NULL 5 );
or use the following statement:
SQL> CREATE TABLE students( 2 id NUMBER(10), 3 name VARCHAR2(20), 4 gender CHAR(1), 5 CONSTRAINT pk_students PRIMARY KEY(id), 6 CONSTRAINT uk_students UNIQUE(name), 7 CONSTRAINT ck_students_gender CHECK(gender IN ('M', 'F')) 8 );
At this time, Oracle will return a success message, indicating that the table has been created successfully.
Summary: The above is the process of creating a table in Oracle. The steps are simple, but the table structure and constraints need to be determined according to the actual situation, which will help with future database operations and maintenance.
The above is the detailed content of oracle how to create table. For more information, please follow other related articles on the PHP Chinese website!