How to Create a Database Table and Define Its Rules
In this article
Creating a database table is the first step in structuring your data for storage and retrieval. This guide walks you through the process of defining a table, setting column types, and applying constraints—the rules that keep your data valid and consistent. You'll learn the standard SQL syntax that works across most relational databases (MySQL, PostgreSQL, SQLite, SQL Server), plus practical tips for avoiding common pitfalls.
What You'll Need
- Access to a database system (e.g., MySQL, PostgreSQL, SQLite, or SQL Server) with permission to create tables.
- A database already created (e.g.,
CREATE DATABASE mydb;). - A text editor or database client (like pgAdmin, MySQL Workbench, or the command line).
- Basic understanding of SQL syntax—though this guide explains each step.
Step-by-Step
- Choose a table name. Use a singular, descriptive name like
customerororder_item. Avoid reserved words (e.g.,useris problematic in some databases—useapp_userinstead). Stick to lowercase letters, numbers, and underscores. - Decide on a primary key. Every table should have a way to uniquely identify each row. Common choices are an auto-incrementing integer (
id INT AUTO_INCREMENT PRIMARY KEYin MySQL,SERIAL PRIMARY KEYin PostgreSQL) or a UUID. This column will be the reference point for other tables. - List all the columns you need. Think about what data you're storing. For a
customertable, you might needfirst_name,last_name,email,created_at. Write them down before writing SQL. - Define each column's data type. Specify the type that best fits the data:
VARCHAR(255)for short text,TEXTfor long text,INTfor whole numbers,DECIMAL(10,2)for money,DATEfor dates,TIMESTAMPfor date and time. Be precise—VARCHAR(3)will reject a four-letter name. - Add constraints to enforce rules. Constraints are the "rules" of the table. Common ones:
NOT NULL– the column must have a value.UNIQUE– no two rows can have the same value (e.g., email).DEFAULT– a default value if none is provided (e.g.,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP).CHECK– a condition that must be true (e.g.,CHECK (age >= 18)).FOREIGN KEY– links to a primary key in another table, ensuring referential integrity.
- Write the CREATE TABLE statement. Use the syntax:
CREATE TABLE customer ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, age INT CHECK (age >= 0), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );Adjust the data types and constraints to your needs. - Execute the statement. Run the SQL in your database client. If successful, you'll get a confirmation. You can verify with
DESCRIBE customer;(MySQL) or\d customer(PostgreSQL) to see the table structure. - Test with sample data. Insert a few rows to confirm the constraints work:
INSERT INTO customer (first_name, last_name, email, age) VALUES ('Jane', 'Doe', 'jane@example.com', 25);Try inserting a duplicate email or a NULL first name to see the errors—this proves your rules are enforced.
Common Mistakes
- Using the wrong data type. Storing phone numbers as
INTloses leading zeros; useVARCHARfor anything you won't do math on. - Forgetting NOT NULL on required fields. If a column is optional, leave it nullable; otherwise, always add
NOT NULL. - Making the primary key a natural column. Using email as a primary key can fail if emails change. Use a surrogate key (auto-increment ID).
- Overusing TEXT for short strings.
TEXTcan be less efficient and lacks a length limit. UseVARCHARwith a sensible max length. - Ignoring foreign key constraints. Without them, you can end up with orphaned records that reference non-existent rows.
Tips
- Plan before you code. Sketch the table on paper or in a diagram tool. It's cheaper to change a plan than a live table.
- Use consistent naming. Pick a convention (snake_case, singular names) and stick to it across all tables.
- Add an
updated_atcolumn. UseTIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(MySQL) or a trigger (PostgreSQL) to track changes. - Start with a migration script. Save your
CREATE TABLESQL in a version-controlled file. This lets you recreate the schema and track changes. - Consider indexes. Add indexes on columns you'll query often (e.g.,
email) to speed up lookups. Primary keys and unique constraints already create indexes.
Troubleshooting
- Syntax errors. Check for missing commas, parentheses, or semicolons. Use your database's documentation for exact syntax—MySQL and PostgreSQL differ slightly.
- "Table already exists" error. If you're re-running a script, add
DROP TABLE IF EXISTS customer;before theCREATE TABLE(but be careful—this deletes data). - "Duplicate column name" error. You've listed a column twice. Review your column list.
- "Invalid use of NULL value" on insert. A column with
NOT NULLis missing a value. Check your INSERT statement. - Foreign key constraint fails. The referenced row doesn't exist in the parent table. Insert the parent row first, or check the data.
- Can't drop a table that other tables reference. Drop the child tables first, or use
CASCADE(e.g.,DROP TABLE customer CASCADE;in PostgreSQL) to automatically drop dependent constraints.
Frequently Asked Questions
What is the difference between CHAR and VARCHAR?
CHAR(n) always stores exactly n characters, padding with spaces. VARCHAR(n) stores up to n characters but uses only as much space as needed. Use VARCHAR for variable-length data like names.
Can I change a table after it's created?
Yes, use ALTER TABLE. For example, to add a column: ALTER TABLE customer ADD COLUMN phone VARCHAR(20);. You can also modify data types or drop columns, but be careful with existing data.
What is a composite primary key?
A primary key made of two or more columns. For example, in an order_item table, the combination of order_id and product_id uniquely identifies a row. Define it with PRIMARY KEY (order_id, product_id).
Should I use an auto-increment ID or a UUID?
Auto-increment IDs are simple and fast, but they can reveal the number of rows and are hard to merge across databases. UUIDs are globally unique and don't expose counts, but they take more space and are slower to index. Choose based on your scale and privacy needs.
How do I delete a table?
Use DROP TABLE table_name;. This permanently removes the table and its data. To remove only the data but keep the table, use TRUNCATE TABLE table_name; (or DELETE FROM table_name; without a WHERE clause).
What does ON DELETE CASCADE do?
When a foreign key is defined with ON DELETE CASCADE, deleting a row in the parent table automatically deletes all child rows referencing it. This is useful for dependent data but can cause unintended mass deletions—use it carefully.