Sobes.tech
Junior

Tell about the syntax for creating a table in a relational database.

sobes.tech AI

Answer from AI

CREATE TABLE table_name (
    column1 datatype constraint, -- Definition of the first column
    column2 datatype constraint, -- Definition of the second column
    column3 datatype constraint, -- Definition of the third column
    ...
    PRIMARY KEY (columnX), -- Definition of the primary key (can be composite)
    FOREIGN KEY (columnY) REFERENCES another_table(another_column) -- Definition of the foreign key
    -- Additional constraints such as UNIQUE, CHECK, DEFAULT, etc.
);

Main elements:

  • CREATE TABLE table_name: Creates a new table with the specified name.
  • column_name datatype: Defines each column in the table. column_name is the name of the column, datatype is the data type it will store (e.g., INT, VARCHAR, DATE).
  • constraint: Optional constraints applied to the column or table (e.g., NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT).

Examples of data types (may vary depending on the DBMS):

  • Numeric: INT, BIGINT, SMALLINT, DECIMAL, FLOAT, DOUBLE
  • String: VARCHAR(length), CHAR(length), TEXT
  • Date/Time: DATE, TIME, DATETIME, TIMESTAMP
  • Boolean: BOOLEAN
  • Binary: BLOB

Examples of constraints:

Constraint Description
NOT NULL The value in the column cannot be NULL.
UNIQUE All values in the column must be unique.
PRIMARY KEY Uniquely identifies each record in the table. Cannot contain NULL.
FOREIGN KEY References PRIMARY KEY in another table, establishing a relationship.
CHECK (condition) Ensures that the value in the column satisfies a specific condition.
DEFAULT value Sets a default value for the column if none is specified.
Tell about the syntax for creating a table in a… - sobes.tech