A database holds your tables, and a table holds your rows. You create a database with CREATE DATABASE, choose it with USE, and then define each table with CREATE TABLE: its columns, their data types and any constraints such as PRIMARY KEY or NOT NULL.
CREATE DATABASE database_name;
USE database_name;
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints
);
Do these in order. Each question uses what the one before it created or changed.
How to use this page: read a question, write your own query, then open "Show the answer" and compare. Trying first is what makes it stick.
Question 1Write a query to create a database named "store".
Show the answer and the output
CREATE DATABASE store;
USE store;Output
Query OK.
Then check with SHOW DATABASES LIKE 'store'
| Database (store) |
|---|
| store |
To create a table inside the database, first select it with USE.
Question 2Create a table named "orderDemo" in the "store" database with 5 columns: id (integer, primary key), product_name (string, not null), order_date (date), price (decimal, not null) and quantity (integer).
Show the answer and the output
CREATE TABLE orderDemo (
id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
order_date DATE,
price DECIMAL(10,2) NOT NULL,
quantity INT
);Output
Query OK.
Then check with DESCRIBE orderDemo
| Field | Type | Null | Key | Default | Extra |
|---|---|---|---|---|---|
| id | int(11) | NO | PRI | NULL | |
| product_name | varchar(50) | NO | NULL | ||
| order_date | date | YES | NULL | ||
| price | decimal(10,2) | NO | NULL | ||
| quantity | int(11) | YES | NULL |
Question 3Create a new table named "orderDetail" that is an exact copy of the "orderDemo" table.
Show the answer and the output
CREATE TABLE orderDetail LIKE orderDemo;Output
Query OK.
Then check with DESCRIBE orderDetail
| Field | Type | Null | Key | Default | Extra |
|---|---|---|---|---|---|
| id | int(11) | NO | PRI | NULL | |
| product_name | varchar(50) | NO | NULL | ||
| order_date | date | YES | NULL | ||
| price | decimal(10,2) | NO | NULL | ||
| quantity | int(11) | YES | NULL |
CREATE TABLE ... LIKE copies the structure exactly, including the primary key. The other common way, CREATE TABLE orderDetail AS SELECT * FROM orderDemo;, copies the columns and the data, but not the primary key or other constraints.
Different from the PDF: The PDF used CREATE TABLE ... AS SELECT, which does not keep the primary key, so it is not an exact copy. LIKE is used here.
Question 4Delete the "orderDemo" table.
Show the answer and the output
DROP TABLE orderDemo;Output
Query OK.
Then check with SHOW TABLES
| Tables_in_store |
|---|
| orderDetail |
DROP TABLE removes the table and all its data permanently.
Want these as PDFs? Download the question PDF or the answer PDF to practise offline.
