Now that we know about data types from the previous blog, let’s go over using that to create tables. Once in a while, either when we’re creating a new database or updating one, we may want to create a table to hold new data. Luckily, the basic syntax to create a table in MySQL isn’t too hard.
Creating The Table
The syntax starts with the CREATE TABLE keywords, followed by a unique table name and then the column names and constraints in parentheses:
If we were to get specific, a column definition looks like the following, where the keywords in brackets are optional:
Column constraints can be a restriction such as UNIQUE so that values in a column are all different from each other.
Inserting Values
Once we’ve created he table layout, we should also know how to insert values into them. The syntax for this is shown below:
This inserts a value of val1 under the first column (col1), and val2 under the second column (col2), and so on. Although this adds only one row, we can add more than one row by separating each row with a comma and enclosing each row with parentheses:
Creating a Sample Table
Now let’s try to create a sample table called STUDENTS that looks like one we’ve seen before:
The column names are ID, Name, and Marks with data types of INT, STRING, and INT respectively. And the values are (1, Ashley, 81), (2, Samantha, 75), (4, Julia, 76), and (3, Belvet, 84).
First we’ll set up the table using what we know:
This will designate what data types can be input into the table for each column. We then need to insert the values as we were told:
And there you have it! We’ve created a table and inserted values into it!
Resources: