SQL / MySQL Beginner Relational Design · 8 min read

CREATE TABLE with Keys, NOT NULL, UNIQUE, and Defaults

Lesson 2 of 33 in the SQL / MySQL learning path.

How do I create a table with the right data types and constraints?

The slug sql-create-users is the historical name of this lesson, and the table stays users so the address still matches a create-users topic. In the school database each student is a user account: the row holds the sign-in identity, while courses and enrollments arrive in later lessons. Naming the table users, and describing the people as students, keeps the older example and the enrollment story in the same schema.

The script creates users with an integer primary key, a required name, a unique email, a password hash, and created_at defaulting to the current timestamp. It also creates courses so the registrar has a home for class records. PRIMARY KEY, NOT NULL, UNIQUE, and DEFAULT are the constraints that keep those rows trustworthy. VARCHAR fits short bounded text such as email. TEXT is for a long syllabus you will not use as a key.

Syntax & Parameters

Syntax
CREATE TABLE table_name (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  column_name VARCHAR(120) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_table_column (column_name)
) ENGINE=InnoDB;

Example

schema.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

SET NAMES utf8mb4;

DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS courses;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE courses (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  code VARCHAR(16) NOT NULL,
  title VARCHAR(160) NOT NULL,
  seats SMALLINT UNSIGNED NOT NULL DEFAULT 30,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_courses_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, password_hash)
VALUES ('Ada Lovelace', 'ada@school.test', 'sample-hash-not-a-secret');

INSERT INTO users (name, email, password_hash, created_at)
VALUES ('Grace Hopper', 'grace@school.test', 'sample-hash-not-a-secret', '2026-02-11 09:30:00');

INSERT INTO courses (code, title)
VALUES ('CS101', 'Intro to Databases');

INSERT INTO courses (code, title, seats, created_at)
VALUES ('CS220', 'Relational Design', 24, '2026-02-11 10:00:00');

SELECT id, name, email, created_at
FROM users
ORDER BY id;

SELECT id, code, title, seats, created_at
FROM courses
ORDER BY id;

Expected Output

users
id | name          | email              | created_at
1  | Ada Lovelace  | ada@school.test    | (the timestamp of the INSERT, from DEFAULT CURRENT_TIMESTAMP)
2  | Grace Hopper  | grace@school.test  | 2026-02-11 09:30:00
2 rows in set

courses
id | code  | title              | seats | created_at
1  | CS101 | Intro to Databases | 30    | (the timestamp of the INSERT, from DEFAULT CURRENT_TIMESTAMP)
2  | CS220 | Relational Design  | 24    | 2026-02-11 10:00:00
2 rows in set

Line-by-Line Walkthrough

  1. CREATE DATABASE IF NOT EXISTS school prepares the registrar database, and USE school plus SET NAMES utf8mb4 point this session at it.
  2. DROP TABLE clears enrollments, courses, and users in child-to-parent order so the practice script can be repeated.
  3. id is an unsigned integer, AUTO_INCREMENT, and the PRIMARY KEY, so each user and each course gets a stable number that later enrollments can reference.
  4. NOT NULL on name, email, and password_hash rejects a user row that is missing its identity or its secret hash.
  5. UNIQUE KEY uq_users_email (email) rejects a second account with the same email, and MySQL also uses that index for lookups.
  6. created_at is DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, so an INSERT that omits the column still stores the time of the write.
  7. The Ada insert omits created_at and receives the default. The Grace insert sets 2026-02-11 09:30:00 explicitly, which is why the two timestamps differ.
  8. password_hash is VARCHAR(255) because it stores the string produced by the application hash function, and the sample value is a stand-in hash, not a password.
  9. VARCHAR(254) matches a bounded email. TEXT would fit a long course description, and a full TEXT value is a poor primary or unique key because indexing it needs a prefix.
  10. courses uses the same key pattern, and seats is NOT NULL DEFAULT 30, so CS101 receives 30 seats when the INSERT names only code and title.

Common Pitfalls & Security

A table can be created and still be unsafe to write. Strict mode rejects a missing NOT NULL value, a duplicate email raises error 1062, and a hash column that receives the raw password becomes a credential leak. Practice inserts below use a stand-in hash string. Application code should store only the result of its password hash function.

  • Inserting ada@school.test a second time fails with duplicate-key error 1062 because UNIQUE KEY uq_users_email already holds that address.
  • Leaving out DEFAULT on a NOT NULL created_at column forces every INSERT to supply a timestamp. The default is what makes the Ada insert valid.
  • VARCHAR(120) silently truncates or rejects a longer name depending on SQL mode. Pick the length from the real limit, and use TEXT for a syllabus that can run to thousands of characters.
  • The unique email index treats Ada@school.test and ada@school.test as the same value under utf8mb4_unicode_ci. Store a canonical form if the registrar must keep those addresses distinct.
  • An UPDATE or DELETE that omits WHERE rewrites or removes every student. That is a catastrophe. This lesson only inserts, and any later change needs a WHERE on id or email.
  • DROP TABLE users deletes every account and cannot be filtered with WHERE. Run it on the practice copy of school, after enrollments has been dropped.

Best Practices & Modern Standards

Declare the primary key, the unique email, the NOT NULL columns, and the timestamp default in CREATE TABLE, so bad rows fail on the first insert. Use INT UNSIGNED for the ids in users, courses, and enrollments so every later foreign key matches the parent type exactly. Keep password_hash long enough for the application hash, and never put the typed password in that column.

Add a column when you know its rule. A status flag added in the next lesson needs a default so existing students stay valid. The PHP side of a user insert, including bound parameters, is covered by php-pdo-insert. This SQL script uses literal values so you can run it in the mysql client.

Real-World Use

In a school enrollment schema the users table is the student account: one row per person, with a unique email and a created_at time for when they registered. The courses table holds each class the school offers, including a seat count. Enrollments, added in the join and foreign-key lessons, will point at these two integer keys. Getting users and courses right means a later registration row has a real student and a real course to reference.

Frequently Asked Questions

Why is the table called users when the lesson is about students?

The slug sql-create-users is the older name for this page, so the teaching table is users and the URL still matches. In this school schema a student is that user account. Courses and enrollments reference users.id.

Why use VARCHAR for email instead of TEXT?

An email has a small maximum length, so VARCHAR(254) stores it and the UNIQUE key can index the whole value. TEXT is for long text such as a syllabus. Indexing TEXT requires a prefix and makes a poor stand-in for an email key.

What happens if two students share an email?

The second INSERT fails with error 1062 because uq_users_email is a UNIQUE key. The first row stays. The application should show a clear message and ask for a different address.

Does DEFAULT CURRENT_TIMESTAMP store the time zone?

DATETIME stores the clock time you give it and does not convert time zones. CURRENT_TIMESTAMP uses the time of the MySQL session. Set the session time zone deliberately if the school reports dates in a known zone.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…