CREATE TABLE: Your First Table
A Cassandra table holds rows and columns, like a table in any other database. You create one with CREATE TABLE.
Syntax
CREATE TABLE table_name (
column1 type1,
column2 type2,
...
PRIMARY KEY (column1)
);
Each column has a name and a type. The type says what kind of value the column holds.
Example: a table of users
CREATE TABLE users (
id int PRIMARY KEY,
name text,
email text
);
This creates a users table with three columns. int holds whole numbers, and text holds text. You will meet more types in the next lesson.
The new table has no rows yet. When you read it, you see only the column names:
SELECT * FROM users;
Output:
id | email | name
----+-------+------
(0 rows)
Look at the column order. SELECT * shows the primary key column first. The other columns follow in alphabetical order, so email comes before name. That is also why employees showed age, department, gender, name.
Every table needs a primary key
The primary key is the column that identifies each row. In Cassandra, every table must have one. It also decides on which node each row is stored, so Cassandra can't work without it. Try to create a table without a primary key, and you get an error:
CREATE TABLE notes (
id int,
body text
);
Output:
InvalidRequest: Error from server: code=2200 [Invalid query] message="No PRIMARY KEY specifed for table 'notes' (exactly one required)"
The message says that exactly one primary key is required. (The spelling mistake "specifed" is in Cassandra's own message.)
For a key with one column, you can write PRIMARY KEY next to the column, as in users. Or you can write it at the end:
CREATE TABLE cities (
id int,
name text,
country text,
PRIMARY KEY (id)
);
Both forms do the same thing. In the Primary Keys section, you will see keys made of more than one column.
Comments
The exercises in this course use comments to explain the task. CQL has three kinds of comments:
-- a comment on one line
// also a comment on one line
/* a comment that
spans many lines */
Now create a table of your own. The exercise below tells you which columns it needs.