Learn how to use MySQL CREATE DATABASE and CREATE TABLE statements to create and structure a database. In this tutorial, you'll learn the syntax and options available for the statements and how to use them to create a new database and tables. With clear explanations and plenty of examples, you'll be confidently creating and organizing your MySQL databases.



MySQL CREATE DATABASE Statement

The MySQL CREATE DATABASE statement is used to create a new database in the MySQL server. Here is the basic syntax of the CREATE DATABASE statement:

Syntax:

CREATE DATABASE database_name;

To create a new database using the CREATE DATABASE statement, you must specify the database name you want to create. For example, to create a database named mydatabase, you would use the following CREATE DATABASE statement:

Example:

CREATE DATABASE mydatabase;

You can also specify additional options when creating a database. For example, you can specify the default character set and collation for the database using the DEFAULT CHARACTER SET and DEFAULT COLLATE options, respectively. Here is an example of a CREATE DATABASE statement that specifies both the default character set and collation:

Example:

CREATE DATABASE mydatabase DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci;

MySQL CREATE TABLE Statement

Once you have created a database, you can create tables and insert data using SQL statements. To create a new table in the database, you can use the CREATE TABLE statement.

Example:

CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255),
  email VARCHAR(255)
);

This CREATE TABLE statement creates a table named users with three columns: id, name, and email. The id column is an integer that is set as the primary key and has the AUTO_INCREMENT attribute, which means that it will automatically increment whenever a new row is inserted into the table. The name and email columns are both VARCHAR columns with a maximum length of 255 characters. To insert data into the users table, you can use the INSERT INTO statement. For example:

INSERT INTO users (name, email) VALUES ('Alex', '[email protected]');

The above MySQL INSERT INTO statement inserts a new row into the users table with the values 'Alex' and '[email protected]' for the name and email columns, respectively.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram