Node.js MySQL Create Table

🚀 Node.js MySQL – Create Table

To create a table from Node.js, you must:

  1. Connect to the MySQL database

  2. Run a CREATE TABLE SQL query

We will use the mysql2 package.


1. Install mysql2

npm install mysql2

2. Create a Connection to Your Database

Example: Connecting to database mydb


 


3. Create a Table Using Node.js

create_table.js


 


📝 4. Run the File

node create_table.js

🎉 Expected Output

Connected to MySQL!
Table 'users' created successfully!

📌 5. Create Table Only If Not Exists

Avoids errors if table already exists:



 


📌 6. Example: Create Multiple Tables



 

You can run multiple queries using connection.query() or by using mysql2 pool.


⚠️ Tips & Best Practices

Best Practice Why
Use IF NOT EXISTS Prevents errors during re-run
Use AUTO_INCREMENT primary keys Unique identifiers
Use TIMESTAMP for created_at Track creation time
Use VARCHAR carefully Optimize column size

You may also like...