How to Create a Table in MySQL

Creating tables is one of the most fundamental tasks when working with MySQL databases. In this tutorial, we will walk through the process step by step, so you can confidently set up your own tables.

1. Connect to MySQL

First, log in to your MySQL server using the command line:

mysql -u root -p

After entering your password, you will be inside the MySQL shell.

2. Choose the Database

Select the database where you want to create your table:

USE my_database;

3. Write the CREATE TABLE Statement

Here’s a basic example of a CREATE TABLE statement:

CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100) UNIQUE,
    hire_date DATE
);
  • id: A unique identifier for each employee.
  • first_name and last_name: Store employee names.
  • email: Must be unique for each employee.
  • hire_date: The date the employee was hired.

4. Execute the Statement

Run the SQL statement inside your MySQL shell:

mysql> CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100) UNIQUE,
    hire_date DATE
);

If successful, you will see:

Query OK, 0 rows affected

5. Verify the Table

Check that your table was created:

SHOW TABLES;
DESCRIBE employees;

This will list your tables and show the structure of the employees table.

6. Tips and Best Practices

  • Always define a primary key.
  • Use appropriate data types for each column.
  • Add NOT NULL where values must be required.
  • Use UNIQUE for fields like email to avoid duplicates.
  • Consider indexing columns used in WHERE clauses for better performance.

Conclusion

Creating tables in MySQL is a foundational skill. Once you understand the syntax, you can build more complex schemas to fit your application’s needs. Practice writing CREATE TABLE statements with different columns and constraints to strengthen your SQL skills!