MySQL Tutorial – Part 1

| (MySQL Tutorial – Part 2) Next >

MySQL Tutorial : Beginning

 


MySQL is embedded Database Management System (DMS) under the open-source GNU General Public License (GPL). Its name goes after the co-founder Monty Widenious’s daughter, My. The logo’s name is “Sakila”.

This client/server system allow the user to reduce record filling time, reduce record retrieval time, flexible retrieval order, flexible output format, simultaneous multiple-user access to records, remote access to records, and transmission of records. In other words, MySQL is a structured collection and management of data. Instead of allocating all the data in one place, a database allows for a rational storage of data in separate tables.

Written in C/C++ , MySQL uses a multilayer server design focus on dependent modules and multi-threaded (using kernel threads). The memory allocation system is also thread-based. It uses a combination of B-tree disk table (MyISAM), index compression, in-memory hast tables used as temporary tables, nested-loop join, and supports full ANSI (American National Standards Institute) and ISO(International Organization for Standardization) SQL standards plus ODBC (levels 0 to 3.51).

I personally use XAMPP which allows me to install an Apache distribution containing MySQL, PHP and Perl in a very easy way.
For this tutorial, we are going to be working using the command line. I installed my XAMPP distribution in my Linux machine.

In MySQL, there is not case sensitive (doesn’t matter the mix of upper case and lower case characters); however, I will be using upper case for those keywords (such as SELECT) that will be used.

Most of the language in MySQL are divided between Data Manipulation Language (DML) and data definition Language (DDL).

The Data Manipulation Language (DML)

  • SELECT – extracts data from a database
  • INSERT INTO – inserts new data into a database
  • UPDATE – updates data in a database
  • DELETE – deletes data from a database

The Data Definition Language (DDL)

  • CREATE DATABASE – creates a new database
  • ALTER DATABASE – modifies a database
  • CREATE TABLE – creates a new table
  • ALTER TABLE – modifies a table
  • DROP TABLE – deletes a table
  • CREATE INDEX – creates an index (such as a search key)
  • DROP INDEX – deletes an index

In the next part of this tutorial, we are going to learn how to:

  • Connect to MySQL from the command line
  • Display a list of databases
  • Select a database
  • Show users privilege
  • Create and modify a database
  • Create and modify a table

Connecting to MySQL

We are going to connect to the database using the following command:
mysql -h <host> -u <user> -p
where:
-h, –host=name Connect to host.
-u, –user=name User for login if not current user.
-p, –password[=name] Password to use when connecting to server. If password is not given it’s asked from the tty.

Example:

user@a-pro:/opt/lampp/bin$
./mysql -h localhost -u lampp -p
Enter password: *************
Welcome to the MySQL monitor.
Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.1.41 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 

mysql>

 

Displaying List of Databases

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| test               |
+--------------------+
2 rows in set (0.09 sec)

 

Using a Database

mysql> USE information_schema;
Database changed

Knowing which Database is Being Use

mysql> SELECT DATABASE();
+------------+
| database() |
+------------+
| db_example |
+------------+
1 row in set (0.00 sec)

if for some reason you see this:

mysql> SELECT DATABASE();
+------------+
| database() |
+------------+
| NULL       |
+------------+
1 row in set (0.00 sec)

This means that non database was selected.

 

Show Database’s Tables

mysql> SHOW TABLES;
+---------------------------------------+
| Tables_in_information_schema          |
+---------------------------------------+
| CHARACTER_SETS                        |
| COLLATIONS                            |
| COLLATION_CHARACTER_SET_APPLICABILITY |
| COLUMNS                               |
| COLUMN_PRIVILEGES                     |
| ENGINES                               |
| EVENTS                                |
| FILES                                 |
| GLOBAL_STATUS                         |
| GLOBAL_VARIABLES                      |
| KEY_COLUMN_USAGE                      |
| PARTITIONS                            |
| PLUGINS                               |
| PROCESSLIST                           |
| PROFILING                             |
| REFERENTIAL_CONSTRAINTS               |
| ROUTINES                              |
| SCHEMATA                              |
| SCHEMA_PRIVILEGES                     |
| SESSION_STATUS                        |
| SESSION_VARIABLES                     |
| STATISTICS                            |
| TABLES                                |
| TABLE_CONSTRAINTS                     |
| TABLE_PRIVILEGES                      |
| TRIGGERS                              |
| USER_PRIVILEGES                       |
| VIEWS                                 |
+---------------------------------------+
28 rows in set (0.00 sec) mysql>

 

Create a New Database

mysql> CREATE DATABASE db_example;
ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db_example'

If you get this kind of error, its because you don’t have the permission which allow you to create a new database.

Use SHOW GRANTS to see what privileges a given account has:

mysql> SHOW GRANTS;
+--------------------------------------+
| Grants for @localhost                |
+--------------------------------------+
| GRANT USAGE ON *.* TO ''@'localhost' |
+--------------------------------------+
1 row in set (0.00 sec)

So, since user doesn’t have the privileges required for the job, lets reconnect as root (administrator)
NOTE: Later, I will go over how to create users and grant them privileges.

user@a-pro:/opt/lampp/bin$
./mysql -h localhost -u root -p
Enter password: *************
Welcome to the MySQL monitor.
Commands end with ; or \g.
Your MySQL connection id is 17
Server version: 5.1.41 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 

mysql>

Now lets create our first database named db_example

mysql> CREATE DATABASE db_example;
Query OK, 1 row affected (0.02 sec)

 

Creating Tables

If we check our new database, db_example, we can see that it is empty. We need to create tables.
Lets create a table of products with the following columns:
id: unique product id number designated to each element
name: product name

mysql> CREATE TABLE tbl_product (
    -> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> PRIMARY KEY (id),
    -> name VARCHAR(50) NOT NULL
    -> );
Query OK, 0 rows affected (0.11 sec)

Lets analyse this command line:

  • tbl_product: name of the table
  • id: INT means integer, UNSIGNED means only positive numbers, NOT NULL means that the record cannot be empty, and AUTO_INCREMENT means that the value given keeps incrementing.
  • PRIMARY KEY (id): This means that the column ‘id’ constraint uniquely identifies each record in a database table. A primary key must contain unique values and cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key.
  • name: VARCHAR (50) means that can have up to 50 characters alphanumeric, NOT NULL means that the record cannot be empty.

As we go, I will be introducing more types such as INT, CHAR, VARCHAR, DATE, and others.

 

Show Tables

mysql> SHOW TABLES;
+----------------------+
| Tables_in_db_example |
+----------------------+
| tbl_product          |
+----------------------+
1 row in set (0.00 sec)

Describe a Table

mysql> DESCRIBE tbl_product;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50)      | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

The same goes if you use:

  • DESC tbl_product;
  • EXPLAIN tbl_product;
  • SHOW COLUMNS FROM tbl_product;
  • SHOW FIELDS FROM tbl_product;

 

Changing Database’s Name

If you are like me, I really like names that have a meaning in everything I do. I like to be clear.
It not the first time, I use a name that doesn’t make sense and then I wish to correct it.
Right now, I wish to change the name of my database from ‘db_example’ to ‘db_examples’.

In MySQL there is no support for database renaming. I know that some of you may say there is ALTER DATABASE but only works depending of which version of MySQL you are working on.
The safest way to rename the database (in which there is no excuses about security and other mambo jumbo) is to create a new database, rename all the tables while making them be part of the new database.
Finally, drop the older database.

  1. mysql> CREATE DATABASE db_examples;
    Query OK, 1 row affected (0.02 sec)
  2. mysql> RENAME TABLE db_example.tbl_product TO db_examples;
    Query OK, 0 rows affected (0.02 sec)
  3. mysql> RENAME TABLE db_example.tbl_product TO db_examples.tbl_product;
    Query OK, 0 rows affected (0.00 sec)
  4. mysql> DROP DATABASE db_example;
    Query OK, 0 rows affected (0.59 sec)

Changing Table’s Name I don’t like ‘tbl_product’ because there are more than one product, there are ‘products’. So lets rename the table as ‘tbl_products’.

mysql> RENAME TABLE db_examples.tbl_product TO tbl_products;
Query OK, 0 rows affected (0.05 sec)

So, we finish with:

mysql> show tables;
+-----------------------+
| Tables_in_db_examples |
+-----------------------+
| tbl_products          |
+-----------------------+
1 row in set (0.00 sec)

Changing the Table’s Structure

Right now our ‘tbl_products’ table looks like this:

mysql> DESCRIBE tbl_product;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50)      | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

However, lets say we wish to add a column (or field) in which we can store a price and a description of each product.
We can accomplish this by using the ALTER TABLE statement.

We follow the following syntax: ALTER TABLE table_name ADD column_name column_type;

Lets add ‘price’ and ‘description’ columns to the table:

  1. mysql> ALTER TABLE tbl_products ADD price INT(10);
    Query OK, 0 rows affected (0.15 sec)
    Records: 0  Duplicates: 0  Warnings: 0
  2. mysql> ALTER TABLE tbl_products ADD description VARCHAR(50);
    Query OK, 0 rows affected (0.07 sec)
    Records: 0  Duplicates: 0  Warnings: 0

So, now the table looks like this:

mysql> DESC tbl_products;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name        | varchar(50)      | NO   |     | NULL    |                |
| price       | int(10)          | YES  |     | NULL    |                |
| description | varchar(50)      | YES  |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

Now that we see the table, we may notice that the type used on the description column should be TEXT instead of VARCHAR of 50 characters.
Lets alter the table using MODIFY:

mysql> ALTER TABLE tbl_products MODIFY description TEXT;
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

Resulting in the following table:

mysql> DESC tbl_products;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name        | varchar(50)      | NO   |     | NULL    |                |
| price       | int(10)          | YES  |     | NULL    |                |
| description | text             | YES  |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

It may see that our work is finished, but there is a problem with this table. The problem is that not every product may have a description. Leaving the column description in this table would be a waste of space and process time. There are other tricks that we can do to store products’ description, so lets DROP the column ‘description’:

mysql> ALTER TABLE tbl_products DROP description;
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

At the end, our table would like looks like this:

mysql> DESC tbl_products;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50)      | NO   |     | NULL    |                |
| price | int(10)          | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

 

Filling The Table Up

There are more than one way to fill a table up. The most common statements use are INSERT INTO and LOAD DATA.
Here I will only talk about LOAD DATA statement. The INSERT INTO is explained in the second part of this tutorial.

LOAD DATA allows you to input the content of a file into a table or to extract the content of a table into a file.

Right now, we are only interested about how to import information into the table.

LOAD DATA LOCAL INFILE ‘/file_with_information_to_import.csv’
INTO TABLE table_name
FIELDS TERMINATED BY ‘,’
LINES TERMINATED BY ‘\n’
(column_1, column_2, column_N);

In this case our list of products are inside a file named ‘products_to_import.css’ with this content:

Chain Saw Husq, 600
Chain Saw tong, 130
Multi-Tester Pepe Electronics, 240

Lets apply the command line:

mysql> LOAD DATA LOCAL INFILE '/home/user/Documents/products_to_import.csv'
    -> INTO TABLE tbl_products
    -> FIELDS TERMINATED BY ','
    -> LINES TERMINATED BY '\n'
    -> (name, price);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0

Now lets, see all the content of our table using the SELECT statement:

mysql> SELECT * FROM tbl_products;
+----+-------------------------------+-------+
| id | name                          | price |
+----+-------------------------------+-------+
|  1 | Chain Saw Husq                |   600 |
|  2 | Chain Saw tong                |   130 |
|  3 | Multi-Tester Pepe Electronics |   240 |
+----+-------------------------------+-------+
3 rows in set (0.00 sec)

Now, we have a complete table to work with.

Data Types

As we saw, we can create different tables with different type of data for each column.
The following are the different data types that can be use on MySQL.

Number Types:

Data type

Description

TINYINT(size)

Values from -128 to 127

UNSIGNED TINYINT(size)

Values from 0 to 255

SMALLINT(size)

Values from -32768 to 32767

UNSIGNED SMALLINT(size)

Values from 0 to 65535

MEDIUMINT(size)

Values from -8388608 to 8388607

UNSIGNED MEDIUMINT(size)

Values from 0 to 16777215

INT(size)

Values from -2147483648 to 2147483647

UNSIGNED INT(size)

Values from 0 to 4294967295

BIGINT(size)

Values from -9223372036854775808 to 9223372036854775807

UNSIGNED BIGINT(size)

Values from 0 to 18446744073709551615

FLOAT(size, number_of_digits)

Represent a small number with a floating decimal point. The number_of_digits parameter specify the maximum number of digits to the right of the decimal point. (*)

DOUBLE(size, number_of_digits)

Represent a large number with a floating decimal point. The number_of_digits parameter specify the maximum number of digits to the right of the decimal point. (*)

DECIMAL(size, number_of_digits)

DECIMAL is a DOUBLE stored as a string which allows for a fixed decimal point. The number_of_digits parameter specify the maximum number of digits to the right of the decimal point. (*)

(*) Because floating-point values are approximate and not stored as exact values, they cannot be treated as exact values in comparisons because it may lead to problems.

Text Types:

Data type

Description

CHAR(size)

This type can store up to 255 characters(*).

VARCHAR(size)

This type is similar to the CHAR type in which it can store up to 255 characters(*). The difference is that if we try to store more than 255 characters, the type is changed from VARCHAR to TEXT automatically.

TINYTEXT

This type can store up to 255 characters(*).

TEXT

This type can store up to 65,535 characters(*).

LONGTEXT

This type can store up to 4,294,967,295 characters(*).

MEDIUMTEXT

This type can store up to 16,777,215 characters(*).

BLOB

The BLOB (Binary Large Objects) type can store up to 65,535 bytes of data.

MEDIUMBLOB

The BLOB (Binary Large Objects) type can store up to 16,777,215 bytes of data.

LONGBLOB

The BLOB (Binary Large Objects) type can store up to 4,294,967,295 bytes of data.

ENUM(x,y,z,etc.)

This type store a list of possible values (up to 65535 values). These values are stored in the order you enter them. If any value intended to be insert in this column is not listed in the ENUM list a blank value will be inserted.

SET

This type can holds up to 64 items. The SET type is similar to ENUM with the exception that it can store more than one choic

(*) These characters can be numbers, letters and special characters.

Date Types:

Data type

Description

DATE()

Store a date in the following format: YYYY-MM-DD(*).

DATETIME()

Store date and time in the following format: YYYY-MM-DD HH:MM:SS(*).

TIMESTAMP()

Store a timestamp as the number of seconds since the Unix epoch (‘1970-01-01 00:00:00’ UTC) following the format: YYYY-MM-DD HH:MM:SS. The timestamp goes from from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC

TIME()

Store a time in the following format HH:MM:SS. The range of time that can be store goes from ‘-838:59:59’ to ‘838:59:59’.

YEAR()

Store a year in two-digit or four-digit format. When the values are stored in a two-digit format, they goes from 70 to 69, representing from 1970 to 2069. When the values are stored in a four-digit format, they represent from 1970 to 2069.

(*) The supported range goes from ‘1000-01-01’ to ‘9999-12-31’

 

| (MySQL Tutorial – Part 2) Next >

© 2012, Alejandro G. Carlstein Ramos Mejia. All rights reserved.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*

Click to Insert Smiley

SmileBig SmileGrinLaughFrownBig FrownCryNeutralWinkKissRazzChicCoolAngryReally AngryConfusedQuestionThinkingPainShockYesNoLOLSillyBeautyLashesCuteShyBlushKissedIn LoveDroolGiggleSnickerHeh!SmirkWiltWeepIDKStruggleSide FrownDazedHypnotizedSweatEek!Roll EyesSarcasmDisdainSmugMoney MouthFoot in MouthShut MouthQuietShameBeat UpMeanEvil GrinGrit TeethShoutPissed OffReally PissedMad RazzDrunken RazzSickYawnSleepyDanceClapJumpHandshakeHigh FiveHug LeftHug RightKiss BlowKissingByeGo AwayCall MeOn the PhoneSecretMeetingWavingStopTime OutTalk to the HandLoserLyingDOH!Fingers CrossedWaitingSuspenseTremblePrayWorshipStarvingEatVictoryCurseAlienAngelClownCowboyCyclopsDevilDoctorFemale FighterMale FighterMohawkMusicNerdPartyPirateSkywalkerSnowmanSoldierVampireZombie KillerGhostSkeletonBunnyCatCat 2ChickChickenChicken 2CowCow 2DogDog 2DuckGoatHippoKoalaLionMonkeyMonkey 2MousePandaPigPig 2SheepSheep 2ReindeerSnailTigerTurtleBeerDrinkLiquorCoffeeCakePizzaWatermelonBowlPlateCanFemaleMaleHeartBroken HeartRoseDead RosePeaceYin YangUS FlagMoonStarSunCloudyRainThunderUmbrellaRainbowMusic NoteAirplaneCarIslandAnnouncebrbMailCellPhoneCameraFilmTVClockLampSearchCoinsComputerConsolePresentSoccerCloverPumpkinBombHammerKnifeHandcuffsPillPoopCigarette