An SQL statement is one complete instruction you give to MySQL: “create this table”, “add this row”, “show me these rows”.
SELECT 'one statement' AS example;
+---------------+
| example |
+---------------+
| one statement |
+---------------+
1 row in set
The parts of a statement
Most statements follow the same pattern: a command word, then what it applies to, then optional clauses that refine it.
CREATE TABLE tags (id INT PRIMARY KEY, label VARCHAR(30));
INSERT INTO tags (id, label) VALUES (1, 'sql');
SELECT id, label FROM tags WHERE id = 1;
+----+-------+
| id | label |
+----+-------+
| 1 | sql |
+----+-------+
1 row in set
| Piece | Example | Job |
|---|---|---|
| Command (verb) | SELECT | What to do |
| Object | tags | Which table (or other object) |
| Clause | WHERE id = 1 | A condition, an order, a limit and so on |
| Terminator | ; | Ends the statement |
The semicolon
The semicolon tells the client where one statement ends. It is not part of the statement the server runs. This matters because:
- You can put several statements on one line or many lines, and the client splits them at each
;. - A statement without a semicolon is simply “not finished yet” in the
mysqlclient. - Some programming languages send one statement per call and do not want the semicolon at all. Others accept several. Your language’s documentation will say.
SELECT 1 AS a;
SELECT 2 AS b;
+---+
| a |
+---+
| 1 |
+---+
1 row in set
+---+
| b |
+---+
| 2 |
+---+
1 row in set
Each statement produced its own result.
Statements spread over lines
SQL ignores extra spaces and line breaks. These two statements are identical to MySQL:
SELECT name,price FROM (SELECT 'Pen' AS name, 10 AS price) AS t WHERE price>5;
SELECT name,
price
FROM (SELECT 'Pen' AS name, 10 AS price) AS t
WHERE price > 5;
+------+-------+
| name | price |
+------+-------+
| Pen | 10 |
+------+-------+
1 row in set
+------+-------+
| name | price |
+------+-------+
| Pen | 10 |
+------+-------+
1 row in set
Use the second style. One clause per line makes SQL much easier to read, review and debug.
Statements you will see in this course
| Kind | Examples |
|---|---|
| Reading data | SELECT |
| Changing data | INSERT, UPDATE, DELETE, REPLACE |
| Changing structure | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| Access control | CREATE USER, GRANT, REVOKE |
| Transactions | START TRANSACTION, COMMIT, ROLLBACK |
| Information | SHOW, DESCRIBE, EXPLAIN |
MySQL-specific statements
SHOW, DESCRIBE, USE and REPLACE are MySQL statements. They are not part of standard SQL. The standard way to look at structure is the INFORMATION_SCHEMA views, which MySQL also supports.