SQL CREATE TABLE
CREATE TABLE defines a new table: its name, its columns and each column's data type. Constraints such as PRIMARY KEY, NOT NULL and REFERENCES protect your data.
Common PostgreSQL types: INTEGER, NUMERIC(10,2) for money, TEXT, DATE, TIMESTAMP and BOOLEAN.
Syntax
CREATE TABLE table_name ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, other_id INTEGER REFERENCES other(id) );
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Create and fill a table
CREATE TABLE reviews (id INTEGER PRIMARY KEY, product_id INTEGER REFERENCES products(id), rating INTEGER NOT NULL, comment TEXT); INSERT INTO reviews VALUES (1, 3, 5, 'Great!'); SELECT * FROM reviews;
A new table with one row (rolled back afterwards).
Common mistakes
- Storing money as FLOAT, which causes rounding errors. Use NUMERIC.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Create a table reviews with columns id (integer, primary key), product_id (integer), rating (integer) and comment (text). Then insert one review: id 1, product 3, rating 5, comment 'Great!'.
FAQ
What is a primary key?
A column (or columns) that uniquely identifies each row. It cannot be NULL or repeated.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.