SQL or Structured Query Language is a language for operating on data in a Relational Data-Base Management System (RDBMS). The data in a database is usually structured into tables (sometimes known as relations) which are rows of data subdivided into columns of specific types. A simple spreadsheet is roughly analogous to a table. Operations on tables follow the CRUD (Create, Read, Update, Delete) model, with specific SQL commands to perform those operations.
When making web applications a back-end data store is often desired for storing user data
mysql [-p] [-u username ] [-h hostname ] [ database ] -p = prompt for password (default = don't ask for a password) -u username = Username to use to connect to the database with (default = your Unix username) -h hostname = Connect to a server on a different host (default is localhost) database = database on the server to use (default = username)
mysql [-p] [-u
] [-h
] [
]
-p
-u
-h
The client command connects to the running database server where you can then issue commands to the server directly. It is also used to restore databases by reading SQL commands created by the mysqldump command as its input.
mysqldump
"INSERT INTO `table` (`col1`, `col2`, `col3`) VALUES ('abc', 1, NULL);"
[client] user=<username> password=<password> database=<database>
mysql
# chmod 600 ~/.my.cnf
SET PASSWORD = password('password')
SET PASSWORD = password('
')
SHOW TABLES;
USE database;
USE
;
CREATE TABLE tbl_name ( create_definition );
CREATE TABLE
(
);
| column_name column_definition
|
| PRIMARY KEY ( index_col_name, ... ) Defines a particular column or columns to represent a unique identifier for any particular row, such as an auto-increasing number. The database is usually laid out in a tree like structure with the primary key defining the nodes for the tree. The primary key should be the constraint with the fewest columns and smallest size. Makes it impossible to commit an update that would create an entry with a duplicate of the primary key.
| PRIMARY KEY ( index_col_name, ... )
| PRIMARY KEY (
,
)
| { INDEX|KEY } [ index_name ] [ index_type ] ( index_col_name, ... ) Creates an index using a particular column or columns, the values of which aren't required to be unique. Used to create an index or tree based on the hopefully fairly well distributed column values to speed row searches.
| { INDEX|KEY } [ index_name ] [ index_type ] ( index_col_name, ... )
INDEX
KEY
| UNIQUE [INDEX|KEY] [ index_name ] [ index_type ] ( index_col_name, ... ) [ index_options ] Defines a secondary unique index or key, like the primary key.
| UNIQUE [INDEX|KEY] [ index_name ] [ index_type ] ( index_col_name, ... ) [ index_options ]
| UNIQUE
| { FULLTEXT|SPATIAL } [INDEX|KEY] [ index_name ] ( index_col_name, ... ) Defines a column of columns to do text searches on.
| { FULLTEXT|SPATIAL } [INDEX|KEY] [ index_name ] ( index_col_name, ... )
FULLTEXT
SPATIAL
data_type
[ NOT NULL | NULL ] Specifies if the value for this column can be NULL or not. Default is to allow NULL.
[ NOT NULL | NULL ]
NOT NULL
NULL
[ DEFAULT default_value ] Defines a default value for this column if none is provided on insert.
[ DEFAULT default_value ]
DEFAULT
[ AUTO_INCREMENT ] Defines a default value for an integer that is auto-increasing.
[ AUTO_INCREMENT ]
AUTO_INCREMENT
[ UNIQUE [KEY] | [PRIMARY] KEY ] Defines this column directly as a unique or primary key.
[ UNIQUE [KEY] | [PRIMARY] KEY ]
UNIQUE
PRIMARY
[ COMMENT 'string' ] Defines a comment for this column. Use "SHOW FULL COLUMNS" to view.
[ COMMENT 'string' ]
COMMENT
'
length: = display length for numeric values. = total # digits of precision for floating types = maximum length for string types.
decimals: = number of digits past the . to display for floats (max 30, should be <= length-2)
Numeric types can include a UNSIGNED and ZEROFILL options.
CHAR and TEXT types can have CHARACTER SET charset_name and COLLATE collation_name options.
BIT
TINYINT
BOOLEAN
TINYINT(1)
SMALLINT
MEDIUMINT
INT
INTEGER
BIGINT
FLOAT
REAL
DOUBLE
DECIMAL
NUMERIC
DATE
TIME
TIMESTAMP
DATETIME
YEAR
CHAR
VARCHAR(
BINARY
VARBINARY(
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
TINYTEXT
TEXT
MEDIUMTEXT
LONGTEXT
ENUM(
SET(
-- This is a comment -- Not necessary if connecting to the 'cs47925' database directly: USE cs47925; -- Delete the table before creation: DROP TABLE IF EXISTS `person`; CREATE TABLE `person` ( `id` INT(8) NOT NULL AUTO_INCREMENT, `fname` VARCHAR(64) NOT NULL DEFAULT '', `lname` VARCHAR(64) NOT NULL DEFAULT '', `age` TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 );
> mysql -p < newdb.sql
ALTER TABLE tbl_name [alter_spec [,alter_spec ...]]
ALTER TABLE
DROP TABLE [IF EXISTS] tbl_name
DROP TABLE
IF EXISTS
TRUNCATE [TABLE] tbl_name
TRUNCATE
TABLE
DESCRIBE tbl_name;
DESCRIBE
INSERT [INTO] tbl_name [(col,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col=expr [, col=expr] ... ]
INSERT
INTO
VALUES
VALUE
),(
),
ON DUPLICATE KEY UPDATE
=
Inserts data from the VALUES section defined by the columns in the optional (col,..) list.
with ON DUPLICATE KEY UPDATE, the database will perform an update if there would be a duplication of a primary or unique key.
INSERT INTO person (fname, lname) VALUES ('Bob', 'Smith'), ('John', 'Doe');
INSERT INTO person VALUES (1, 'Bob', 'Smith', 46) ON DUPLICATE KEY UPDATE fname='Bob', lname='Smith', age=46;
or:
INSERT [INTO] tbl_name SET col={expr | DEFAULT}, ... [ ON DUPLICATE KEY UPDATE col=expr [, col=expr] ... ]
SET
INSERT INTO person SET fname='Bob', lname='Smith';
INSERT [INTO] tbl_name SELECT ... [ ON DUPLICATE KEY UPDATE col=expr [, col=expr] ... ]
SELECT
INSERT INTO department SELECT * FROM person WHERE id=10;
[ALL | DISTINCT | DISTINCTROW]
ALL
DISTINCT
DISTINCTROW
Some rows may be identical, select will return them all (ALL, the default) or may be told to only return distinct values (DISTINCT/DISTINCTROW). select_expr [, select_expr ...]
one of the following:
[ FROM table_references ]
FROM
[WHERE where_condition]
WHERE
[GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]
GROUP BY
ASC
DESC
WITH ROLLUP
[ORDER BY {col_name | expr | position} [ASC | DESC], ...]
ORDER BY
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
LIMIT
OFFSET
SELECT * FROM person; SELECT fname,lname FROM person WHERE id < 100 LIMIT 10; SELECT fname,lname FROM person ORDER BY age ASC;
SELECT * FROM person;
SELECT fname,lname FROM person WHERE id < 100 LIMIT 10;
SELECT fname,lname FROM person ORDER BY age ASC;
Single table syntax:
UPDATE tbl_name SET col1={expr1 | DEFAULT} [,col2={expr2 | DEFAULT}] ... [WHERE where_condition]
UPDATE
UPDATE person SET age=50 WHERE id=1; UPDATE person SET lname='Johnson' WHERE ( fname='Alice' AND lname='Smith' );
UPDATE person SET age=50 WHERE id=1;
UPDATE person SET lname='Johnson' WHERE ( fname='Alice' AND lname='Smith' );
DELETE FROM tbl_name
DELETE FROM
[ORDER BY ...]
[LIMIT row_count]
[RETURNING select_expr [, select_expr ...]]
RETURNING
DELETE FROM person WHERE id=5; DELETE FROM person ORDER BY age DESC LIMIT 5; DELETE FROM person WHERE lname='Smith' RETURNING id;
DELETE FROM person WHERE id=5;
DELETE FROM person ORDER BY age DESC LIMIT 5;
DELETE FROM person WHERE lname='Smith' RETURNING id;
When modifying a table where you may have many readers and writers simultaneously operating on a tables data, it becomes necessary to use locks
LOCK TABLES tbl_name [[AS] alias] lock_type [, tbl_name [[AS] alias] lock_type] ...
LOCK TABLES
AS
lock_type:
READ
The holder of a read lock can read a table, but not write to it.
Any number of readers can obtain a read lock at the same time.
Other users can read the table without acquiring a read lock.
WRITE
The user that hold a write lock may read and write to a table.
no one else may read or write to the table while the above user holds the lock.
lock requests for the table will block until the write lock is released.
UNLOCK TABLES;