Creating a Table
The database is open and empty. Now you describe the shape of the data you are going to keep — the columns, and what each one holds. This is the single most important query in the chapter, because everything later depends on getting the structure right.
1The syntax
create table <table name> (
<column1> <data type>,
<column2> <data type>,
...
<columnN> <data type>);A name, then a bracket, then one line per column: its name followed by its data type. Commas between them, and the closing bracket and semicolon at the end.
2Building the students table
Here is the table this whole course uses, being made. Remember the columns can be spread over several lines — nothing runs until the semicolon.
0 rows affected is correct and not a problem. You created a structure, not data — the table exists and has no rows in it yet. primary key on the id line is the rule from the keys lesson, written down at last; the next lesson takes that and the other constraints properly.
3Reading the structure back
Before putting a single row in, check that the table you built is the table you meant. desc — short for describe, and both work — shows the structure:
Reading the six headings across:
The column's name.
Its data type, with the length you asked for.
YES means the column may be left empty. NO means a value is compulsory — which is why the primary key says NO.
PRI marks the primary key. UNI and MUL appear once other constraints are used.
What goes in when you do not supply a value. NULL unless you set one.
Anything unusual about the column. Empty for everything in this course.
Notice what MySQL worked out for itself: id has Null: NO and Key: PRI because you said primary key, and a primary key can never be NULL. You wrote one thing; two facts followed.
4Two mistakes worth meeting now
The first is creating a table before choosing a database. MySQL has no idea where to put it:
The cure is use lambdalab; first, not a change to the query.
The second is a typo in a table name, which shows up later:
The table is called students. The error even prints the name it looked for, lambdalab.student, which tells you both the database it searched and the exact spelling it used.
5Recap
Builds the structure. Replies Query OK, 0 rows affected.
Lists the tables in the open database.
Shows the columns, types, and which is the key.
No database selected — you forgot use.
create table replies 'Query OK, 0 rows affected'. Did it work?
desc students; returns 6 rows for a table holding 40 students. What are those 6 rows?
Which is NOT a valid way to see a table's structure?