DB Lab 03 - MySQL by Examples
DB Lab 03 - MySQL by Examples
DB Lab 03 - MySQL by Examples
BMIS 32113
DATABASE - LAB 03
-- Database-Level
DROP DATABASE databaseName -- Delete the database (irrecoverable!)
DROP DATABASE IF EXISTS databaseName -- Delete if it exists
CREATE DATABASE databaseName -- Create a new database
CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not exists
SHOW DATABASES -- Show all the databases in this server
USE databaseName -- Set the default (current) database
SELECT DATABASE() -- Show the default database
SHOW CREATE DATABASE databaseName -- Show the CREATE DATABASE statement
-- Table-Level
DROP TABLE [IF EXISTS] tableName, ...
CREATE TABLE [IF NOT EXISTS] tableName (
columnName columnType columnAttribute, ...
PRIMARY KEY(columnName),
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
)
SHOW TABLES -- Show all the tables in the default database
DESCRIBE|DESC tableName -- Describe the details for a table
ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and DROP COLUMN
ALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES tableName
(columnNmae)
ALTER TABLE tableName DROP FOREIGN KEY constraintName
SHOW CREATE TABLE tableName -- Show the CREATE TABLE statement for this
tableName
-- Row-Level
INSERT INTO tableName
VALUES (column1Value, column2Value,...) -- Insert on all Columns
-- Others
SHOW WARNINGS; -- Show the warnings of the previous statement
A MySQL database server contains many databases (or schemas). Each database
consists of one or more tables. A table is made up of columns (or fields)
and rows (records).
The SQL keywords and commands are NOT case-sensitive. For clarity, they are shown in
uppercase. The names or identifiers (database names, table names, column names,
etc.) are case-sensitive in some systems, but not in other systems. Hence, it is best to
treat identifiers as case-sensitive.
SHOW DATABASES
You can use SHOW DATABASES to list all the existing databases in the server.
Let us begin with a simple example - a product sales database. A product sales
database typically consists of many tables, e.g., products, customers, suppliers, orders,
payments, employees, among others. Let's call our database " southwind" (inspired from
Microsoft's Northwind Trader sample database). We shall begin with the first table called
"products" with the following columns (having data types as indicated) and rows:
Database: southwind
Table: products
You can create a new database using SQL command "CREATE DATABASE databaseName";
and delete a database using " DROP DATABASE databaseName". You could optionally
apply condition "IF EXISTS" or "IF NOT EXISTS" to these commands. For example,
IMPORTANT: Use SQL DROP (and DELETE) commands with extreme care, as the deleted
entities are irrecoverable. THERE IS NO UNDO!!!
The CREATE DATABASE commands uses some defaults. You can issue a " SHOW CREATE
DATABASE databaseName" to display the full command and check these default values.
We use \G (instead of ';') to display the results vertically. (Try comparing the outputs
produced by ';' and \G.)
Unquoted names or identifiers (such as database name, table name and column name)
cannot contain blank and special characters, or crash with MySQL keywords (such
as ORDER and DESC). You can include blanks and special characters or use MySQL
keyword as identifier by enclosing it with a pair of back-quote, in the form of `name`.
NHMR/FBM Feb 2016 Extracted from ntu.edu.sg
Lab 03 BMIS 32113 -DB
For robustness, the SHOW command back-quotes all the identifiers, as illustrated in the
above example.
MySQL multi-line comments are enclosed within /* and */; end-of-line comments begins
with -- (followed by a space) or #.
The /*!40100 ...... */ is known as version comment, which will only be run if the server is
at or above this version number 4.01.00. To check the version of your MySQL server,
issue query "SELECT version()".
The command "USE databaseName" sets a particular database as the default (or current)
database. You can reference a table in the default database using tableName directly.
But you need to use the fully-qualified databaseName.tableName to reference a table
NOT in the default database.
In our example, we have a database named " southwind" with a table named "products".
If we issue "USE southwind" to set southwind as the default database, we can simply call
the table as "products". Otherwise, we need to reference the table as
"southwind.products".
To display the current default database, issue command " SELECT DATABASE()".
You can create a new table in the default database using command "CREATE
TABLE tableName" and "DROP TABLE tableName". You can also apply condition " IF EXISTS"
or "IF NOT EXISTS". To create a table, you need to define all its columns, by providing the
columns' name, type, and attributes.
-- Beware that DROP (and DELETE) actions are irreversible and not recoverable!
mysql> DROP DATABASE IF EXISTS southwind;
Query OK, 1 rows affected (0.31 sec)
-- Create the table "products". Read "explanations" below for the column defintions
mysql> CREATE TABLE IF NOT EXISTS products (
productID INT UNSIGNED NOT NULL AUTO_INCREMENT,
productCode CHAR(3) NOT NULL DEFAULT '',
name VARCHAR(30) NOT NULL DEFAULT '',
quantity INT UNSIGNED NOT NULL DEFAULT 0,
price DECIMAL(7,2) NOT NULL DEFAULT 99999.99,
PRIMARY KEY (productID)
);
Query OK, 0 rows affected (0.08 sec)
-- Show all the tables to confirm that the "products" table has been created
mysql> SHOW TABLES;
+---------------------+
| Tables_in_southwind |
+---------------------+
| products |
+---------------------+
-- Show the complete CREATE TABLE statement used by MySQL to create this table
mysql> SHOW CREATE TABLE products \G
*************************** 1. row ***************************
Table: products
Create Table:
CREATE TABLE `products` (
`productID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`productCode` char(3) NOT NULL DEFAULT '',
`name` varchar(30) NOT NULL DEFAULT '',
`quantity` int(10) unsigned NOT NULL DEFAULT '0',
`price` decimal(7,2) NOT NULL DEFAULT '99999.99',
PRIMARY KEY (`productID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Explanations
The attribute "NOT NULL" specifies that the column cannot contain
the NULL value. NULL is a special value indicating "no value", "unknown value" or
"missing value". In our case, these columns shall have a proper value. We also set the
default value of the columns. The column will take on its default value, if no value is
specified during the record creation.
We set the column productID as the so-called primary key. Values of the primary-key
column must be unique. Every table shall contain a primary key. This ensures that every
row can be distinguished from other rows. You can specify a single column or a set of
columns (e.g., firstName and lastName) as the primary key. An index is build
automatically on the primary-key column to facilitate fast search. Primary key is also
used as reference by other tables.
We set the column productID to AUTO_INCREMENT. with default starting value of 1. When
you insert a row with NULL (recommended) (or 0, or a missing value) for
the AUTO_INCREMENT column, the maximum value of that column plus 1 would be
inserted. You can also insert a valid value to an AUTO_INCREMENT column, bypassing the
auto-increment.
Let's fill up our "products" table with rows. We set the productID of the first record to
1001, and use AUTO_INCREMENT for the rest of records by inserting a NULL, or with a
missing column value. Take note that strings must be enclosed with a pair of single
quotes (or double quotes).
We can use the INSERT INTO statement to insert a new row with all the column values,
using the following syntax:
You need to list the values in the same order in which the columns are defined in
the CREATE TABLE, separated by commas. For columns of string data type
(CHAR, VARCHAR), enclosed the value with a pair of single quotes (or double quotes). For
columns of numeric data type (INT, DECIMAL, FLOAT, DOUBLE), simply place the number.
You can also insert multiple rows in one INSERT INTO statement:
The remaining columns will receive their default value, such as AUTO_INCREMENT,
default, or NULL.
The most common, important and complex task is to query a database for a subset of
data that meets your needs - with the SELECT command. The SELECT command has the
following syntax:
-- List all the rows of ALL columns, * is a wildcard denoting all columns
SELECT * FROM tableName
For examples,
-- List all rows of ALL the columns. The wildcard * denotes ALL columns
mysql> SELECT * FROM products;
+-----------+-------------+-----------+----------+-------+
| productID | productCode | name | quantity | price |
+-----------+-------------+-----------+----------+-------+
| 1001 | PEN | Pen Red | 5000 | 1.23 |
| 1002 | PEN | Pen Blue | 8000 | 1.25 |
| 1003 | PEN | Pen Black | 2000 | 1.25 |
| 1004 | PEC | Pencil 2B | 10000 | 0.48 |
| 1005 | PEC | Pencil 2H | 8000 | 0.49 |
+-----------+-------------+-----------+----------+-------+
5 rows in set (0.00 sec)
You can also issue SELECT without a table. For example, you can SELECT an expression
or evaluate a built-in function.
// Multiple columns
mysql> SELECT 1+1, NOW();
+-----+---------------------+
| 1+1 | NOW() |
+-----+---------------------+
| 2 | 2012-10-24 22:16:34 |
+-----+---------------------+
1 row in set (0.00 sec)
Comparison Operators
For numbers (INT, DECIMAL, FLOAT), you could use comparison operators: '=' (equal
to), '<>' or '!=' (not equal to), '>' (greater than), '<' (less than), '>=' (greater than or
equal to), '<=' (less than or equal to), to compare two numbers. For example, price >
1.0, quantity <= 500.
mysql> SELECT name, price FROM products WHERE price < 1.0;
+-----------+-------+
| name | price |
+-----------+-------+
| Pencil 2B | 0.48 |
| Pencil 2H | 0.49 |
+-----------+-------+
2 rows in set (0.00 sec)
mysql> SELECT name, quantity FROM products WHERE quantity <= 2000;
+-----------+----------+
| name | quantity |
+-----------+----------+
| Pen Black | 2000 |
+-----------+----------+
1 row in set (0.00 sec)
CAUTION: Do not compare FLOATs (real numbers) for equality ('=' or '<>'), as they are
not precise. On the other hand, DECIMAL are precise.
For strings, you could also use '=', '<>', '>', '<', '>=', '<=' to compare two strings
(e.g., productCode = 'PEC'). The ordering of string depends on the so-
called collation chosen. For example,
For strings, in addition to full matching using operators like '=' and '<>', we can
perform pattern matching using operator LIKE (or NOT LIKE) with wildcard characters.
The wildcard '_' matches any single character; '%' matches any number of characters
(including zero). For example,
MySQL also support regular expression matching via the REGEXE operator.
Arithmetic Operators
You can perform arithmetic operations on numeric fields using arithmetic operators, as
tabulated below:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
DIV Integer Division
% Modulus (Remainder)
You can combine multiple conditions with boolean operators AND, OR, XOR. You can also
invert a condition using operator NOT. For examples,
mysql> SELECT * FROM products WHERE quantity >= 5000 AND name LIKE 'Pen %';
+-----------+-------------+----------+----------+-------+
| productID | productCode | name | quantity | price |
+-----------+-------------+----------+----------+-------+
| 1001 | PEN | Pen Red | 5000 | 1.23 |
| 1002 | PEN | Pen Blue | 8000 | 1.25 |
+-----------+-------------+----------+----------+-------+
mysql> SELECT * FROM products WHERE quantity >= 5000 AND price < 1.24 AND
name LIKE 'Pen %';
+-----------+-------------+---------+----------+-------+
| productID | productCode | name | quantity | price |
+-----------+-------------+---------+----------+-------+
| 1001 | PEN | Pen Red | 5000 | 1.23 |
+-----------+-------------+---------+----------+-------+
mysql> SELECT * FROM products WHERE NOT (quantity >= 5000 AND name LIKE 'Pen
%');
+-----------+-------------+-----------+----------+-------+
| productID | productCode | name | quantity | price |
+-----------+-------------+-----------+----------+-------+
| 1003 | PEN | Pen Black | 2000 | 1.25 |
| 1004 | PEC | Pencil 2B | 10000 | 0.48 |
| 1005 | PEC | Pencil 2H | 8000 | 0.49 |
+-----------+-------------+-----------+----------+-------+
IN, NOT IN
You can select from members of a set with IN (or NOT IN) operator. This is easier and
clearer than the equivalent AND-OR expression.
mysql> SELECT * FROM products WHERE name IN ('Pen Red', 'Pen Black');
+-----------+-------------+-----------+----------+-------+
| productID | productCode | name | quantity | price |
+-----------+-------------+-----------+----------+-------+
| 1001 | PEN | Pen Red | 5000 | 1.23 |
| 1003 | PEN | Pen Black | 2000 | 1.25 |
+-----------+-------------+-----------+----------+-------+
To check if the value is within a range, you could use BETWEEN ... AND ... operator.
Again, this is easier and clearer than the equivalent AND-OR expression.
NULL is a special value, which represent "no value", "missing value" or "unknown value".
You can checking if a column contains NULL by IS NULL or IS NOT NULL. For example,
You can order the rows selected using ORDER BY clause, with the following syntax:
The selected row will be ordered according to the values in columnA, in either ascending
(ASC) (default) or descending (DESC) order. If several rows have the same value
in columnA, it will be ordered according to columnB, and so on. For strings, the ordering
could be case-sensitive or case-insensitive, depending on the so-called character
collating sequence used. For examples,
You can randomize the returned records via function RAND(), e.g.,
LIMIT Clause
A SELECT query on a large database may produce many rows. You could use
the LIMIT clause to limit the number of rows displayed, e.g.,
To continue to the following records , you could specify the number of rows to be
skipped, followed by the number of rows to be displayed in the LIMIT clause, as follows:
-- Skip the first two rows and display the next 1 row
mysql> SELECT * FROM products ORDER BY price LIMIT 2, 1;
+-----------+-------------+---------+----------+-------+
| productID | productCode | name | quantity | price |
+-----------+-------------+---------+----------+-------+
| 1001 | PEN | Pen Red | 5000 | 1.23 |
+-----------+-------------+---------+----------+-------+
AS - Alias
You could use the keyword AS to define an alias for an identifier (such as column name,
table name). The alias will be used in displaying the name. It can also be used as
reference. For example,
Take note that the identifier "Unit Price" contains a blank and must be back-quoted.
Function CONCAT()
You can also concatenate a few columns as one (e.g., joining the last name and first
name) using function CONCAT(). For example,