CREATE TABLE
Creates a new table, with its columns and the constraints that apply to them.
Access SQL, with one LibRed extension. ACE accepts this statement as written here, except for a calculated
column (AS (expression)), which is a LibRed extension and is marked where it is described.
Syntax
Section titled “Syntax”CREATE [ TEMPORARY ] TABLE table_name ( { column_definition | table_constraint } [ , … ] )
column_definition ::= column_name data_type [ AS ( expression ) ] [ column_constraint … ]
column_constraint ::= NULL | NOT NULL | DEFAULT [ = ] expression | WITH { COMPRESSION | COMP } | IDENTITY [ ( seed [ , increment ] ) ] | [ CONSTRAINT constraint_name ] PRIMARY KEY [ CLUSTERED | NONCLUSTERED ] | [ CONSTRAINT constraint_name ] UNIQUE [ CLUSTERED | NONCLUSTERED ] | [ CONSTRAINT constraint_name ] REFERENCES ref_table [ ( ref_column [ , … ] ) ] [ referential_action … ]
table_constraint ::= [ CONSTRAINT constraint_name ] PRIMARY KEY [ CLUSTERED | NONCLUSTERED ] ( column_name [ , … ] ) | [ CONSTRAINT constraint_name ] UNIQUE [ CLUSTERED | NONCLUSTERED ] ( column_name [ , … ] ) | [ CONSTRAINT constraint_name ] FOREIGN KEY [ NO INDEX ] ( column_name [ , … ] ) REFERENCES ref_table [ ( ref_column [ , … ] ) ] [ referential_action … ] | [ CONSTRAINT constraint_name ] CHECK ( expression )
referential_action ::= ON { UPDATE | DELETE } { CASCADE | NO ACTION | RESTRICT | SET NULL | SET DEFAULT }Arguments
Section titled “Arguments”TEMPORARY
Section titled “TEMPORARY”Accepted by the parser, but the statement then fails: LibRed does not create temporary tables.
table_name
Section titled “table_name”The name of the new table. The statement fails if a table of that name already exists.
column_name data_type
Section titled “column_name data_type”A column and its type. The type names LibRed accepts are listed under Data types. A column needs a type; a calculated column needs one too.
NULL | NOT NULL
Section titled “NULL | NOT NULL”Whether the column may hold a Null. NULL is the default. NOT NULL makes the column required: an INSERT
that leaves it Null fails.
DEFAULT expression
Section titled “DEFAULT expression”The value an INSERT gives the column when it names no value for it. The expression is stored as written, a
leading = included, and evaluated afresh for each row it fills. It may use constants, operators and scalar
functions (Now(), Date(), IIf(…)), but not another column, a subquery, an aggregate or an unknown function.
A default the column’s type cannot hold, such as DEFAULT 300 on a BYTE, fails the statement.
WITH COMPRESSION | WITH COMP
Section titled “WITH COMPRESSION | WITH COMP”Stores the column’s text with Unicode compression. It applies to text and memo columns only; on any other type the statement fails.
IDENTITY [ ( seed [ , increment ] ) ]
Section titled “IDENTITY [ ( seed [ , increment ] ) ]”Makes a Long column an AutoNumber that counts from seed by increment, each 1 when left out. The increment
may be negative. It must come straight after the type, after NULL or NOT NULL, or after another IDENTITY;
after DEFAULT, PRIMARY KEY or another constraint it is a syntax error. On a type other than Long it is
accepted and ignored. IDENTITY may also stand as the type itself: Id IDENTITY(5, 2).
PRIMARY KEY
Section titled “PRIMARY KEY”Makes the column, or with the table form the listed columns, the table’s primary key. A primary key is unique and every key column must have a value.
A table has one primary key, declared once. A second PRIMARY KEY, on another column, on the same column, or a
table-level one beside a column-level one, fails with “Primary key already exists.” For a key over several
columns, use the table form: PRIMARY KEY (OrderID, ProductID).
UNIQUE
Section titled “UNIQUE”Creates a unique index on the column or columns. As with CREATE UNIQUE INDEX, a key that
has a Null in it is never a duplicate.
CLUSTERED | NONCLUSTERED
Section titled “CLUSTERED | NONCLUSTERED”Accepted after PRIMARY KEY or UNIQUE and ignored. ACE stores nothing for either word.
REFERENCES ref_table [ ( ref_column [ , … ] ) ]
Section titled “REFERENCES ref_table [ ( ref_column [ , … ] ) ]”A foreign key: each value in the column (or columns) must match a row in ref_table, or be Null. With no
column list it references ref_table’s primary key, pairing the columns in order. The statement fails if
ref_table has no primary key, if the number of columns differs, or if a pair of columns differs in storage
type. An AutoNumber counts as a Long here, and lengths may differ: a TEXT(20) can reference a TEXT(10).
A table may reference itself. With no column list, the primary key must be declared earlier in the statement than the reference.
FOREIGN KEY [ NO INDEX ] ( column_name [ , … ] )
Section titled “FOREIGN KEY [ NO INDEX ] ( column_name [ , … ] )”The table form of a foreign key, for one or more columns. A foreign key normally creates an index over its
columns in the referencing table. NO INDEX creates the relationship without that index.
referential_action
Section titled “referential_action”What happens to referencing rows when a referenced row is deleted (ON DELETE) or its key is changed
(ON UPDATE). The two may be written in either order.
| Action | ON DELETE |
ON UPDATE |
|---|---|---|
NO ACTION (the default) |
The delete fails while referencing rows exist. | The change fails while referencing rows exist. |
RESTRICT |
Same as NO ACTION. |
Same as NO ACTION. |
CASCADE |
Deletes the referencing rows. | Changes the referencing rows’ key to match. |
SET NULL |
Sets the referencing columns to Null. | Not supported: the statement fails. |
SET DEFAULT |
Same as NO ACTION. |
Same as NO ACTION. |
A cascade carries on down a chain of relationships, because each row it changes applies its own relationships in turn.
CHECK ( expression )
Section titled “CHECK ( expression )”A condition every row must meet. An INSERT or UPDATE that makes the condition False fails. There is no
column form: CHECK after a column’s type is a syntax error, as it is in ACE. Write it as a table constraint
instead.
constraint_name
Section titled “constraint_name”The name of the constraint. A primary key, unique constraint or foreign key creates an index of this name, and
ALTER TABLE … DROP CONSTRAINT removes the constraint by it. Without a name, LibRed
generates one. An unnamed foreign key is named as ACE names one: Rel_ and part of a new GUID.
AS ( expression )
Section titled “AS ( expression )”LibRed extension. Makes the column a calculated column: its value is the expression, worked out from the row’s other columns when the row is inserted and again whenever a column it reads changes. ACE has no SQL syntax for a calculated column (Access creates them through DAO), so a statement that uses this runs on LibRed only. The file that results is an ordinary Access file with a calculated column in it.
The declared data_type is the type of the result. The parentheses are required. A calculated column cannot
also be NOT NULL, have a DEFAULT, be WITH COMPRESSION or be a PRIMARY KEY.
The expression is stored in the file and evaluated by the Access expression service’s rules, which are
ANSI-89, not the ANSI-92 the rest of LibRed’s SQL uses. In particular, LIKE in a calculated column takes
* and ? as its wildcards, not % and _. See wildcards.
Data types
Section titled “Data types”Type names aren’t case-sensitive. A name in the same row is an alias: it creates the same kind of column.
| Type names | Access type | Notes |
|---|---|---|
COUNTER, AUTOINCREMENT, IDENTITY |
AutoNumber (Long) | Optional (seed, increment), each 1 by default. |
LONG, INTEGER, INT, INTEGER4 |
Long Integer | 4 bytes. |
SHORT, SMALLINT, INTEGER2 |
Integer | 2 bytes. |
BYTE, TINYINT, INTEGER1 |
Byte | 1 byte. |
BIGINT |
Large Number | 8 bytes. Needs the ACE 16 file format (see Remarks). |
SINGLE, REAL, IEEESINGLE, FLOAT4 |
Single | |
DOUBLE, FLOAT, DOUBLE PRECISION, IEEEDOUBLE, FLOAT8, NUMBER |
Double | |
CURRENCY, MONEY, SMALLMONEY |
Currency | SMALLMONEY is the same 8-byte Currency. |
DATETIME, DATE, TIME, TIMESTAMP, SMALLDATETIME |
Date/Time | SMALLDATETIME is the same 8-byte Date/Time. |
DATETIME2 |
Date/Time Extended | Needs the ACE 17 file format. No aliases. |
YESNO, BIT, BOOLEAN, LOGICAL, LOGICAL1 |
Yes/No | |
GUID, UNIQUEIDENTIFIER |
Replication ID | 16 bytes. |
DECIMAL, NUMERIC, DEC |
Decimal | (precision, scale): precision 1 to 28, default 18; scale 0 to the precision, default 0. |
TEXT(n), VARCHAR, NVARCHAR, STRING, ALPHANUMERIC, CHARACTER VARYING, CHAR VARYING, NATIONAL CHAR VARYING, NATIONAL CHARACTER VARYING, NCHAR VARYING, NATIONAL TEXT(n) |
Text | Variable length, (n) characters, at most 255. Without a size, 255. |
CHAR, CHARACTER, NCHAR, NATIONAL CHAR, NATIONAL CHARACTER |
Text, fixed length | Padded with spaces to (n) characters, at most 255. Without a size, 255. |
TEXT (no size), MEMO, LONGTEXT, LONGCHAR, NOTE, NTEXT, NATIONAL TEXT (no size) |
Memo | Long text. |
BINARY |
Binary, fixed length | (n) bytes, at most 510. Without a size, 510. |
VARBINARY, BINARY VARYING, BIT VARYING |
Binary | Variable length, (n) bytes, at most 510. Without a size, 510. |
BIGBINARY |
Binary (long) | Variable length, (n) bytes, at most 4000. Without a size, 4000. |
LONGBINARY, OLEOBJECT, IMAGE, GENERAL |
OLE Object | Long binary data. |
TEXT with a size is a Text column; TEXT with none is a Memo. A size larger than the type allows fails the
statement rather than widening the column: use MEMO or LONGBINARY for longer values. A type name not in the
table fails the statement.
Remarks
Section titled “Remarks”A table constraint may appear anywhere in the list, between columns too, but it can only name columns declared
before it. CREATE TABLE T (CONSTRAINT pk PRIMARY KEY (Id), Id LONG) fails.
A table has at most one primary key, and one AutoNumber column.
NULL, NOT NULL and DEFAULT follow ACE’s placement rules. NULL and NOT NULL may not stand side by side
before the DEFAULT, NOT NULL may not appear twice, and a NULL after the DEFAULT is a syntax error.
A CHECK is stored as the text you wrote and evaluated on every INSERT and UPDATE of the table. ACE enforces
a CHECK that LibRed wrote. The condition may contain a subquery: CHECK ((SELECT COUNT(*) FROM Quota) <= 2) on
a table Quota refuses a third row.
File format upgrade
Section titled “File format upgrade”BIGINT needs the ACE 16 file format, DATETIME2 the ACE 17 format, and a calculated column the ACE 14 format.
When the open file is older, CREATE TABLE raises the file’s format version to the one the column needs rather
than failing, which is what ACE does too. The raise is part of the statement’s transaction, so a statement that
fails leaves the version as it was.
The raise is one way. An older version of Access cannot open the file afterwards. A Jet 4 .mdb file cannot take
an ACE format, and the statement fails there. To start a database at a given format, create it with
LibRedConnection.CreateDatabase(…, version:) instead.
Differences from ACE
Section titled “Differences from ACE”- Calculated columns (
AS (expression)) are a LibRed extension. ACE has no syntax for them. DEFAULTtakes any expression LibRed can parse. ACE’s own DDL parser refuses many valid defaults, such as1 + 2with spaces, a concatenation or a nested call likeYear(Now()). ACE still reads and applies such a default when LibRed has written it.- A column whose name the database’s sort order treats as equal to another column’s is refused. ACE accepts
such a column (
prebesidepreț, for example), after which every reference reaches only the first.
Examples
Section titled “Examples”These run against the Northwind sample database, as in the playground. Each example creates its own tables, but the second refers to the first.
Create a table with an AutoNumber primary key, a foreign key to Customers, and two defaults:
CREATE TABLE Notes ( NoteID COUNTER CONSTRAINT pkNotes PRIMARY KEY, CustomerID TEXT(5) NOT NULL REFERENCES Customers, Subject TEXT(100) WITH COMPRESSION, Body MEMO, Created DATETIME DEFAULT Now(), Pinned YESNO DEFAULT False)Create a link table with a two-column primary key and foreign keys that cascade:
CREATE TABLE Tags ( TagID LONG NOT NULL, Name TEXT(50) NOT NULL, CONSTRAINT pkTags PRIMARY KEY (TagID), CONSTRAINT uqTagName UNIQUE (Name))CREATE TABLE NoteTags ( NoteID LONG NOT NULL, TagID LONG NOT NULL, CONSTRAINT pkNoteTags PRIMARY KEY (NoteID, TagID), CONSTRAINT fkNoteTagsNote FOREIGN KEY (NoteID) REFERENCES Notes (NoteID) ON DELETE CASCADE, CONSTRAINT fkNoteTagsTag FOREIGN KEY (TagID) REFERENCES Tags ON UPDATE CASCADE ON DELETE CASCADE)Create an AutoNumber that starts at 100 and counts in tens:
CREATE TABLE Tickets (TicketID AUTOINCREMENT(100, 10) CONSTRAINT pkTickets PRIMARY KEY, Subject TEXT(100))Add a CHECK constraint. The second INSERT fails:
CREATE TABLE Prices (ProductID LONG NOT NULL, Price CURRENCY NOT NULL, CONSTRAINT ckPrice CHECK (Price >= 0))INSERT INTO Prices VALUES (1, 9.5)INSERT INTO Prices VALUES (2, -1)Create a calculated column (LibRed extension). Total reads 7.5 after the INSERT:
CREATE TABLE Lines (Qty LONG, Price CURRENCY, Total CURRENCY AS ([Qty] * [Price]))INSERT INTO Lines (Qty, Price) VALUES (3, 2.5)Create a BIGINT column. On Northwind, which is an ACE 12 file, this raises the file to the ACE 16 format:
CREATE TABLE Counters (Name TEXT(50), Hits BIGINT)