Node.js MySQL Create Table
🚀 Node.js MySQL – Create Table
To create a table from Node.js, you must:
-
Connect to the MySQL database
-
Run a
CREATE TABLESQL query
We will use the mysql2 package.
✅ 1. 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
🎉 Expected Output
📌 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 |
