Sub topic 1
Anatomy of a CREATE TABLE statement
A CREATE TABLE statement names a table, lists its columns, and optionally attaches rules and storage settings. This chapter covers the statement's structure and the choices you make before any constraints are added. Later chapters go deeper on data types, constraints, and identity columns.
Prerequisites
This chapter assumes you can do the following:
- Write basic
SELECT,INSERT,UPDATE, andDELETEstatements. - Explain what a table, a row, and a key are in a relational database.
- Connect to an Oracle Database 12c or later schema with SQL*Plus, SQLcl, or SQL Developer, and run statements there.
- Create objects in your own schema. This needs the
CREATE TABLEprivilege and a quota on a tablespace.
The overall shape
Every CREATE TABLE statement has the same parts, in this order:
- The keywords
CREATE TABLE. - An optional schema name and the table name.
- A parenthesized, comma-separated list of column definitions and, optionally, out-of-line constraints.
- Optional table properties after the closing parenthesis, such as
TABLESPACE.
Here is a small, complete example:
CREATE TABLE projects (
project_id NUMBER,
project_name VARCHAR2(100) NOT NULL,
start_date DATE DEFAULT SYSDATE,
budget NUMBER(12,2)
);Oracle reports Table created. when the statement succeeds. The table is empty and has four columns. project_name has an inline NOT NULL rule, and start_date has a default.
Column definitions
Each column definition follows this pattern:
column_name data_type [DEFAULT expression] [identity clause] [inline constraints]Only the name and data type are required. When you include the optional parts, write them in the order shown. For example, DEFAULT comes before NOT NULL:
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULLWriting NOT NULL DEFAULT 'ACTIVE' raises a syntax error (ORA-00907 or ORA-00923, depending on the tool and position).
Column order matters in two ways:
SELECT *andINSERTwithout a column list use the order in which you declared the columns.- Oracle assigns each column a position number (
COLUMN_ID). You cannot reorder columns later with a simple statement. You can only add columns at the end, or use theINVISIBLEandVISIBLEattributes as a workaround.
Always name the columns in your INSERT statements. Then a later table change cannot silently break them.
Inline and out-of-line constraints
Rules can be attached in two places:
- Inline (column-level): written as part of one column definition, as with
NOT NULLabove. - Out-of-line (table-level): written as a separate item in the parenthesized list, after the column definitions.
CREATE TABLE project_tasks (
task_id NUMBER NOT NULL,
project_id NUMBER NOT NULL,
task_name VARCHAR2(200) NOT NULL,
CONSTRAINT project_tasks_pk PRIMARY KEY (task_id)
);Constraints that involve more than one column must be out-of-line. A constraint on a single column can go either way. The CONSTRAINT name prefix is optional. If you leave it out, Oracle assigns a name such as SYS_C0012345, which is hard to read in error messages. The chapter on constraint naming covers this in detail.
Naming rules for tables and columns
Oracle applies the same rules to table names and column names.
- A name must begin with a letter.
- After the first character it can contain letters, digits, and the characters
_,$, and#. - The limit is 128 bytes from Oracle Database 12.2 onward (when
COMPATIBLEis 12.2 or higher). Earlier versions allow 30 bytes. - A name cannot be a reserved word such as
SELECT,TABLE, orORDER. - Unquoted names are case-insensitive and stored in uppercase.
projects,Projects, andPROJECTSall refer to the same table.
You can break most of these rules by wrapping a name in double quotes:
CREATE TABLE "Project Notes" (
note_id NUMBER,
note VARCHAR2(4000)
);This works, but from then on every reference must use the exact quoted spelling, "Project Notes", including the case and the space. Tools and ORMs often trip over this. Stick with unquoted, underscore-separated names unless you have to match an existing naming scheme.
Schemas and the shared namespace
A table belongs to a schema, which is the set of objects owned by one database user. Without a prefix, Oracle creates the table in the schema you are connected to. You can also qualify the name:
CREATE TABLE hr_demo.holidays (
holiday_date DATE,
description VARCHAR2(100)
);Creating a table in another user's schema requires the CREATE ANY TABLE privilege. This is rarely appropriate for application work.
Within one schema, a table name must be unique among more than tables. Tables, views, sequences, private synonyms, and several other object types share one namespace. If you try to reuse a name, Oracle raises:
ORA-00955: name is already being used by an existing objectThis also happens when a view or sequence already has the name you picked. Identity columns create a system-managed sequence for you, but that sequence gets a generated ISEQ$$_ name, so it will not collide with your table names.
Creating a table from a query
CREATE TABLE ... AS SELECT (often called CTAS) creates a table and fills it from a query in a single statement:
CREATE TABLE projects_archive AS
SELECT project_id, project_name, start_date, budget
FROM projects
WHERE 1 = 0;The condition 1 = 0 is never true. The statement therefore copies only the structure and no rows. Remove it to copy the data as well.
CTAS takes column names and data types from the query. It carries over NOT NULL constraints. It does not copy primary keys, unique constraints, foreign keys, or check constraints, so you must add those afterward. You can rename columns by listing new names in parentheses after the table name:
CREATE TABLE project_budgets (project, planned_budget) AS
SELECT project_name, budget
FROM projects;Table properties after the column list
Everything after the closing parenthesis describes how Oracle stores the table. The most common clause is TABLESPACE, which picks where the table's segment lives:
CREATE TABLE audit_events (
event_id NUMBER,
event_time TIMESTAMP DEFAULT SYSTIMESTAMP,
details VARCHAR2(4000)
)
TABLESPACE users;This statement runs only if a tablespace named USERS exists and you have a quota on it. If you leave the clause out, Oracle uses your default tablespace. Most application tables do not need other storage clauses, because modern Oracle versions manage extents and block usage automatically. Other options exist for temporary tables, partitioning, compression, and external tables. They are outside this tutorial.
Oracle creates the table's storage lazily by default, a feature called deferred segment creation. The table exists in the data dictionary right away, but it takes no space until the first row is inserted. This is why a brand-new empty table may not appear in some space-usage views.
Checking what you created
You can confirm the result in two ways. DESCRIBE is a SQL*Plus and SQLcl command, and the query uses the data dictionary:
DESCRIBE projects
SELECT column_id, column_name, data_type, data_length, nullable, data_default
FROM user_tab_columns
WHERE table_name = 'PROJECTS'
ORDER BY column_id;Note the uppercase 'PROJECTS'. Dictionary views store unquoted names in uppercase, so a lowercase comparison finds nothing. The NULLABLE column shows N for columns with a NOT NULL rule. DATA_DEFAULT shows the default expression, such as SYSDATE.
Dropping and re-creating
During development you will often recreate tables. Use DROP TABLE:
DROP TABLE project_budgets;
DROP TABLE projects_archive PURGE;By default a dropped table goes to the recycle bin, where its space is held and it can be restored with FLASHBACK TABLE ... TO BEFORE DROP. Adding PURGE frees it immediately and cannot be undone. If other tables have foreign keys pointing at the table, add CASCADE CONSTRAINTS to the drop, or drop the child tables first.
Common errors
| Error | Typical cause |
|---|---|
| `ORA-00955` | The name is already used by a table, view, sequence, or synonym in the schema. |
| `ORA-00904` | A column name is invalid or was spelled differently than at creation, often a quoting or case problem. |
| `ORA-00972` | The identifier is too long for the database's limit. |
| `ORA-00902` | A data type is missing or not recognized. |
| `ORA-01031` | You lack the privilege to create tables. |
| `ORA-01950` | You have no quota on the target tablespace. |
Exercise
You run CREATE TABLE orders (...) and receive ORA-00955, although you are sure no table called ORDERS exists in your schema. What is the most likely cause, and how can you find the conflicting object?
Show answer
Another object type in the same schema, such as a view, sequence, or synonym, already uses the name ORDERS, because these types share one namespace with tables. Query USEROBJECTS with WHERE objectname = 'ORDERS' to see the type of the conflicting object, then rename it or choose another table name.
Exercise
Write a CREATE TABLE statement for a table named events with a NUMBER column eventid, a VARCHAR2(50) column eventname that cannot be NULL, and a DATE column event_date that defaults to the current date. Then give the query that confirms the defaults in the data dictionary.
Show answer
CREATE TABLE events (eventid NUMBER, eventname VARCHAR2(50) NOT NULL, eventdate DATE DEFAULT SYSDATE); then SELECT columnname, nullable, datadefault FROM usertabcolumns WHERE tablename = 'EVENTS' ORDER BY column_id; The table name in the query is uppercase because unquoted names are stored in uppercase.