How do you create a new table in SQL?

Instruction: Explain the process of creating a new table within a database using SQL.

Context: This question tests the candidate's ability to articulate the steps involved in defining a new table structure using the CREATE TABLE statement.

Updated

Official answer

CREATE TABLE defines columns, data types and constraints. Design the row grain and required invariants first. This PostgreSQL example creates its referenced table before the child:

CREATE TABLE departments (
  department_id integer PRIMARY KEY,
  department_name text NOT NULL
);
CREATE TABLE employees (
  employee_id integer PRIMARY KEY,
  employee_name text NOT NULL,
  department_id integer NOT NULL REFERENCES departments(department_id),
  salary numeric(12,2) NOT NULL CHECK (salary >= 0)
);

Each employee has a unique ID, a non-NULL name, an existing department and a nonnegative salary. A NOT NULL name may still be an empty string; add a justified business constraint if that is forbidden. This example requires callers to provide IDs; it does not declare an identity generator.

Choose schema ownership and privileges deliberately, use migrations for changes, and test valid and rejected inserts. Defaults, identity syntax and transactional DDL behavior vary by engine. Index design follows actual access patterns, not a rule to index every column.

Related Questions