CREATE TABLE in SQL: building tables, explained and practiced

CREATE TABLE sets up a new table: its name, its columns, their data types and the rules every row has to follow. Good rules stop bad data at the door, long before it skews a report.

In short: CREATE TABLE suppliers (supplier_id INTEGER PRIMARY KEY, name TEXT NOT NULL) creates an empty table. Every column gets a name, a data type and, where needed, rules such as NOT NULL (required), DEFAULT (fallback value) or CHECK (allowed values).

What you should know first: reading data with SELECT and adding rows with INSERT.

Try it now

This time you build a table instead of querying one. After your statement runs, the exercise inserts test data and shows you what ended up in your table, so you can see straight away whether your required fields and defaults do their job.

Task Product categories are getting their own table. Create the table categories with the columns category_id (INTEGER PRIMARY KEY, the database assigns the number), name (text, required) and active (whole number, required, default 1). To check your table, the exercise then adds the categories from products (name only) and tries to save one category without a name and one without a value for active.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

How CREATE TABLE works

After CREATE TABLE comes the name of the new table, then the columns in parentheses, separated by commas. Each column has a name, a data type and optional rules. Purchasing wants to keep track of suppliers:

CREATE TABLE suppliers (
  supplier_id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  payment_days INTEGER NOT NULL DEFAULT 30
);
INSERT INTO suppliers (name, city) VALUES ('Northern Paper Mills', 'Albany');
INSERT INTO suppliers (name, city, payment_days) VALUES ('Fenwick Office Furniture', 'Birmingham', 14);
SELECT * FROM suppliers;
supplier_idnamecitypayment_days
1Northern Paper MillsAlbany30
2Fenwick Office FurnitureBirmingham14

The database handed out the IDs 1 and 2 on its own, because supplier_id is an INTEGER PRIMARY KEY. The first insert left out the payment terms, so DEFAULT 30 filled them in. A supplier without a name would have been rejected.

The rules you'll use most

RuleWhat it doesExample
NOT NULLrequired field, empty values are rejectedname TEXT NOT NULL
DEFAULTvalue used when the insert doesn't supply onestatus TEXT DEFAULT 'open'
PRIMARY KEYunique identifier for each rowcustomer_id INTEGER PRIMARY KEY
UNIQUEeach value may appear only onceemail TEXT UNIQUE
CHECKcondition every row must meetprice REAL CHECK (price >= 0)

One subtlety with CHECK: if the condition comes out as NULL because the value is missing, the SQLite and PostgreSQL docs both treat that as passing. When a value is mandatory, add NOT NULL as well. Primary and foreign keys get their own lesson: primary and foreign keys.

One more exercise: rules with CHECK

Task Marketing is planning discount campaigns. Create the table promotions: promotion_id (INTEGER PRIMARY KEY), product_id (whole number, required), discount (whole number, required, only 1 to 50 percent allowed) and status (text, required, default 'planned'). To check it, the exercise adds a 10 percent promotion for every product with more than 100 units in stock, then tries discounts of 0, 50 and 60 percent and one with no value.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Data types in MySQL, PostgreSQL, SQL Server and SQLite

Data types are where the databases differ the most. Here are the everyday cases:

ContentMySQLPostgreSQLSQL ServerSQLite
whole numberINTintegerintINTEGER
money amountDECIMAL(10,2)numeric(10,2)decimal(10,2)NUMERIC or REAL
textVARCHAR(100)varchar(100) or textnvarchar(100)TEXT
dateDATEdatedatetext as YYYY-MM-DD
yes/noBOOLEAN (same as TINYINT(1))booleanbitnumber 0 or 1
auto-numbered IDINT AUTO_INCREMENTGENERATED ALWAYS AS IDENTITYIDENTITY(1,1)INTEGER PRIMARY KEY

SQLite is relaxed about types. It has no separate date or yes/no type, and the type name you write only tells it how it should prefer to store values. VARCHAR(100) is treated like TEXT, and SQLite doesn't enforce the length. Strict type checking arrived with STRICT tables in version 3.37.0. In the other three databases the type decides what can be stored at all, so pick types and lengths with care.

IF NOT EXISTS: create it only if it's missing

If the table already exists, CREATE TABLE stops with an error. With CREATE TABLE IF NOT EXISTS suppliers (...) nothing happens instead, which is handy for scripts that run more than once. The catch: the existing table isn't compared with your definition. If it has different columns, it stays exactly as it was.

A table from a query: CREATE TABLE … AS SELECT

Instead of listing columns, you can build a table straight from a query result. The columns take their names from the SELECT:

CREATE TABLE out_of_stock AS
SELECT product_id, name, price
FROM products
WHERE stock = 0;
SELECT * FROM out_of_stock;
product_idnameprice
7Yellow sticky notes, 12 pads6.99
12Cross-cut shredder129.0

What you get is a snapshot: once the warehouse restocks, the new table doesn't change. In SQLite it also has no primary key and no rules at all. If you want something that always reflects the current data, a view is the right tool.

Task Accounting wants to keep a fixed snapshot of the cancelled orders. Use CREATE TABLE … AS SELECT to create the table cancelled_orders with the columns order_id, customer_id, order_date and order_value (the sum of quantity times unit_price over all items) for every order with the status cancelled.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 39 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9
1013253.49

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

A comma after the last column

active INTEGER NOT NULL DEFAULT 1,) fails because the comma promises another column. The exercise reports “Syntax error near ")"”. The last column is followed only by the closing parenthesis.

A required column with no default

If active has NOT NULL but no DEFAULT, every insert that leaves active out fails. The exercise then says “categories.active must not be empty (NOT NULL)”. In this case it means: the test inserts don't supply a value, so the column needs a default.

The table already exists

Creating customers a second time gives you “customers already exists. Use another name or write IF NOT EXISTS.” To change an existing table, use ALTER TABLE.

INT instead of INTEGER for the ID

In SQLite only the exact spelling INTEGER PRIMARY KEY counts up by itself. With INT PRIMARY KEY the ID stays empty when the insert leaves it out, and the exercise tells you that not all values match.

Default text in double quotes

SQLite lets DEFAULT "planned" through, but PostgreSQL and SQL Server read double quotes as a column name. The exercise flags it: text goes in single quotes, DEFAULT 'planned'.

And how do I create a database?

In MySQL, PostgreSQL and SQL Server, CREATE DATABASE shop; creates an empty database, and you then create the tables inside it. MySQL accepts IF NOT EXISTS there, PostgreSQL doesn't. SQLite has no CREATE DATABASE: a complete database with all its tables lives in a single file.

CREATE TABLE in MySQL, PostgreSQL, SQL Server and SQLite

DatabaseIF NOT EXISTSTable from a queryCHECK enforced
MySQLyesCREATE TABLE new AS SELECT … (AS is optional)since 8.0.16, ignored before
PostgreSQLyes, with a notice instead of an errorCREATE TABLE new AS SELECT …yes
SQL Servernot part of the CREATE TABLE syntaxSELECT … INTO new FROM …yes
SQLite (these exercises)yesCREATE TABLE new AS SELECT …yes

SQL Server's SELECT … INTO doesn't carry over indexes or constraints from the source table either.

Sources: MySQL Reference Manual (CREATE TABLE, CHECK Constraints, Numeric Type Syntax, CREATE DATABASE), PostgreSQL documentation (CREATE TABLE, Data Types, Constraints, CREATE DATABASE), Microsoft Learn (CREATE TABLE, Data types, SELECT INTO, CREATE DATABASE), sqlite.org (CREATE TABLE, Datatypes, FAQ, About, Release History 3.37.0).

Frequently asked questions

How do I delete a table?

With DROP TABLE suppliers;. The table and all its data are gone, with no confirmation prompt. In the exercises that's harmless because every run starts from fresh data. On a real database, double-check what you're dropping first.

Can I add columns later?

Yes, with ALTER TABLE ... ADD COLUMN, which is the next lesson. You don't have to know every column on day one.

Why are dates stored as text in the exercises?

SQLite has no date type of its own. Its date functions work with text in the form YYYY-MM-DD, and in that form dates also sort and compare correctly as text.

How should I name tables and columns?

Lowercase, no spaces, words joined with underscores: customer_since rather than “Customer Since”. Then you never need quotes around names, and your queries run on any database.

Up next: ALTER TABLE

Tables rarely stay the way they were first built. ALTER TABLE lets you add a column, rename one or drop it.

Practice ALTER TABLE

Write to us

Choose language

Select your preferred language