- SQL Statement Classes
- Common CLI commands
- CREATE TABLE …
- ALTER TABLE … MODIFY …
- DROP TABLE
- INSERT INTO … VALUES …
- UPDATE … SET … WHERE …
- DELETE … FROM … WHERE
- When Good Statements Go Bad
- SELECT … FROM … WHERE
SQL Statement Classes
- SQL schema statements — used to define the data structures stored in the database. Ex: create table.
- SQL data statements — used to manipulate the data structures previously defined using SQL schema statements. Ex: insert, update, delete, and select.
- SQL transaction statements — used to begin, end, and roll back transactions.
SELECT /* one or more things */ ...
FROM /* one or more places */ ...
WHERE /* one or more conditions apply */ ...Common CLI commands
show character set;
show databases;
use <DATABASE>; # OR mysql -u <USER> -p <DATABASE>;
show tables;
desc <TABLE>;SELECT now(); # 2019-04-04 20:44:26CREATE TABLE …
ALTER TABLE … MODIFY …
set foreign_key_checks=0; # disable the foreign key constraint on the favorite_food
ALTER TABLE person
MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
set foreign_key_checks=1;DROP TABLE
DROP TABLE favorite_food;INSERT INTO … VALUES …
INSERT INTO person
(person_id, fname, lname, eye_color, birth_date)
VALUES (null, 'William','Turner', 'BR', '1972-05-27');UPDATE … SET … WHERE …
UPDATE person
SET street = '1225 Tremont St.',
city = 'Boston',
state = 'MA',
country = 'USA',
postal_code = '02138'
WHERE person_id = 1;DELETE … FROM … WHERE
DELETE FROM person
WHERE person_id = 2;When Good Statements Go Bad
- Nonunique Primary Key
- Nonexistent Foreign Key
- Column Value Violations
- Invalid Date Conversions
mysql> INSERT INTO person
-> (person_id, fname, lname, eye_color, birth_date)
-> VALUES (1, 'Charles','Fulton', 'GR', '1968-01-15');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'mysql> INSERT INTO favorite_food (person_id, food)
-> VALUES (999, 'lasagna');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint
fails ('sakila'.'favorite_food', CONSTRAINT 'fk_fav_food_person_id' FOREIGN KEY
('person_id') REFERENCES 'person' ('person_id'))mysql> UPDATE person
-> SET eye_color = 'ZZ'
-> WHERE person_id = 1;
ERROR 1265 (01000): Data truncated for column 'eye_color' at row 1mysql> UPDATE person
-> SET birth_date = 'DEC-21-1980'
-> WHERE person_id = 1;
ERROR 1292 (22007): Incorrect date value: 'DEC-21-1980' for column 'birth_date'
at row 1‣
SELECT … FROM … WHERE
How data is retrieved, joined, filtered, grouped, and sorted.
SELECT person_id, fname, lname, birth_date
FROM person
WHERE person_id = 1;