An Example for the Beginners (But NOT for the dummies)


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.
You can use SHOW DATABASES to list all the existing databases in the server.
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
+--------------------+
4 rows in set (0.00 sec)


The databases "mysql", "information_schema" and "performance_schema" are system databases used internally by MySQL. A "test" database is provided during installation for your testing.
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 (with the data types as indicated) and rows:

Database: southwind Table: products
productID INT
productCode CHAR(3)
name VARCHAR(30)
quantity INT
price DECIMAL(10,2)
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

2.1 Creating and Deleting a Database - CREATE DATABASE and DROP DATABASE

CREATE DATABASE and DROP DATABASE
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,
mysql> CREATE DATABASE southwind;
Query OK, 1 row affected (0.03 sec)
mysql> DROP DATABASE southwind;
Query OK, 0 rows affected (0.11 sec)
mysql> CREATE DATABASE IF NOT EXISTS southwind;
Query OK, 1 row affected (0.01 sec)
mysql> DROP DATABASE IF EXISTS southwind;
Query OK, 0 rows affected (0.00 sec)
IMPORTANT: Use SQL DROP (and DELETE) commands with extreme care, as the deleted entities are irrecoverable. THERE IS NO UNDO!!!
SHOW CREATE DATABASE
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.)
mysql> CREATE DATABASE IF NOT EXISTS southwind;
mysql> SHOW CREATE DATABASE southwind \G
*************************** 1. row ***************************
Database: southwind
Create Database: CREATE DATABASE `southwind` /*!40100 DEFAULT CHARACTER SET latin1 */
Back-Quoted Identifiers (`name`)
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, i.e., `name`. For robustness, the SHOW command back-quotes all the identifiers, as illustrated in the above example.

MySQL Version Comments
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()".

2.2 Setting the Default Database - USE

The command "USE databaseName" selects a particular database as the default (or current) database. You can refer to a table in the default database using tableName directly; but you need to use the fully-qualified databaseName.tableName to refer to 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()".

2.3 Creating and Deleting a Table - CREATE TABLE and DROP TABLE

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.
Let's create the table "products" for our database "southwind".
-- Remove the database "southwind", if it exists.
-- 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 database "southwind"
mysql> CREATE DATABASE southwind;
Query OK, 1 row affected (0.01 sec)
-- Show all the databases in the server
-- to confirm that "southwind" database has been created.

mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| southwind |
| ...... |

+--------------------+
-- Set "southwind" as the default database so as to reference its table directly.
mysql> USE southwind;
Database changed
-- Show the current (default) database
mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| southwind |
+------------+
-- Show all the tables in the current database.
-- "southwind" has no table (empty set).
mysql> SHOW TABLES;
Empty set (0.00 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 |
+---------------------+
-- Describe the fields (columns) of the "products" table
mysql> DESCRIBE products;
+-------------+------------------+------+-----+------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+------------+----------------+
| productID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| productCode | char(3) | NO | | | |
| name | varchar(30) | NO | | | |
| quantity | int(10) unsigned | NO | | 0 | |
| price | decimal(7,2) | NO | | 99999.99 | |
+-------------+------------------+------+-----+------------+----------------+
-- 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
We define 5 columns in the table products: productID, productCode, name, quantity and price. The data types are:
 productID is INT UNSIGNED - non-negative integers.
 productCode is CHAR(3) - a fixed-length alphanumeric string of 3 characters.
 name is VARCHAR(30) - a variable-length string of up to 30 characters. We use fixed-length string for productCode, as we assume that the productCode contains exactly 3 characters. On the other hand, we use variable-length string for name, as its length varies - VARCHAR is more efficient than CHAR.
 quantity is also INT.
 price is DECIMAL(10,2) - a decimal number with 2 decimal places. DECIMAL is precise (represented as integer with a fix decimal point). On the other hand, FLOAT and DOUBLE (real numbers) are not precise and are approximated. DECIMAL type is recommended for currency.
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". We also set the default values of all 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 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 for other tables.
We set the column productID to AUTO_INCREMENT. with default starting value of 1. When you insert a NULL (recommended) (or 0, or a missing value), into an 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.

2.4 Inserting Rows - INSERT INTO


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).
-- Insert a row with all the column values
mysql> INSERT INTO products VALUES (1001, 'PEN', 'Pen Red', 5000, 1.23);
Query OK, 1 row affected (0.04 sec)
-- Insert multiple rows
-- Inserting NULL to an auto_increment column results in max_value + 1
mysql> INSERT INTO products VALUES
(NULL, 'PEN', 'Pen Blue', 8000, 1.25),
(NULL, 'PEN', 'Pen Black', 2000, 1.25);
Query OK, 2 rows affected (0.03 sec)
Records: 2 Duplicates: 0 Warnings: 0
-- Insert value to selected columns
-- Missing value for an auto_increment column also results in max_value + 1
mysql> INSERT INTO products (productCode, name, quantity, price) VALUES
('PEC', 'Pencil 2B', 10000, 0.48),
('PEC', 'Pencil 2H', 8000, 0.49);
Query OK, 2 row affected (0.03 sec)
-- Missing columns get their default values
mysql> INSERT INTO products (productCode, name) VALUES ('PEC', 'Pencil HB');
Query OK, 1 row affected (0.04 sec)
-- 2nd column is defined to be NOT NULL
mysql> INSERT INTO products values (NULL, NULL, NULL, NULL, NULL); ERROR 1048 (23000): Column 'productCode' cannot be null
-- Query the table
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 |
| 1006 | PEC | Pencil HB | 0 | 9999999.99 |
+-----------+-------------+-----------+----------+------------+
6 rows in set (0.02 sec)
-- Remove the last row
mysql> DELETE FROM products WHERE productID = 1006;
Syntax
We can use the INSERT INTO statement to insert a new row with all the column values, using the following syntax:

INSERT INTO tableName VALUES (firstColumnValue, ..., lastColumnValue) -- All columns
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:
INSERT INTO tableName VALUES
(row1FirstColumnValue, ..., row1lastColumnValue),
(row2FirstColumnValue, ..., row2lastColumnValue),
...
To insert a row with values on selected columns only, use:
-- Insert single record with selected columns
INSERT INTO tableName (column1Name, ..., columnNName) VALUES (column1Value, ..., columnNValue)
-- Alternately, use SET to set the values
INSERT INTO tableName SET column1=value1, column2=value2, ...
-- Insert multiple records
INSERT INTO tableName
(column1Name, ..., columnNName)
VALUES
(row1column1Value, ..., row2ColumnNValue),
(row2column1Value, ..., row2ColumnNValue),
...
The remaining columns will receive their default value, such as AUTO_INCREMENT, default, or NULL.

2.5 Querying the Database - SELECT

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 the specified columns
SELECT column1Name, column2Name, ... FROM tableName
-- List all the rows of ALL columns, * is a wildcard denoting all columns
SELECT * FROM tableName
-- List rows that meet the specified criteria in WHERE clause
SELECT column1Name, column2Name,... FROM tableName WHERE criteria
SELECT * FROM tableName WHERE criteria
For examples,

Comments

Popular posts from this blog

Advantages and disadvantages of USE CASE diagram

Microsoft Toolkit 2.5.4 Windows and Office Activation

How to Set Up a Counter Strike LAN Game