Database Management
- How to Add an Index
- How to Create a Table
- How to Delete a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Remove a Column
- How to Change a Column Name
- How to Set a Column with Default Value
- How to Remove a Default Value to a Column
- How to Add a Not Null Constraint
- How to Remove a Not Null Constraint
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Alter Sequence
Dates and Times
Analysis
- How to Use Coalesce
- How to Calculate Percentiles
- How to Get the First Row per Group
- How to Avoid Gaps in Data
- How to Do Type Casting
- How to Write a Common Table Expression
- How to Import a CSV
- How to Compare Two Values When One is Null
- How to Write a Case Statement
- How to Query a JSON Column
- How to Have Multiple Counts
- How to Calculate Cumulative Sum-Running Total
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
andlast_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!