0% found this document useful (0 votes)
127 views

Mysql Document

1) The document provides step-by-step instructions for installing MySQL on Windows and Linux systems. It describes downloading, extracting, and running the setup program on Windows, and using RPM files to install on Linux. 2) It also explains how to create a MySQL database called "employees" and grant access to a user account. Commands like "CREATE DATABASE" and "GRANT" are used. 3) Basic MySQL commands are demonstrated like "SHOW DATABASES" to view existing databases and "DESCRIBE" to view the structure of a table. The "employee_data" table that was created is described.

Uploaded by

Sandeep Boyina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

Mysql Document

1) The document provides step-by-step instructions for installing MySQL on Windows and Linux systems. It describes downloading, extracting, and running the setup program on Windows, and using RPM files to install on Linux. 2) It also explains how to create a MySQL database called "employees" and grant access to a user account. Commands like "CREATE DATABASE" and "GRANT" are used. 3) Basic MySQL commands are demonstrated like "SHOW DATABASES" to view existing databases and "DESCRIBE" to view the structure of a table. The "employee_data" table that was created is described.

Uploaded by

Sandeep Boyina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 60

Installing MySQL on Windows

Once you have successfully downloaded the Windows version, installing it is a breeze... trust me!
(The installation steps below have be tested on Win95 and Win98 using mysql-shareware-
3_22_34-win.zip

Create a temporary directory called mysqltem.

1. Unzip the file to this directory.


2. After unzipping is over, you'll find a file called "setup.exe".
3. Close all programs
4. Click on Start - Run and browse to the setup file in mysqltem.
5. Click "OK" to proceed
6. The setup program loads and guides you through the installation process.
7. Choose the "Typical" installation, unless you know what you want!
8. MySQL would be installed in c:\mysql (unless you specified some other directory).
9. Restart Windows.
10. Start an MS-DOS session and migrate to c:\mysql\bin
11. Now, type the following at the prompt:
12. mysqld-shareware --standalone
13. OR (in later versions)
14. mysqld

This starts the MySQL server.

15. Type "mysql" (without the quotes) at the DOS prompt.


16. The prompt is changed to the "mysql" prompt.
17. To test the MySQL server, type "show databases;" at the prompt.
18. This should display something like:
19. +----------------+
20. | Database |
21. +----------------+
22. | mysql |
23. | test |
24. +----------------+
25. 2 rows in set (0.00 sec)

If you see the above... congrats... you have sucessfully installed MySQL on your system.

26. Type "quit" at the mysql prompt.


27. You are now back to the MS-DOS prompt.
28. Since our work is done (for the time being), we should shut the MySQL server. Issue the
following command at the prompt.
29. mysqladmin -u root shutdown

Installing MySQL on Linux

It's simple to install MySQL on Linux using the RPM file.

Become the super user if you are working in your account. (Type "su" and the prompt and give
the root password).

Change to the directory that has the RPM download.

1. Type the following command at the prompt:


2. rpm -ivh "mysql_file_name.rpm"

Similarly you can also install the MySQL client and MySQL development RPMs if you've
downloaded them.
Alternatively, you can install the RPMs through GnoRPM (found under System).

3. Now we'll set a password for the root user. Issue the following at the prompt.
4. mysqladmin -u root password mysqldata

where mysqldata is the password for the root. (Change this to anything you like).

5. It is now time to test the programs. Typing the following at the prompt starts the mysql
client program.
6. mysql -u root -p

The system asks for the the password. Type the root password (mysqldata).
If you don't get the prompt for password, it might be because MySQL Server is not
running. To start the server, change to /etc/rc.d/init.d/ directory and issue the command
./mysql start (or mysql start depending on the value of the PATH variable on your system).
Now invoke mysql client program.

7. Once MySQL client is running, you should get the mysql> prompt. Type the following at
this prompt:
8. show databases;
9. You should now get a display similar to:
10. +----------------+
11. | Database |
12. +----------------+
13. | mysql |
14. | test |
15. +----------------+
16. 2 rows in set (0.00 sec)

MySQL database introduction:

The MySQL database package consists of the following:


The MySQL server: This is the heart of MySQL. You can consider it a program that
stores and manages your databases.
MySQL client programs: MySQL comes with many client programs. The one with
which we'll be dealing a lot is called mysql (note: smallcaps). This provides an interface
through which you can issue SQL statements and have the results displayed.
MySQL client Library: This can help you in writing client programs in C. (We won't be
taking about this in our tutorial).

Creating MySQL database on Windows system


1. Start the MySQL server by issuing the command mysqld-shareware --standalone at
the prompt in c:\mysql\bin. Refer the previous session Installing MySQL on Windows for
further details.
2. Now invoke the mysql client program by typing mysql at the prompt.
3. The prompt is changed to a mysql> prompt. Type:
4. create database employees;
(Note: The command ends with a semi-colon).

5. The MySQL server responds with something like:


6. Query OK, 1 row affected (0.00 sec)
7. This means that you have sucessfully created the database. Now, let's see how many
databases you have on your system. Issue the following command.
8. show databases;

The server responds with the list of databases.

+----------------+
| Database |
+----------------+
| employees |
| mysql |
| test |
+----------------+
3 rows in set (0.00 sec)

Here we have three databases, two created by MySQL during installation and our
employees database.

9. To come back to the DOS prompt, type quit at the mysql prompt.

Creating MySQL database on Linux system


1. I assume that you are working from your account and not the root. Start a terminal
session and become the superuser (Type su at the prompt and then enter the root
password).
2. Now we'll access the MySQL server. Type:
3. mysql -u root -p

The system prompts for the MySQL root password that you set up in Installing MySQL on
Linux. (Note: This is not the Linux root password but the MySQL root password). Enter
the password, which is not displayed for security reasons.
Once you are successfully logged in, the system prints a welcome message and displays
the mysql prompt ... something like

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 1 to server version: 3.22.32

Type 'help' for help.

mysql>
4. Now we are ready for creating the employees database. Issue the command:
5. create database employees;

(Note: The command ends with a semi-colon)

6. An important point to note is that this database is created by the root and so will not be
accessible to any other user unless permitted by the root. Thus, in order to use this database
from my account (called manish), I have to set the permissions by issuing the following
command:
7. GRANT ALL ON employees.* TO manish@localhost IDENTIFIED BY "eagle"

The above command grants my account (manish@localhost) all the permissions on


employees database and sets my password to eagle. You should replace manish with your
user name and choose an appropriate password.

8. Close the mysql session by typing quit at the prompt. Exit from superuser and come back
to your account. (Type exit).
9. To connect to MySQL from your account, type:
10. mysql -u user_name -p

Type in the password when prompted. (This password was set by the GRANTS ALL...
command above) . The system displays the welcome message once you have successfully
logged on to MySQL. Here is how your session should look like:

[manish@localhost manish]$ mysql -u manish -p


Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 3.22.32
Type 'help' for help.
mysql>
11. Typing the command SHOW DATABASES; will list all the databases available on the
system. You should get a display similar to:
12. mysql> SHOW DATABASES;
13. +----------------+
14. | Database |
15. +----------------+
16. | employees |
17. | mysql |
18. | test |
19. +----------------+
20. 3 rows in set (0.00 sec)
21. Enter quit at the mysql> prompt to come out of the mysql client program.

Creating tables
Once you've selected the employees database, issue the CREATE TABLE command at the mysql
prompt.
CREATE TABLE employee_data
(
emp_id int unsigned not null auto_increment primary key,
f_name varchar(20),
l_name varchar(20),
title varchar(30),
age int,
yos int,
salary int,
perks int,
email varchar(60)
);
Note: When you press the enter key after typing the first line, the mysql prompt changes to a ->.
This means that mysql understands that the command is not complete and prompts you for
additional statements. Remember, each mysql command ends with a semi-colon and each column
declaration is separated by a comma. Also, you can type the entire command on one line if you so
want.
You screen should look similar to:
mysql> CREATE TABLE employee_data
-> (
-> emp_id int unsigned not null auto_increment primary key,
-> f_name varchar(20),
-> l_name varchar(20),
-> title varchar(30),
-> age int,
-> yos int,
-> salary int,
-> perks int,
-> email varchar(60)
-> );
Query OK, 0 rows affected (0.01 sec)

MySQL tables

Now that we've created our employee_data table, let's check its listing.
Type SHOW TABLES; at the mysql prompt. This should present you with the following
display:

mysql> SHOW TABLES;


+---------------------+
| Tables in employees |
+---------------------+
| employee_data |
+---------------------+
1 row in set (0.00 sec)
Describing tables
MySQL provides up with a command that displays the column details of the tables.
Issue the following command at the mysql prompt:
DESCRIBE employee_data;
The display would be as follows:
mysql> DESCRIBE employee_data;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| emp_id | int(10) unsigned | | PRI | 0 | auto_increment |
| f_name | varchar(20) | YES | | NULL | |
| l_name | varchar(20) | YES | | NULL | |
| title | varchar(30) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
| yos | int(11) | YES | | NULL | |
| salary | int(11) | YES | | NULL | |
| perks | int(11) | YES | | NULL | |
| email | varchar(60) | YES | | NULL | |
+--------+------------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)

Inserting data

Inserting data into tables


The INSERT SQL statement impregnates our table with data. Here is a general form of
INSERT.
INSERT into table_name (column1, column2....)
values (value1, value2...);
where table_name is the name of the table into which we want to insert data; column1, column2
etc. are column names and value1, value2 etc. are values for the respective columns. This is quite
simple, isn't it?
The following statement inserts the first record in employee_data table.
INSERT INTO employee_data
(f_name, l_name, title, age, yos, salary, perks, email)
values
("Manish", "Sharma", "CEO", 28, 4, 200000,
50000, "[email protected]");
As with other MySQL statements, you can enter this command on one line or span it in multiple
lines.
Some important points:
The table name is employee_data
The values for columns f_name, l_name, title and email are text strings and surrounded
with quotes.
Values for age, yos, salary and perks are numbers (intergers) and without quotes.
You'll notice that we've inserted data in all columns except emp_id. This is because, we
leave this job to MySQL, which will check the column for the largest value, increment it
by one and insert the new value.

Once you type the above command correctly in the mysql client, it displays a success message.
mysql> INSERT INTO employee_data
-> (f_name, l_name, title, age, yos, salary, perks, email)
-> values
-> ("Manish", "Sharma", "CEO", 28, 4, 200000,
-> 50000, "[email protected]");
Query OK, 1 row affected (0.00 sec)

Querying tables

Our employee_data table now contains enough data for us to work with. Let us see how we
can extract (query) it. Querying involves the use of the MySQL SELECT command.
Data is extracted from the table using the SELECT SQL command. Here is the format of a
SELECT statement:
SELECT column_names from table_name [WHERE ...conditions];
The conditions part of the statement is optional (we'll go through this later). Basically, you require
to know the column names and the table name from which to extract the data.
For example, in order to extract the first and last names of all employees, issue the following
command.
SELECT f_name, l_name from employee_data;
The statement tells MySQL to list all the rows from columns f_name and l_name.
mysql> SELECT f_name, l_name from employee_data;
+---------+------------+
| f_name | l_name |
+---------+------------+
| Manish | Sharma |
| John | Hagan |
| Ganesh | Pillai |
| Anamika | Pandit |
| Mary | Anchor |
| Fred | Kruger |
| John | MacFarland |
| Edward | Sakamuro |
| Alok | Nanda |
| Hassan | Rajabi |
| Paul | Simon |
| Arthur | Hoopla |
| Kim | Hunter |
| Roger | Lewis |
| Danny | Gibson |
| Mike | Harper |
| Monica | Sehgal |
| Hal | Simlai |
| Joseph | Irvine |
| Shahida | Ali |
| Peter | Champion |
+---------+------------+
21 rows in set (0.00 sec)
On close examination, you'll find that the display is in the order in which the data was inserted.
Furthermore, the last line indicates the number of rows our table has (21).
To display the entire table, we can either enter all the column names or use a simpler form of the
SELECT statement.
SELECT * from employee_data;
Another example
SELECT f_name, l_name, age from employee_data;
Selecting f_name, l_name and age columns would display something like:
mysql> SELECT f_name, l_name, age from employee_data;
+---------+------------+------+
| f_name | l_name | age |
+---------+------------+------+
| Manish | Sharma | 28 |
| John | Hagan | 32 |
| Ganesh | Pillai | 32 |
| Anamika | Pandit | 27 |
| Mary | Anchor | 26 |
| Fred | Kruger | 31 |
| John | MacFarland | 34 |
| Edward | Sakamuro | 25 |
| Alok | Nanda | 32 |
| Hassan | Rajabi | 33 |
| Paul | Simon | 43 |
| Arthur | Hoopla | 32 |
| Kim | Hunter | 32 |
| Roger | Lewis | 35 |
| Danny | Gibson | 34 |
| Mike | Harper | 36 |
| Monica | Sehgal | 30 |
| Hal | Simlai | 27 |
| Joseph | Irvine | 27 |
| Shahida | Ali | 32 |
| Peter | Champion | 36 |
+---------+------------+------+
21 rows in set (0.00 sec)

selecting data using conditions

In this section of the MySQL tutorial we'll look at the format of a SELECT statement we met in
the last session in detail. We will learn how to use the select statement using the WHERE clause.
SELECT column_names from table_name [WHERE ...conditions];
Now, we know that the conditions are optional (we've seen several examples in the last session...
and you would have encountered them in the assignments too).
The SELECT statement without conditions lists all the data in the specified columns. The strength
of RDBMS lies in letting you retrieve data based on certain specified conditions.
In this session we'll look at the SQL Comparision Operators.

The = and != comparision operators


SELECT f_name, l_name from employee_data where f_name = 'John';

+--------+------------+
| f_name | l_name |
+--------+------------+
| John | Hagan |
| John | MacFarland |
+--------+------------+
2 rows in set (0.00 sec)
This displays the first and last names of all employees whose first names are John. Note that the
word John in the condition is surrounded by single quotes. You can also use double quotes. The
quotes are important since MySQL will throw an error if they are missing. Also, MySQL
comparisions are case insensitive; which means "john", "John" or even "JoHn" would work!
SELECT f_name,l_name from employee_data where title="Programmer";

+--------+------------+
| f_name | l_name |
+--------+------------+
| Fred | Kruger |
| John | MacFarland |
| Edward | Sakamuro |
| Alok | Nanda |
+--------+------------+
4 rows in set (0.00 sec)

Selects the first and last names of all employees who are programmers.
SELECT f_name, l_name from employee_data where age = 32;
+---------+--------+
| f_name | l_name |
+---------+--------+
| John | Hagan |
| Ganesh | Pillai |
| Alok | Nanda |
| Arthur | Hoopla |
| Kim | Hunter |
| Shahida | Ali |
+---------+--------+
6 rows in set (0.00 sec)

This lists the first and last names of all empoyees 32 years of age. Remember that the column
type of age was int, hence it's not necessary to surround 32 with quotes. This is a subtle difference
between text and integer column types.
The != means 'not equal to' and is the opposite of the equality operator.

The greater than and lesser than operators


Okay, let's retrieve the first names of all employees who are older than 32.
SELECT f_name, l_name from employee_data where age > 32;
+--------+------------+
| f_name | l_name |
+--------+------------+
| John | MacFarland |
| Hassan | Rajabi |
| Paul | Simon |
| Roger | Lewis |
| Danny | Gibson |
| Mike | Harper |
| Peter | Champion |
+--------+------------+
7 rows in set (0.00 sec)
How about employees who draw more than $120000 as salary...
SELECT f_name, l_name from employee_data where salary > 120000;
+--------+--------+
| f_name | l_name |
+--------+--------+
| Manish | Sharma |
+--------+--------+
1 row in set (0.00 sec)
Now, let's list all employees who have had less than 3 years of service in the company.
SELECT f_name, l_name from employee_data where yos < 3;
+--------+----------+
| f_name | l_name |
+--------+----------+
| Mary | Anchor |
| Edward | Sakamuro |
| Paul | Simon |
| Arthur | Hoopla |
| Kim | Hunter |
| Roger | Lewis |
| Danny | Gibson |
| Mike | Harper |
| Hal | Simlai |
| Joseph | Irvine |
+--------+----------+
10 rows in set (0.00 sec)

The <= and >= operators


Used primarily with integer data, the less than equal (<=) and greater than equal (>=)operators
provide additional functionality.
select f_name, l_name, age, salary
from employee_data where age >= 33;

+--------+------------+------+--------+
| f_name | l_name | age | salary |
+--------+------------+------+--------+
| John | MacFarland | 34 | 80000 |
| Hassan | Rajabi | 33 | 90000 |
| Paul | Simon | 43 | 85000 |
| Roger | Lewis | 35 | 100000 |
| Danny | Gibson | 34 | 90000 |
| Mike | Harper | 36 | 120000 |
| Peter | Champion | 36 | 120000 |
+--------+------------+------+--------+
7 rows in set (0.00 sec)
Selects the names, ages and salaries of employees who are more than or equal to 33 years of age..
select f_name, l_name from employee_data where yos <= 2;
+--------+----------+
| f_name | l_name |
+--------+----------+
| Mary | Anchor |
| Edward | Sakamuro |
| Paul | Simon |
| Arthur | Hoopla |
| Kim | Hunter |
| Roger | Lewis |
| Danny | Gibson |
| Mike | Harper |
| Hal | Simlai |
| Joseph | Irvine |
+--------+----------+
10 rows in set (0.00 sec)
Displays employee names who have less than or equal to 2 years of service in the company.

Pattern Matching with text data

We will now learn at how to match text patterns using the where clause and the LIKE operator in
this section of the MySQL reference guide.
The equal to(=) comparision operator helps is selecting strings that are identical. Thus, to list the
names of employees whose first names are John, we can use the following SELECT statement.
select f_name, l_name from employee_data where f_name = "John";
+--------+------------+
| f_name | l_name |
+--------+------------+
| John | Hagan |
| John | MacFarland |
+--------+------------+
2 rows in set (0.00 sec)

What if we wanted to display employees whose first names begin with the alphabet J?
SQL allows for some pattern matching with string data. Here is how it works.
select f_name, l_name from employee_data where f_name LIKE "J%";

+--------+------------+
| f_name | l_name |
+--------+------------+
| John | Hagan |
| John | MacFarland |
| Joseph | Irvine |
+--------+------------+
3 rows in set (0.00 sec)
You'll notice that we've replaced the Equal To sign with LIKE and we've used a percentage sign
(%) in the condition.
The % sign functions as a wildcard (similar to the usage of * in DOS and Linux systems). It
signifies any character. Thus, "J%" means all strings that begin with the alphabet J.
Similarly "%S" selects strings that end with S and "%H%", strings that contain the alphabet H.
Okay, let's list all the employees that have Senior in their titles.
select f_name, l_name, title from employee_data
where title like '%senior%';

+--------+--------+----------------------------+
| f_name | l_name | title |
+--------+--------+----------------------------+
| John | Hagan | Senior Programmer |
| Ganesh | Pillai | Senior Programmer |
| Kim | Hunter | Senior Web Designer |
| Mike | Harper | Senior Marketing Executive |
+--------+--------+----------------------------+
4 rows in set (0.00 sec)

Listing all employees whose last names end with A is very simple
mysql> select f_name, l_name from employee_data
where l_name like '%a';

+--------+--------+
| f_name | l_name |
+--------+--------+
| Manish | Sharma |
| Alok | Nanda |
| Arthur | Hoopla |
+--------+--------+
3 rows in set (0.00 sec)

Logical Operators

In this section of the SQL primer we look at how to select data based on certain conditions
presented through MySQL logical operators.
SQL conditions can also contain Boolean (logical) operators. They are
1). AND
2). OR
3). NOT
Their usage is quite simple. Here is a SELECT statement that lists the names of employees who
draw more than $70000 but less than $90000.
SELECT f_name, l_name from employee_data
where salary > 70000 AND salary < 90000;

+--------+------------+
| f_name | l_name |
+--------+------------+
| Mary | Anchor |
| Fred | Kruger |
| John | MacFarland |
| Edward | Sakamuro |
| Paul | Simon |
| Arthur | Hoopla |
| Joseph | Irvine |
+--------+------------+
7 rows in set (0.00 sec)

Let's display the last names of employees whose last names start with the alphabet S or A.
SELECT l_name from employee_data where
l_name like 'S%' OR l_name like 'A%';

+----------+
| l_name |
+----------+
| Sharma |
| Anchor |
| Sakamuro |
| Simon |
| Sehgal |
| Simlai |
| Ali |
+----------+
7 rows in set (0.00 sec)

Okay here is a more complex example... listing the names and ages of employees whose last
names begin with S or P and who are less than 30 years of age.
SELECT f_name, l_name , age from employee_data
where (l_name like 'S%' OR l_name like 'A%') AND
age < 30;

+--------+----------+------+
| f_name | l_name | age |
+--------+----------+------+
| Manish | Sharma | 28 |
| Mary | Anchor | 26 |
| Edward | Sakamuro | 25 |
| Hal | Simlai | 27 |
+--------+----------+------+
4 rows in set (0.00 sec)

Note the usage of parenthesis in the statement above. The parenthesis are meant to separate the
various logical conditions and remove any abiguity.
The NOT operator helps in listing all non programmers. (Programmers include Senior
programmers, Multimedia Programmers and Programmers).
SELECT f_name, l_name, title from employee_data
where title NOT LIKE "%programmer%";

+---------+----------+----------------------------+
| f_name | l_name | title |
+---------+----------+----------------------------+
| Manish | Sharma | CEO |
| Anamika | Pandit | Web Designer |
| Mary | Anchor | Web Designer |
| Kim | Hunter | Senior Web Designer |
| Roger | Lewis | System Administrator |
| Danny | Gibson | System Administrator |
| Mike | Harper | Senior Marketing Executive |
| Monica | Sehgal | Marketing Executive |
| Hal | Simlai | Marketing Executive |
| Joseph | Irvine | Marketing Executive |
| Shahida | Ali | Customer Service Manager |
| Peter | Champion | Finance Manager |
+---------+----------+----------------------------+
12 rows in set (0.00 sec)
A final example before we proceed to the assignments.
Displaying all employees with more than 3 years or service and more than 30 years of age.
select f_name, l_name from employee_data
where yos > 3 AND age > 30;

+--------+------------+
| f_name | l_name |
+--------+------------+
| John | Hagan |
| Ganesh | Pillai |
| John | MacFarland |
| Peter | Champion |
+--------+------------+
4 rows in set (0.00 sec)

IN and BETWEEN

This section of the tutorial MySQL looks at the In and BETWEEN operators.
To list employees who are Web Designers and System Administrators, we use a SELECT
statement as
SELECT f_name, l_name, title from
-> employee_data where
-> title = 'Web Designer' OR
-> title = 'System Administrator';

+---------+--------+----------------------+
| f_name | l_name | title |
+---------+--------+----------------------+
| Anamika | Pandit | Web Designer |
| Mary | Anchor | Web Designer |
| Roger | Lewis | System Administrator |
| Danny | Gibson | System Administrator |
+---------+--------+----------------------+
4 rows in set (0.01 sec)
SQL also provides an easier method with IN. Its usage is quite simple.
SELECT f_name, l_name, title from
-> employee_data where title
-> IN ('Web Designer', 'System Administrator');

+---------+--------+----------------------+
| f_name | l_name | title |
+---------+--------+----------------------+
| Anamika | Pandit | Web Designer |
| Mary | Anchor | Web Designer |
| Roger | Lewis | System Administrator |
| Danny | Gibson | System Administrator |
+---------+--------+----------------------+
4 rows in set (0.00 sec)

Suffixing NOT to IN will display data that is NOT found IN the condition. The following lists
employees who hold titles other than Programmer and Marketing Executive.
SELECT f_name, l_name, title from
-> employee_data where title NOT IN
-> ('Programmer', 'Marketing Executive');

+---------+----------+----------------------------+
| f_name | l_name | title |
+---------+----------+----------------------------+
| Manish | Sharma | CEO |
| John | Hagan | Senior Programmer |
| Ganesh | Pillai | Senior Programmer |
| Anamika | Pandit | Web Designer |
| Mary | Anchor | Web Designer |
| Hassan | Rajabi | Multimedia Programmer |
| Paul | Simon | Multimedia Programmer |
| Arthur | Hoopla | Multimedia Programmer |
| Kim | Hunter | Senior Web Designer |
| Roger | Lewis | System Administrator |
| Danny | Gibson | System Administrator |
| Mike | Harper | Senior Marketing Executive |
| Shahida | Ali | Customer Service Manager |
| Peter | Champion | Finance Manager |
+---------+----------+----------------------------+
14 rows in set (0.00 sec)
BETWEEN is employed to specify integer ranges. Thus instead of age >= 32 AND age <= 40, we
can use age BETWEEN 32 and 40.
select f_name, l_name, age from
-> employee_data where age BETWEEN
-> 32 AND 40;

+---------+------------+------+
| f_name | l_name | age |
+---------+------------+------+
| John | Hagan | 32 |
| Ganesh | Pillai | 32 |
| John | MacFarland | 34 |
| Alok | Nanda | 32 |
| Hassan | Rajabi | 33 |
| Arthur | Hoopla | 32 |
| Kim | Hunter | 32 |
| Roger | Lewis | 35 |
| Danny | Gibson | 34 |
| Mike | Harper | 36 |
| Shahida | Ali | 32 |
| Peter | Champion | 36 |
+---------+------------+------+
12 rows in set (0.00 sec)

You can use NOT with BETWEEN as in the following statement that lists employees who draw
salaries less than $90000 and more than $150000.
select f_name, l_name, salary
-> from employee_data where salary
-> NOT BETWEEN
-> 90000 AND 150000;

+---------+------------+--------+
| f_name | l_name | salary |
+---------+------------+--------+
| Manish | Sharma | 200000 |
| Mary | Anchor | 85000 |
| Fred | Kruger | 75000 |
| John | MacFarland | 80000 |
| Edward | Sakamuro | 75000 |
| Alok | Nanda | 70000 |
| Paul | Simon | 85000 |
| Arthur | Hoopla | 75000 |
| Hal | Simlai | 70000 |
| Joseph | Irvine | 72000 |
| Shahida | Ali | 70000 |
+---------+------------+--------+
11 rows in set (0.00 sec)

Ordering data

This section of the online MySQL tutorial looks at how we can change the display order of the
data extracted from MySQL tables using the ORDER BY clause of the SELECT statement.
The data that we have retrieved so far was always displayed in the order in which it was stored in
the table. Actually, SQL allows for sorting of retrieved data with the ORDER BY clause. This
clause requires the column name based on which the data will be sorted. Let's see how to display
employee names with last names sorted alphabetically (in ascending order).
SELECT l_name, f_name from
employee_data ORDER BY l_name;

+------------+---------+
| l_name | f_name |
+------------+---------+
| Ali | Shahida |
| Anchor | Mary |
| Champion | Peter |
| Gibson | Danny |
| Hagan | John |
| Harper | Mike |
| Hoopla | Arthur |
| Hunter | Kim |
| Irvine | Joseph |
| Kruger | Fred |
| Lewis | Roger |
| MacFarland | John |
| Nanda | Alok |
| Pandit | Anamika |
| Pillai | Ganesh |
| Rajabi | Hassan |
| Sakamuro | Edward |
| Sehgal | Monica |
| Sharma | Manish |
| Simlai | Hal |
| Simon | Paul |
+------------+---------+
21 rows in set (0.00 sec)

Here are employees sorted by age.


SELECT f_name, l_name, age
from employee_data
ORDER BY age;

+---------+------------+------+
| f_name | l_name | age |
+---------+------------+------+
| Edward | Sakamuro | 25 |
| Mary | Anchor | 26 |
| Anamika | Pandit | 27 |
| Hal | Simlai | 27 |
| Joseph | Irvine | 27 |
| Manish | Sharma | 28 |
| Monica | Sehgal | 30 |
| Fred | Kruger | 31 |
| John | Hagan | 32 |
| Ganesh | Pillai | 32 |
| Alok | Nanda | 32 |
| Arthur | Hoopla | 32 |
| Kim | Hunter | 32 |
| Shahida | Ali | 32 |
| Hassan | Rajabi | 33 |
| John | MacFarland | 34 |
| Danny | Gibson | 34 |
| Roger | Lewis | 35 |
| Mike | Harper | 36 |
| Peter | Champion | 36 |
| Paul | Simon | 43 |
+---------+------------+------+
21 rows in set (0.00 sec)
The ORDER BY clause can sort in an ASCENDING (ASC) or DESCENDING (DESC) order
depending upon the argument supplied.
To list employee first names in descending order, we'll use the statement below.
SELECT f_name from employee_data
ORDER by f_name DESC;

+---------+
| f_name |
+---------+
| Shahida |
| Roger |
| Peter |
| Paul |
| Monica |
| Mike |
| Mary |
| Manish |
| Kim |
| Joseph |
| John |
| John |
| Hassan |
| Hal |
| Ganesh |
| Fred |
| Edward |
| Danny |
| Arthur |
| Anamika |
| Alok |
+---------+
21 rows in set (0.00 sec)

Note: The ascending (ASC) order is the default.

Limiting data retrieval

This section of the online MySQL lesson looks at how to limit the number of records displayed
by the SELECT statement.
As your tables grow, you'll find a need to display only a subset of data. This can be achieved with
the LIMIT clause.
For example, to list only the names of first 5 employees in our table, we use LIMIT with 5 as
argument.
SELECT f_name, l_name from
employee_data LIMIT 5;
+---------+--------+
| f_name | l_name |
+---------+--------+
| Manish | Sharma |
| John | Hagan |
| Ganesh | Pillai |
| Anamika | Pandit |
| Mary | Anchor |
+---------+--------+
5 rows in set (0.01 sec)

These are the first five entries in our table.


You can couple LIMIT with ORDER BY. Thus, the following displays the 4 senior most
employees.
SELECT f_name, l_name, age from
employee_data ORDER BY age DESC
LIMIT 4;

+--------+----------+------+
| f_name | l_name | age |
+--------+----------+------+
| Paul | Simon | 43 |
| Mike | Harper | 36 |
| Peter | Champion | 36 |
| Roger | Lewis | 35 |
+--------+----------+------+
4 rows in set (0.00 sec)

Cool, yeh?
Similarly, we can list the two youngest employees.
SELECT f_name, l_name, age from
employee_data ORDER BY age
LIMIT 2;
+--------+----------+------+
| f_name | l_name | age |
+--------+----------+------+
| Edward | Sakamuro | 25 |
| Mary | Anchor | 26 |
+--------+----------+------+
2 rows in set (0.01 sec)

Extracting Subsets
Limit can also be used to extract a subset of data by providing an additional argument.
The general form of this LIMIT is:
SELECT (whatever) from table LIMIT starting row, Number to extract;
SELECT f_name, l_name from
employee_data LIMIT 6,3;

+--------+------------+
| f_name | l_name |
+--------+------------+
| John | MacFarland |
| Edward | Sakamuro |
| Alok | Nanda |
+--------+------------+
3 rows in set (0.00 sec)

This extracts 3 rows starting from the sixth row.

DISTINCT keyword

In this section of the online MySQL guide, we will look at how to select and display records from
MySQL tables using the DISTINCT keyword that eliminates the occurences of the same data.
To list all titles in our company database, we can throw a statement as:
select title from employee_data;
+----------------------------+
| title |
+----------------------------+
| CEO |
| Senior Programmer |
| Senior Programmer |
| Web Designer |
| Web Designer |
| Programmer |
| Programmer |
| Programmer |
| Programmer |
| Multimedia Programmer |
| Multimedia Programmer |
| Multimedia Programmer |
| Senior Web Designer |
| System Administrator |
| System Administrator |
| Senior Marketing Executive |
| Marketing Executive |
| Marketing Executive |
| Marketing Executive |
| Customer Service Manager |
| Finance Manager |
+----------------------------+
21 rows in set (0.00 sec)

You'll notice that the display contains multiple occurences of certain data. The SQL DISTINCT
clause lists only unique data. Here is how you use it.
select DISTINCT title from employee_data;

+----------------------------+
| title |
+----------------------------+
| CEO |
| Customer Service Manager |
| Finance Manager |
| Marketing Executive |
| Multimedia Programmer |
| Programmer |
| Senior Marketing Executive |
| Senior Programmer |
| Senior Web Designer |
| System Administrator |
| Web Designer |
+----------------------------+
11 rows in set (0.00 sec)

This shows we have 11 unique titles in the company.


Also, you can sort the unique entries using ORDER BY.
select DISTINCT age from employee_data
ORDER BY age;

+------+
| age |
+------+
| 25 |
| 26 |
| 27 |
| 28 |
| 30 |
| 31 |
| 32 |
| 33 |
| 34 |
| 35 |
| 36 |
| 43 |
+------+
12 rows in set (0.00 sec)

DISTINCT is often used with the COUNT aggregate function, which we'll meet in later sessions.

Finding the minimum and maximum values

MySQL provides inbuilt functions to find the minimum and maximum values.
SQL provides 5 aggregate functions. They are:
1). MIN(): Minimum value
2). MAX(): Maximum value
3). SUM(): The sum of values
4). AVG(): The average values
5). COUNT(): Counts the number of entries.
In this session of the online MySQL course, we'll look at finding the minimum and maximum
values in a column.

Minimum value
select MIN(salary) from employee_data;

+-------------+
| MIN(salary) |
+-------------+
| 70000 |
+-------------+
1 row in set (0.00 sec)

Maximum value
select MAX(salary) from employee_data;

+-------------+
| MAX(salary) |
+-------------+
| 200000 |
+-------------+
1 row in set (0.00 sec)

Finding the average and sum

Totalling column values with SUM

The SUM() aggregate function calculates the total of values in a column. You require to give the
column name, which should be placed inside parenthesis.
Let's see how much Bignet spends on salaries.

select SUM(salary) from employee_data;

+-------------+
| SUM(salary) |
+-------------+
| 1997000 |
+-------------+
1 row in set (0.00 sec)

SImilarly, we can display the total perks given to employees.


select SUM(perks) from employee_data;

+------------+
| SUM(perks) |
+------------+
| 390000 |
+------------+
1 row in set (0.00 sec)

How about finding the total of salaries and perks?


select sum(salary) + sum(perks) from employee_data;
+-------------------------+
| sum(salary)+ sum(perks) |
+-------------------------+
| 2387000 |
+-------------------------+
1 row in set (0.01 sec)

This shows a hidden gem of the SELECT command. You can add, subtract, multiply or divide
values. Actually, you can write full blown arithemetic expressions. Cool!

Finding Averages
The AVG() aggregate function is employed for calculating averages of data in columns.
select avg(age) from employee_data;
+----------+
| avg(age) |
+----------+
| 31.6190 |
+----------+
1 row in set (0.00 sec)

This displays the average age of employees in Bignet and the following displays the average
salary.
select avg(salary) from employee_data;
+-------------+
| avg(salary) |
+-------------+
| 95095.2381 |
+-------------+
1 row in set (0.00 sec)

Count

The COUNT() aggregate functions counts and displays the total number of entries. For example,
to count the total number of entries in the table, issue the command below.
select COUNT(*) from employee_data;

+----------+
| COUNT(*) |
+----------+
| 21 |
+----------+
1 row in set (0.00 sec)
As you have learnt, the * sign means "all data"
Now, let's count the total number of employees who hold the "Programmer" title.
select COUNT(*) from employee_data
where title = 'Programmer';
+----------+
| COUNT(*) |
+----------+
| 4|
+----------+
1 row in set (0.01 sec)

The GROUP BY clause


The GROUP BY clause allows us to group similar data. Thus, to list all unique titles in our table
we can issue
select title from employee_data
GROUP BY title;

+----------------------------+
| title |
+----------------------------+
| CEO |
| Customer Service Manager |
| Finance Manager |
| Marketing Executive |
| Multimedia Programmer |
| Programmer |
| Senior Marketing Executive |
| Senior Programmer |
| Senior Web Designer |
| System Administrator |
| Web Designer |
+----------------------------+
11 rows in set (0.01 sec)

You'll notice that this is similar to the usage of DISTINCT, which we encountered in a previous
session.
Okay, here is how you can count the number of employees with different titles.
select title, count(*)
from employee_data GROUP BY title;

+----------------------------+----------+
| title | count(*) |
+----------------------------+----------+
| CEO | 1|
| Customer Service Manager | 1|
| Finance Manager | 1|
| Marketing Executive | 3|
| Multimedia Programmer | 3|
| Programmer | 4|
| Senior Marketing Executive | 1|
| Senior Programmer | 2|
| Senior Web Designer | 1|
| System Administrator | 2|
| Web Designer | 2|
+----------------------------+----------+
11 rows in set (0.00 sec)

For the command above, MySQL first groups different titles and then executes count on each
group.
Sorting the data
Now, let's find and list the number of employees holding different titles and sort them using
ORDER BY.
select title, count(*) AS Number
from employee_data
GROUP BY title
ORDER BY Number;

+----------------------------+--------+
| title | Number |
+----------------------------+--------+
| CEO | 1|
| Customer Service Manager | 1|
| Finance Manager | 1|
| Senior Marketing Executive | 1|
| Senior Web Designer | 1|
| Senior Programmer | 2|
| System Administrator | 2|
| Web Designer | 2|
| Marketing Executive | 3|
| Multimedia Programmer | 3|
| Programmer | 4|
+----------------------------+--------+
11 rows in set (0.00 sec)

HAVING clause

To list the average salary of employees in different departments (titles), we use the GROUP BY
clause, as in:
select title, AVG(salary)
from employee_data
GROUP BY title;

+----------------------------+-------------+
| title | AVG(salary) |
+----------------------------+-------------+
| CEO | 200000.0000 |
| Customer Service Manager | 70000.0000 |
| Finance Manager | 120000.0000 |
| Marketing Executive | 77333.3333 |
| Multimedia Programmer | 83333.3333 |
| Programmer | 75000.0000 |
| Senior Marketing Executive | 120000.0000 |
| Senior Programmer | 115000.0000 |
| Senior Web Designer | 110000.0000 |
| System Administrator | 95000.0000 |
| Web Designer | 87500.0000 |
+----------------------------+-------------+
11 rows in set (0.00 sec)

Now, suppose you want to list only the departments where the average salary is more than
$100000, you can't do it, even if you assign a pseudo name to AVG(salary) column. Here, the

HAVING clause comes to our rescue.


select title, AVG(salary)
from employee_data
GROUP BY title
HAVING AVG(salary) > 100000;

+----------------------------+-------------+
| title | AVG(salary) |
+----------------------------+-------------+
| CEO | 200000.0000 |
| Finance Manager | 120000.0000 |
| Senior Marketing Executive | 120000.0000 |
| Senior Programmer | 115000.0000 |
| Senior Web Designer | 110000.0000 |
+----------------------------+-------------+
5 rows in set (0.00 sec)

SELECT statement

The MySQL SELECT command is something like a print or write command of other languages.
You can ask it to display text strings, numeric data, the results of mathematical expressions etc.
Displaying the MySQL version number
select version();

+-----------+
| version() |
+-----------+
| 3.22.32 |
+-----------+
1 row in set (0.00 sec)

Displaying the current date and time


select now();

+---------------------+
| now() |
+---------------------+
| 2001-05-31 00:36:24 |
+---------------------+
1 row in set (0.00 sec)

Displaying the current Day, Month and Year


SELECT DAYOFMONTH(CURRENT_DATE);
+--------------------------+
| DAYOFMONTH(CURRENT_DATE) |
+--------------------------+
| 28 |
+--------------------------+
1 row in set (0.01 sec)
SELECT MONTH(CURRENT_DATE);
+---------------------+
| MONTH(CURRENT_DATE) |
+---------------------+
| 1|
+---------------------+
1 row in set (0.00 sec)

SELECT YEAR(CURRENT_DATE);
+--------------------+
| YEAR(CURRENT_DATE) |
+--------------------+
| 2001 |
+--------------------+
1 row in set (0.00 sec)

Displaying text strings


select 'I Love MySQL';

+--------------+
| I Love MySQL |
+--------------+
| I Love MySQL |
+--------------+
1 row in set (0.00 sec)

Obviously you can provide pseudo names for these columns using AS.
select 'Manish Sharma' as Name;

+---------------+
| Name |
+---------------+
| Manish Sharma |
+---------------+
1 row in set (0.00 sec)

Evaluating expressions
select ((4 * 4) / 10 ) + 25;

+----------------------+
| ((4 * 4) / 10 ) + 25 |
+----------------------+
| 26.60 |
+----------------------+
1 row in set (0.00 sec)

Concatenating

With SELECT you can concatenate values for display. CONCAT accepts arguments between
parenthesis. These can be column names or plain text strings. Text strings have to be surrounded
with quotes (single or double).
SELECT CONCAT(f_name, " ", l_name)
from employee_data
where title = 'Programmer';

+-----------------------------+
| CONCAT(f_name, " ", l_name) |
+-----------------------------+
| Fred Kruger |
| John MacFarland |
| Edward Sakamuro |
| Alok Nanda |
+-----------------------------+
4 rows in set (0.00 sec)

You can also give descriptive names to these columns using AS.
select CONCAT(f_name, " ", l_name)
AS Name
from employee_data
where title = 'Marketing Executive';

+---------------+
| Name |
+---------------+
| Monica Sehgal |
| Hal Simlai |
| Joseph Irvine |
+---------------+
3 rows in set (0.00 sec)

Mathematical Functions

In addition to the four basic arithmetic operations addition (+), Subtraction (-), Multiplication (*)
and Division (/), MySQL also has the Modulo (%) operator. This calculates the remainder left
after division.
select 87 % 9;
+--------+
| 87 % 9 |
+--------+
| 6|
+--------+
1 row in set (0.00 sec)
MOD(x, y)
Displays the remainder of x divided by y, SImilar to the Modulus operator.
select MOD(37, 13);

+-------------+
| MOD(37, 13) |
+-------------+
| 11 |
+-------------+
1 row in set (0.00 sec)

ABS(x)
Calculates the Absolute value of number x. Thus, if x is negative its positive value is returned.
select ABS(-4.05022);
+---------------+
| ABS(-4.05022) |
+---------------+
| 4.05022 |
+---------------+
1 row in set (0.00 sec)

select ABS(4.05022);
+--------------+
| ABS(4.05022) |
+--------------+
| 4.05022 |
+--------------+
1 row in set (0.00 sec)

SIGN(x)
Returns 1, 0 or -1 when x is positive, zero or negative, respectively.
select SIGN(-34.22);
+--------------+
| SIGN(-34.22) |
+--------------+
| -1 |
+--------------+
1 row in set (0.00 sec)

select SIGN(54.6);
+------------+
| SIGN(54.6) |
+------------+
| 1|
+------------+
1 row in set (0.00 sec)

select SIGN(0);
+---------+
| SIGN(0) |
+---------+
| 0|
+---------+
1 row in set (0.00 sec)

POWER(x,y)
Calculates the value of x raised to the power of y.
select POWER(4,3);
+------------+
| POWER(4,3) |
+------------+
| 64.000000 |
+------------+
1 row in set (0.00 sec)

SQRT(x)
Calculates the square root of x.
select SQRT(3);
+----------+
| SQRT(3) |
+----------+
| 1.732051 |
+----------+
1 row in set (0.00 sec)
ROUND(x) and ROUND(x,y)
Returns the value of x rounded to the nearest integer. ROUND can also accept an additional
argument y that will round x to y decimal places.
select ROUND(14.492);
+---------------+
| ROUND(14.492) |
+---------------+
| 14 |
+---------------+
1 row in set (0.00 sec)

select ROUND(4.5002);
+---------------+
| ROUND(4.5002) |
+---------------+
| 5|
+---------------+
1 row in set (0.00 sec)

select ROUND(-12.773);
+----------------+
| ROUND(-12.773) |
+----------------+
| -13 |
+----------------+
1 row in set (0.00 sec)

select ROUND(7.235651, 3);


+--------------------+
| ROUND(7.235651, 3) |
+--------------------+
| 7.236 |
+--------------------+
1 row in set (0.00 sec)
FLOOR(x)
Returns the largest integer that is less than or equal to x.
select FLOOR(23.544);
+---------------+
| FLOOR(23.544) |
+---------------+
| 23 |
+---------------+
1 row in set (0.00 sec)

select FLOOR(-18.4);
+--------------+
| FLOOR(-18.4) |
+--------------+
| -19 |
+--------------+
1 row in set (0.00 sec)

CEILING(x)
Returns the smallest integer that is greater than or equal to x.
select CEILING(54.22);
+----------------+
| CEILING(54.22) |
+----------------+
| 55 |
+----------------+
1 row in set (0.00 sec)

select CEILING(-62.23);
+-----------------+
| CEILING(-62.23) |
+-----------------+
| -62 |
+-----------------+
1 row in set (0.00 sec)

TAN(x), SIN(x) and COS(x)


Calculate the trignometic ratios for angle x (measured in radians).
select SIN(0);
+----------+
| SIN(0) |
+----------+
| 0.000000 |
+----------+
1 row in set (0.00 sec)

Update

The SQL UPDATE command updates the data in tables. Its format is quite simple.
UPDATE table_name SET
column_name1 = value1,
column_name2 = value2,
column_name3 = value3 ...
[WHERE conditions];

Obviously, like other SQL commands, you can type in in one line or multiple lines.

Let's look at some examples.


Bignet has been doing good business, the CEO increases his salary by $20000 and perks by
$5000. His previous salary was $200000 and perks were $50000.
UPDATE employee_data SET
salary=220000, perks=55000
WHERE title='CEO';

Query OK, 1 row affected (0.02 sec)


Rows matched: 1 Changed: 1 Warnings: 0
You can test this out by listing the data in the table.
select salary, perks from
employee_data WHERE
title = 'CEO';

+--------+-------+
| salary | perks |
+--------+-------+
| 220000 | 55000 |
+--------+-------+
1 row in set (0.00 sec)

Actually, you don't need to know the previous salary explicitly. You can be cheeky and use
arithmetic operators. Thus, the following statement would have done the same job without us
knowing the original data beforehand.
UPDATE employee_data SET
salary = salary + 20000,
perks = perks + 5000
WHERE title='CEO';

Query OK, 1 row affected (0.01 sec)


Rows matched: 1 Changed: 1 Warnings: 0

Another progressive (???) step Bignet takes is changing the titles of Web Designer to Web
Developer.
mysql> update employee_data SET
-> title = 'Web Developer'
-> WHERE title = 'Web Designer';
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0

It's important that you take a long hard look at the condition part in the statement before
executing update, else you might update the wrong data. Also, an UPDATE statement without
conditions will update all the data in the column in all rows!
Be very caferul.

Date column

Till now we've dealt with text (varchar) and numbers (int) data types. To understand date type,
we'll create one more table.
Download employee_per.dat file below and follow the instructions. The file contain the CREATE
table command as well as the INSERT statements.
employee_per.dat
These instructions are a repeat of those in session 6 and 8.

Windows system
1). Move the file to c:\mysql\bin.
2). Issue the command at DOS prompt.
dosprompt> mysql employees <employee_per.dat
3). Start mysql client program and check if the table has been created using SHOW TABLES;
command.
Linux system

1). Move to the directory that contains the downloaded files.


2). At the prompt, type the command below:
$prompt> mysql employees <employee_per.dat -u your_username -p
3). Check if the table has been created through SHOW TABLES; command in mysql client
program.

Click here for viewing this new table, employee_per.


The details of the table can be displayed with DESCRIBE command.
mysql> DESCRIBE employee_per;

+------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| e_id | int(10) unsigned | | PRI | 0 | |
| address | varchar(60) | YES | | NULL | |
| phone | int(11) | YES | | NULL | |
| p_email | varchar(60) | YES | | NULL | |
| birth_date | date | YES | | NULL | |
| sex | enum('M','F') | YES | | NULL | |
| m_status | enum('Y','N') | YES | | NULL | |
| s_name | varchar(40) | YES | | NULL | |
| children | int(11) | YES | | NULL | |
+------------+------------------+------+-----+---------+-------+
9 rows in set (0.01 sec)
Notice that column birth_date has date as column type. I've also introduced another column type
ENUM, which we'll discuss later.
e-id: are employee ids, same as that in table employee_data
address: Addresses of employees
phone: Phone numbers
p_email: Personal email addresses
birth_date: Birth dates
sex: The sex of the employee, Male or Female
m_status: Marital status,Yes or No.
s_name: Name of Spouse (NULL if employee is unmarried)
children: Number of children (NULL if employee is unmarried)
Characteristics of Date
MySQL dates are ALWAYS represented with the year followed by the month and then the date.
Often you'll find dates written as YYYY-MM-DD, where YYYY is 4 digit year, MM is 2 digit
month and DD, 2 digit date. We'll look at DATE and related column types in the session on
column types.
Operations on Date
Date column type allow for several operations such as sorting, testing conditions using
comparision operators etc.
Using = and != operators
select p_email, phone
from employee_per
where birth_date = '1969-12-31';

+---------------------------+---------+
| p_email | phone |
+---------------------------+---------+
| [email protected] | 6666666 |
+---------------------------+---------+
1 row in set (0.00 sec)
Note: MySQL requires the dates to be enclosed in quotes.

Using >= and <= operators


select e_id, birth_date
from employee_per where
birth_date >= '1970-01-01';

+------+------------+
| e_id | birth_date |
+------+------------+
| 1 | 1972-03-16 |
| 4 | 1972-08-09 |
| 5 | 1974-10-13 |
| 8 | 1975-01-12 |
| 17 | 1970-04-18 |
| 18 | 1973-10-09 |
| 19 | 1973-01-20 |
+------+------------+
7 rows in set (0.00 sec)

Specifying ranges

select e_id, birth_date


from employee_per where
birth_date BETWEEN
'1969-01-01' AND '1974-01-01';

+------+------------+
| e_id | birth_date |
+------+------------+
| 1 | 1972-03-16 |
| 4 | 1972-08-09 |
| 6 | 1969-12-31 |
| 17 | 1970-04-18 |
| 18 | 1973-10-09 |
| 19 | 1973-01-20 |
+------+------------+
6 rows in set (0.00 sec)

select e_id, birth_date


from employee_per where
birth_date >= '1969-01-01'
AND birth_date <= '1974-01-01';

+------+------------+
| e_id | birth_date |
+------+------------+
| 1 | 1972-03-16 |
| 4 | 1972-08-09 |
| 6 | 1969-12-31 |
| 17 | 1970-04-18 |
| 18 | 1973-10-09 |
| 19 | 1973-01-20 |
+------+------------+
6 rows in set (0.00 sec)

Date column2
Using Date to sort data

select e_id, birth_date


from employee_per
ORDER BY birth_date;
+------+------------+
| e_id | birth_date |
+------+------------+
| 11 | 1957-11-04 |
| 16 | 1964-03-06 |
| 21 | 1964-06-13 |
| 14 | 1965-04-28 |
| 15 | 1966-06-23 |
| 7 | 1966-08-20 |
| 10 | 1967-07-06 |
| 20 | 1968-01-25 |
| 12 | 1968-02-15 |
| 2 | 1968-04-02 |
| 9 | 1968-05-19 |
| 13 | 1968-09-03 |
| 3 | 1968-09-22 |
| 6 | 1969-12-31 |
| 17 | 1970-04-18 |
| 1 | 1972-03-16 |
| 4 | 1972-08-09 |
| 19 | 1973-01-20 |
| 18 | 1973-10-09 |
| 5 | 1974-10-13 |
| 8 | 1975-01-12 |
+------+------------+

Selecting data using Dates


Here is how we can select employees born in March.
select e_id, birth_date
from employee_per
where MONTH(birth_date) = 3;

+------+------------+
| e_id | birth_date |
+------+------------+
| 1 | 1972-03-16 |
| 16 | 1964-03-06 |
+------+------------+
2 rows in set (0.00 sec)

Alternatively, we can use month names instead of numbers.


select e_id, birth_date
from employee_per
where MONTHNAME(birth_date) = 'January';

+------+------------+
| e_id | birth_date |
+------+------------+
| 8 | 1975-01-12 |
| 19 | 1973-01-20 |
| 20 | 1968-01-25 |
+------+------------+
3 rows in set (0.00 sec)

Be careful when using month names as they are case sensitive. Thus, January will work but
JANUARY will not!
Similarly, you can select employees born in a specific year or under specific dates.

select e_id, birth_date


from employee_per
where year(birth_date) = 1972;

+------+------------+
| e_id | birth_date |
+------+------------+
| 1 | 1972-03-16 |
| 4 | 1972-08-09 |
+------+------------+
2 rows in set (0.00 sec)
select e_id, birth_date
from employee_per
where DAYOFMONTH(birth_date) = 20;

+------+------------+
| e_id | birth_date |
+------+------------+
| 7 | 1966-08-20 |
| 19 | 1973-01-20 |
+------+------------+
2 rows in set (0.00 sec)

Current dates
We had seen in the session on SELECT statement (A little more on the SELECT statement) that
current date, month and year can be displayed with CURRENT_DATE argument to
DAYOFMONTH(), MONTH() and YEAR() clauses, respectively. The same can be used to select
data from tables.
select e_id, birth_date
from employee_per where
MONTH(birth_date) = MONTH(CURRENT_DATE);

+------+------------+
| e_id | birth_date |
+------+------------+
| 8 | 1975-01-12 |
| 19 | 1973-01-20 |
| 20 | 1968-01-25 |
+------+------------+
3 rows in set (0.00 sec)

Null column type


The NULL column type is special in many ways. To insert a NULL value, just leave the column
name from the INSERT statement. Columns have NULL as default unless specified by NOT
NULL. You can have null values for integers as well as text or binary data.
NULL cannot be compared using arithemetic operators. Comparisions for NULL take place with
IS NULL or IS NOT NULL.
select e_id, children
from employee_per
where children IS NOT NULL;

+------+----------+
| e_id | children |
+------+----------+
| 2| 3|
| 3| 2|
| 7| 3|
| 9| 1|
| 11 | 4|
| 12 | 3|
| 13 | 2|
| 15 | 3|
| 16 | 2|
| 17 | 1|
| 21 | 2|
+------+----------+
11 rows in set (0.00 sec)

The above lists ids and no. of children of all employees who have children.

Table joins

Till now, we've used SELECT to retrieve data from only one table. However, we can extract data
from two or more tables using a single SELECT statement.
The strength of RDBMS lies in allowing us to relate data from one table with data from another.
This correlation can only be made if atleast one column in the two tables contain related data.
In our example, the columns that contain related data are emp_id of employee_data and e_id of
employee_per.

Let's conduct a table join and extract the names (from employee_data) and spouse names (from
employee_per) of married employee.
select CONCAT(f_name, " ", l_name) AS Name,
s_name as 'Spouse Name' from
employee_data, employee_per
where m_status = 'Y' AND
emp_id = e_id;

+-----------------+-----------------+
| Name | Spouse Name |
+-----------------+-----------------+
| Manish Sharma | Anamika Sharma |
| John Hagan | Jane Donner |
| Ganesh Pillai | Sandhya Pillai |
| Anamika Sharma | Manish Sharma |
| John MacFarland | Mary Shelly |
| Alok Nanda | Manika Nanda |
| Paul Simon | Muriel Lovelace |
| Arthur Hoopla | Rina Brighton |
| Kim Hunter | Matt Shikari |
| Danny Gibson | Betty Cudly |
| Mike Harper | Stella Stevens |
| Monica Sehgal | Edgar Alan |
| Peter Champion | Ruby Richer |
+-----------------+-----------------+
13 rows in set (0.00 sec)

The FROM clause takes the names of the two tables from which we plan to extract data. Also, we
specify that data has to be retrieved for only those entries where the emp_id and e_id are same.
The names of columns in the two tables are unique. However, this may not true always, in which
case we can explicitly specify column names along with table name using the dot notation.
select CONCAT(employee_data.f_name, " ", employee_data.l_name)
AS Name, employee_per.s_name AS 'Spouse Name'
from employee_data, employee_per
where employee_per.m_status = 'Y'
AND employee_data.emp_id = employee_per.e_id;

+-----------------+-----------------+
| Name | Spouse Name |
+-----------------+-----------------+
| Manish Sharma | Anamika Sharma |
| John Hagan | Jane Donner |
| Ganesh Pillai | Sandhya Pillai |
| Anamika Sharma | Manish Sharma |
| John MacFarland | Mary Shelly |
| Alok Nanda | Manika Nanda |
| Paul Simon | Muriel Lovelace |
| Arthur Hoopla | Rina Brighton |
| Kim Hunter | Matt Shikari |
| Danny Gibson | Betty Cudly |
| Mike Harper | Stella Stevens |
| Monica Sehgal | Edgar Alan |
| Peter Champion | Ruby Richer |
+-----------------+-----------------+
13 rows in set (0.00 sec)

Delete

The SQL delete statement requires the table name and optional conditions.
DELETE from table_name [WHERE conditions];
NOTE: If you don't specify any conditions ALL THE DATA IN THE TABLE WILL BE
DELETED!!!
One of the Multimedia specialists 'Hasan Rajabi' (employee id 10) leaves the company. We'll
delete his entry.
DELETE from employee_data
WHERE emp_id = 10;
Query OK, 1 row affected (0.00 sec)

Dropping tables

To remove all entries from the table we can issue the DELETE statement without any conditions.
DELETE from employee_data;
Query OK, 0 rows affected (0.00 sec)

However, this does not delete the table. The table still remains, which you can check with SHOW
TABLES;
mysql> SHOW TABLES;
+---------------------+
| Tables in employees |
+---------------------+
| employee_data |
+---------------------+
1 rows in set (0.00 sec)

To delete the table, we issue a DROP table command.


DROP TABLE employee_data;
Query OK, 0 rows affected (0.01 sec)

Now, we won't get this table in SHOW TABLES; listing

Database Column Types


The three major types of column types used in MySQL are
1). Integer
2). Text
3). Date
Choosing a column data type is very important in order to achieve speed, effective storage and
retrieval. Hence, I've dedicated two sessions to this topic. Now, I'll be touching only the surface;
for a thorough explanation refer the resources in What Next? session.

Numeric Column Types

In addition to int (Integer data type), MySQL also has provision for floating-point and double
precision numbers. Each integer type can take also be UNSIGNED and/or AUTO_INCREMENT.
TINYINT: very small numbers; suitable for ages. Actually, we should have used this
data type for employee ages and number of children. Can store numbers between 0 to 255
if UNSIGNED clause is applied, else the range is between -128 to 127.
SMALLINT: Suitable for numbers between 0 to 65535 (UNSIGNED) or -32768 to
32767.
MEDIUMINT: 0 to 16777215 with UNSIGNED clause or -8388608 to 8388607.
INT: UNSIGNED integers fall between 0 to 4294967295 or -2147683648 to
2147683647.
BIGINT: Huge numbers. (-9223372036854775808 to 9223372036854775807)
FLOAT: Floating point numbers (single precision)
DOUBLE: Floating point numbers (double precision)
DECIMAL:Floating point numbers represented as strings.

Date and time column types


DATE: YYYY-MM-DD (Four digit year followed by two digit month and date)
TIME: hh:mm:ss (Hours:Minutes:Seconds)
DATETIME: YYYY-MM-DD hh:mm:ss (Date and time separated by a space character)
TIMESTAMP: YYYYMMDDhhmmss
YEAR: YYYY (4 digit year)

Column Types2

Text data type


Text can be fixed length (char) or variable length strings. Also, text comparisions can be case
sensitive or insensitive depending on the type you choose.
CHAR(x): where x can range from 1 to 255.
VARCHAR(x): x ranges from 1 - 255
TINYTEXT: small text, case insensitive
TEXT: slightly longer text, case insensitive
MEDIUMTEXT: medium size text, case insensitive
LONGTEXT: really long text, case insensitive
TINYBLOB: Blob means a Binary Large OBject. You should use blobs for case
sensitive searches.
BLOB: slightly larger blob, case sensitive.
MEDIUMBLOB: medium sized blobs, case sensitive.
LONGBLOB: really huge blobs, case sensitive.
ENUM: Enumeration data type have fixed values and the column can take only one
value from the given set. The values are placed in parenthesis following ENUM
declaration. An example, is the marital status column we encountered in employee_per
table.
m_status ENUM("Y", "N")

Thus, m_status column will take only Y or N as values. If you specify any other value with
the INSERT statement, MYSQL will not return an error, it just inserts a NULLvalue in the
column.

SET: An extension of ENUM. Values are fixed and placed after the SET declaration;
however, SET columns can take multiple values from the values provided. Consider a
column with the SET data type as
hobbies SET ("Reading", "Surfing", "Trekking", "Computing")
You can have 0 or all the four values in the column.
INSERT tablename (hobbies) values ("Surfing", "Computing");

You might also like