How to create a table in SQL.
How to create a table in SQL starts with choosing its columns, their data types, and the rules each row must follow.

Loading the lesson…
Loading activities…
How to create a table in SQL starts with choosing its columns, their data types, and the rules each row must follow.

Loading the lesson…
Loading activities…
You know how to query data that's already sitting there. Now it's time to build the tables that hold it. Making a table is a lot like designing a form. You decide what info to collect, what format it should come in and which fields somebody HAS to fill out.
Here's the basic shape of creating a table.
Let's walk through it.
CREATE TABLE users makes a brand new table named "users"Every column needs a data type, which tells the database what kind of data to expect in it.
| Data Type | What It Stores | Example Values |
|---|---|---|
INTEGER | Whole numbers | 1, 42, -7, 1000000 |
TEXT | Strings of any length | 'Hello', 'alice@example.com' |
BOOLEAN | True or false | TRUE, FALSE |
TIMESTAMP | Date and time | '2024-01-15 09:30:00' |
DECIMAL | Precise numbers | 19.99, 3.14159 |
VARCHAR(n) | Text with a max length | VARCHAR(255) for short strings |
Constraints are rules that keep your data clean and consistent. I grew up working construction with my dad, and his rule was "do it right or don't do it at all." Constraints are that rule written into your database... the table flat out refuses sloppy data.
Every table needs a primary key, which is a column that uniquely identifies each row.
The id column holds a unique value for every product. Two products can never share the same ID.
Requires a value other than NULL. An empty text string still passes NOT NULL, so validate blank names in your app or add a separate database check.
Makes sure no two rows have the same value in that column.
Fills in a value automatically when you don't give it one.
In PostgreSQL you can use SERIAL or GENERATED ALWAYS AS IDENTITY to hand out unique IDs automatically.
Now you don't have to pass in the id when you insert something. The database takes care of it for you.
Let's design a table for a blog app.
Here's what that table gives you.
Made a mistake, or need to add a column later on? That's what ALTER TABLE is for.
This one removes a table completely (careful, it deletes ALL the data inside it too).
CREATE TABLE defines a new table along with its columns and their data typesYou've built tables and laid out their structure. Next up you'll fill them with data using INSERT, change existing data with UPDATE and remove data with DELETE. Those three (plus SELECT) are the core of pretty much everything you'll ever do with a database.