Sunday, December 29, 2024

How do you create multiple tables on one database in MySQL?

 In MySQL, you can create multiple tables in one database by using the CREATE TABLE statement for each table you wish to create. Here is the general syntax to create multiple tables within the same database:

  1. Ensure you're using the correct database: Before creating tables, you need to make sure you're using the database where you want to create them. You can switch to your desired database with:

    USE your_database_name;
    
  2. Create each table: You can create multiple tables by executing a separate CREATE TABLE statement for each one. Here's an example:

    CREATE TABLE table1 (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(100),
        age INT
    );
    
    CREATE TABLE table2 (
        id INT PRIMARY KEY AUTO_INCREMENT,
        description TEXT,
        price DECIMAL(10, 2)
    );
    
    CREATE TABLE table3 (
        id INT PRIMARY KEY AUTO_INCREMENT,
        title VARCHAR(100),
        published_date DATE
    );
    

In this example:

  • table1 has columns for an id, name, and age.
  • table2 has columns for id, description, and price.
  • table3 has columns for id, title, and published_date.
  1. Execute all the queries: Run these queries sequentially in your MySQL client or script to create multiple tables in your chosen database.

If you're creating these tables programmatically (e.g., from an application), you can execute multiple CREATE TABLE statements one after the other in your database connection.

No comments:

Post a Comment