SQL
Jump to navigation
Jump to search
Create a new database:
DROP DATABASE test;
CREATE DATABASE test;
CHARACTER SET latin1;
COLLATE latin1_bin;
Cheatsheet
| Action | Command | Notes |
|---|---|---|
| select a db | USE database | no semicolon needed |
| primary key column | blank_id INT AUTO_INCREMENT PRIMARY KEY | |
| display table attributes | DESCRIBE mytable; | |
| add data to a table | INSERT INTO table (field1) VALUES ('value1'); | |
| create a db | CREATE DATABASE mydatabase; | |
| create a table | CREATE TABLE db.table (col1, col2, col3, ...); | |
| show how a table was made | SHOW CREATE TABLE table \G | |
| backup a table (not a db) | mysqldump -u user -p dbname table > tbl-bak.sql | |
| backup a full db | mysqldump -u user -p dbname > dbname-bak.sql | |
| restore a full db | mysql -u user -p dbname < dbname-bak.sql | |
| copy table's form to new db | CREATE TABLE dbnew.table LIKE table; | |
| populate new table | INSERT INTO newtable SELECT * FROM oldtable; | |
| add column | ALTER TABLE table ADD COLUMN col_id INT AFTER col2; | |
| drop column | ALTER TABLE table DROP COLUMN column; | |
| copy table | CREATE TABLE new_tbl SELECT * FROM old_tbl | |
| delete all rows | TRUNCATE TABLE tbl; | |
| reset root passwd | ALTER USER 'root'@'localhost IDENTIFIED BY 'newPassword'; | |
| change column name | ALTER TABLE tbl RENAME COLUMN old_col TO new_col; | |
| change column type | ALTER TABLE tbl MODIFY name CHAR(20) DEFAULT 'N/A'; | |
| add a column | ALTER TABLE tbl ADD new_col CHAR(20); | |
| delete a row | DELETE FROM tbl WHERE thing_id = 42; |
Concepts
- ACID
- Atomic
- Consistent
- Isolated
- Durable
- CAP Theorem
Only two of consistency, availability and partition tolerance can be guaranteed simultaneously
- Table Types
- Subquery-generated: enclosed in parentheses; temporary to the query
- Temporary tables: generated by a
CREATE TEMPORARY TABLEstatement. Disappears either post-transaction or at session end - View (virtual table): a query stored in the data dictionary.
CREATE VIEW view_name AS.... No data stored, but can be queried against - Table Links: joined queries
- Taxonomy of SQL
- DDL (data definition):
CREATE, ALTER, DROP, RENAME, TRUNCATE, COMMENT - DQL (data query):
SELECT - DML (data manipulation):
INSERT, UPDATE, DELETE, MERGE, CALL, EXPLAIN, LOCK TABLE - DCL (data control):
GRANT, REVOKE - TCL (transaction control):
COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION