We use cookies to enhance your experience on the site
CodeWorlds

CREATE TABLE - building a new shelf

The most important command of the scriptorium is CREATE TABLE. It creates a new, empty shelf ready to receive scrolls.

Basic syntax

1CREATE TABLE table_name (
2  column1 TYPE,
3  column2 TYPE,
4  column3 TYPE
5);

We read it like this: "Build a shelf named table_name, and in it the fields: column1, column2, column3". Each field has its name and its type.

Writing rules

  • After the table name we open a round parenthesis
    (
    .
  • Inside we list the columns, each on a new line for readability.
  • We separate column definitions with commas - but we do NOT put a comma after the last one.
  • We close the parenthesis
    )
    and end the whole thing with a semicolon ";".

Definition of a single column

In a column definition we first write the name, and right after it the data type:

1tytul VARCHAR(255)

This means: "the tytul field accepts text up to 255 characters". The order is always this: NAME, then TYPE.

Example: a simple kategorie shelf

1CREATE TABLE kategorie (
2  id INT,
3  nazwa VARCHAR(100)
4);

A shelf

kategorie
was created with two fields:
id
for numbers and
nazwa
for short text. It is still empty - but the plan is ready!

Does the table name matter?

Very much! A table name is the address of the shelf in the Library. You will later use it to retrieve data (

SELECT * FROM kategorie
), add columns or drop the whole shelf. Good names are short, plural (
ksiazki
,
autorzy
,
czytelnicy
) and describe the kind of scrolls stored. We avoid spaces and special characters - instead we use underscores, e.g.
rok_wydania
.

Remember three things

  1. Parentheses
    ( )
    enclose the list of columns - without them MySQL reports an error.
  2. Commas separate the columns, but there is none after the last one.
  3. A semicolon ";" ends the whole statement.

When these three elements are in place, the shelf is built in the blink of an eye!

Go to CodeWorlds