SQL Access
SQL Access
DATABASE
Simply put, a database is a computerized record keeping system. More completely, it is a
system involving:
1 the data
2 the hardware that physically stores that data
3 the software that utilizes the hardware's file system in order to
1) store the data and
2) to provide a standardized method for retrieving or changing the data
4 the users who turn the data into information.
Analytic Databases
Analytic databases (a.k.a. OLAP- On Line Analytical Processing) are primarily static,
read-only databases which store archived, historical data used for analysis. For example,
a company might store sales records over the last ten years in an analytic database and
use that database to analyze marketing strategies in relationship to demographics.
Operational Databases
Operational databases (a.k.a. OLTP On Line Transaction Processing), on the other hand,
are used to manage more dynamic bits of data. These types of databases allow you to do
more than simply view archived data. Operational databases allow you to modify that
data (add, change or delete data).
These types of databases are usually used to track real-time information. For example, a
company might have an operational database used to track warehouse/stock quantities.
Database Models
Besides differentiating databases according to function, databases can also be
differentiated according to how they model the data.
Before the 1980's, the two most commonly used Database Models were the hierarchical
and network systems. Let's take a quick look at these two models and then move on to the
more current models.
46650880.doc 1
Hierarchical Databases
As its name implies, the Hierarchical Database Model defines hierarchically arranged
data. Perhaps the most intuitive way to visualize this type of relationship is by
visualizing an upside down tree of data. In this tree, a single table acts as the "root" of the
database from which other tables "branch" out.
You will be instantly familiar with this relationship because that is how all windows-
based directory management systems (like Windows Explorer) work these days.
Relationships in such a system are thought of in terms of children and parents such that a
child may only have one parent but a parent can have multiple children.
At the core of the relational model is the concept of a table (also called a relation) in
which all data is stored. Each table is made up of records (horizontal rows also known as
tuples) and fields (vertical columns also known as attributes).
It is important to note that how or where the tables of data are stored makes no difference.
Each table can be identified by a unique name and that name can be used by the database
to find the table behind the scenes. As a user, all you need to know is the table name in
order to use it. You do not need to worry about the complexities of how the data is stored
on the hard drive.
This is quite different from the hierarchical and network models in which the user had to
have an understanding of how the data was structured within the database in order to
retrieve, insert, update, or delete records from the database.
Thus, if you wish to retrieve a row from a table for example, you do so by comparing the
value stored within a particular column for that row to some search criteria.
For example, you might say "Give me all the rows from the 'STUDENTS' table which
have 'Selena' in the 'FIRST_NAME' column."
The database might return a list which looks essentially like this:
Selena Sol SID-001 213-456-7890
Selena Roberts SID-268 818-934-5069
Selena Smith SID-991 310-234-6475
Client/Server Databases
As we said before, most databases that you will come across these days will be relational
databases. However, there are many types of relational databases. A client/server
database works like this: A database server is left running 24 hours a day, and 7 days a
week. Thus, the server can handle database requests at any hour. Database requests come
46650880.doc 2
in from "clients" who access the database through its command line interface or by
connecting to a database socket. Requests are handled as they come in and multiple
requests can be handled at one time.
Bibliographic Databases
This provide a descriptive record of an item, but the item itself is not provided in the
database. Information about the item is provided, including such things as author, title,
subject, publisher, etc. The information provided is called a citation. Sometimes a short
summary or abstract of the item is provided as well. Examples of bibliographic databases
include the GALILEO database Social Sciences Abstracts, or the Internet Movie
Database on the World Wide Web.
Full-text Database
This provides the full-text of a publication. For instance, Research Library in GALILEO
provides not only the citation to a journal article, but often the entire text of the article as
well. "CollegeSource Online" offers full-text of 20,000 college catalogs, so rather than
having to request a catalog from several colleges to make comparisons, you can gather
information from all colleges you're interested in at one time.
Meta-Databases
These are databases that allow one to search for content that is indexed by other
databases. JAKE and GOLD are examples of this kind of database. If you find a citation
for an article in one of the bibliographic databases and want to determine if the article is
available in full-text in another database, you could do a search for the journal in JAKE
to get a list of all the databases that index that specific publication and whether those
databases include it in full-text.
46650880.doc 3
Components of a Database System
• Hardware
o Physical devices
• Software
o Operating System, DBMS, application, utilities
• People
o System admins, database admins, designers, analysts and programmers,
end users
• Procedures
o Instructions and rules governing the design and use
• Data
o The raw facts in the database
46650880.doc 4
Microsoft Access Tutotial
This tutorial will help you get started with Microsoft Access but it is a very good idea to
use the Help Files that come with the program.
First of all you need to understand how Microsoft Access breaks down a database. Some
keywords involved in this process are: Database File, Table, Record, Field, Data-type.
46650880.doc 5
Here is the Hierarchy that Microsoft Access uses in breaking down a database.
Database File: This is your main file that encompasses
the entire database and that is saved to your hard-drive
or floppy disk.
Example) StudentDatabase.mdb
Table:A table is a collection of data about a specific
topic. There can be multiple tables in a database.
Example #1) Students
Example #2) Teachers
Field:Fields are the different categories within a Table.
Tables usually contain multiple fields.
Example #1) Student LastName
Example #2) Student FirstName
46650880.doc 6
Creating New, and Opening Existing Databases
46650880.doc 7
OK. Otherwise choose the database you had previously used and click
OK.
If you have already opened a database or closed the dialog box that displays when
Microsoft Access starts up, click New Database on the toolbar.
2. On the Databases tab, double-click the icon for the kind of database you want to
create.
3. Specify a name and location for the database.
4. Click Create to start defining your new database
If you have already opened a database or closed the dialog box that displays when
Microsoft Access starts up, click New Database on the toolbar, and then double-
click the Blank Database icon on the General tab.
2. Specify a name and location for the database and click Create. (Below is the
screen that shows up following this step)
46650880.doc 8
Tables
A table is a collection of data about a specific topic, such as students or contacts. Using a
separate table for each topic means that you store that data only once, which makes your
database more efficient, and reduces data-entry errors.
Tables organize data into columns (called fields) and rows (called records).
46650880.doc 9
2. Double-Click on "Create table in Design view".
(DESIGN VIEW)
46650880.doc 10
Primary Key
• One or more fields (columns) whose value or values uniquely identify each record
in a table. A primary key does not allow Null values and must always have a
unique value. A primary key is used to relate a table to foreign keys in other
tables.
• NOTE: You do not have to define a primary key, but it's usually a good idea. If
you don't define a primary key, Microsoft Access asks you if you would like to
create one when you save the table.
• For our tutorial, make the Soc Sec # field the primary key, meaning that every
student has a social security number and no 2 numbers are the same.
o To do this, simply select the Soc Sec # field and select the primary key
button
Switching Views
• To switch views form the datasheet (spreadsheet view) and the design view,
simply click the button in the top-left hand corner of the Access program.
Datasheet View Design View
Displays the view, which allows Displays the view, which allows you to enter
you to enter raw data into your fields, data-types, and descriptions into your
database table. database table.
Entering Data
• Click on the Datasheet View and simply start "chugging" away by entering the
data into each field. NOTE: Before starting a new record, the Soc Sec # field
must have something in it, because it is the Primary Key.
Manipulating Data
46650880.doc 11
• Adding a new row
o Simply drop down to a new line and enter the information
• Updating a record
o Simply select the record and field you want to update, and change its data
to what it should be
• Deleting a record
o Simply select the entire row and hit the Delete Key on the keyboard
46650880.doc 12
6. Click on Next
7. Leave !(999) 000-0000 the way it is. This is a default.
8. Click Next
9. Select which option you want it to look like
10. Click Next
11. Click Finish
• Selecting a value from a dropdown box with a set of values that you assign to
it. This saves you from retyping the value each time
o Example) Choosing a city that is either Auburn, Bay City, Flint, Midland,
or Saginaw
1. Switch to Design View
2. Select the field you want to alter (City)
3. At the bottom select the Lookup Tab
4. In the Display Control box, select Combo Box
5. Under Row Source Type, select Value List
6. Under Row Source, enter the values how you want them
displayed, separated by a comma. (Auburn, Bay City, Flint,
Midland, Saginaw)
NOTE:This will not alphabetize them for you, so you will
have to do that yourself. It should look something like this:
7. Select in the datasheet view and you should see the change when
you go to the city field.
Relationships
After you've set up multiple tables in your Microsoft Access database, you need a way of
telling Access how to bring that information back together again. The first step in this
process is to define relationships between your tables. After you've done that, you can
create queries, forms, and reports to display information from several tables at once.
A relationship works by matching data in key fields - usually a field with the same name
in both tables. In most cases, these matching fields are the primary key from one table,
which provides a unique identifier for each record, and a foreign key in the other table.
46650880.doc 13
For example, teachers can be associated with the students they're responsible for by
creating a relationship between the teacher's table and the student's table using the
TeacherID fields.
Having met the criteria above, follow these steps for creating relationships between
tables.
1. In the database window view, at the top, click on Tools ---> Relationships
2. Select the Tables you want to link together, by clicking on them and selecting the
Add Button
3. Drag the primary key of the Parent table (Teacher in this case), and drop it into
the same field in the Child table (Student in this case.)
When the Cascade Update Related Fields check box is set, changing a
o
primary key value in the primary table automatically updates the matching
value in all related records.
o When the Cascade Delete Related Records check box is set, deleting a
record in the primary table deletes any related records in the related table
5. Click Create and Save the Relationship
Forms
A form is nothing more than a graphical representation of a table. You can add, update,
and delete records in your table by using a form. NOTE: Although a form can be named
different from a table, they both still manipulate the same information and the exact data.
Hence, if you change a record in a form, it will be changed in the table also.
A form is very good to use when you have numerous fields in a table. This way you can
46650880.doc 14
see all the fields in one screen, whereas if you were in the table view (datasheet) you
would have to keep scrolling to get the field you desire.
Reports
A report is an effective way to present your data in a printed format. Because you have
control over the size and appearance of everything on a report, you can display the
information the way you want to see it.
46650880.doc 15
10. Select the style you desire...HINT: if you plan on printing your report, I suggest
you use a light background to save on printer toner and ink
11. Click Next
12. Give your report a name, and select Preview the Report
13. Select Finish
14. You should see your report. To adjust the design of your report, simply hit the
design button (same as with the tables), and adjust your report accordingly
4. Select Label Wizard and the table you would like to get your information from.
5. Click OK
6. Select the layout of your labels
7. Click Next
8. Select the font size and color you want on each label
9. Click Next
10. Select how you want your label to look
11. Click Next
12. Select how you want your labels sorted
13. Give your label report a name and preview it
46650880.doc 16
Time Required: 60 minutes
Here's How:
1. Verify that your system meets the basic requirements for Access. You'll need at
least a 233MHz or faster Pentium processor with 128MB of RAM. You'll also
need at least 180MB of free hard disk space.
2. Ensure that your operating system is up-to-date. It's a good idea to apply all
security updates and hot fixes to your system before installing access by visiting
http://windowsupdate.microsoft.com/
3. Insert the Office CD into your CD-ROM drive. The installation process will begin
automatically and ask you to wait while the system prepares the Installation
Wizard.
4. The next step of the process will prompt you to enter your name, your
organization's name and the product key found on your CD case. Once you've
completed this, click Next to continue.
5. The next screen will prompt you to accept the terms of the End User License
Agreement (EULA) by clicking the check box. Once you've done so, click Next
to continue.
6. If you'd like to install the entire Office suite choose "Install Now" on the next
screen. If you'd like to customize your installation, you may do so at this stage.
7. The next screen summarizes the installation. After you've reviewed the
comments, click the Install button to begin the installation.
8. When the installation completes, you may be prompted to restart your computer.
Go ahead and do so.
9. When your comptuer restarts, the first thing you should do is to visit the Office
Update site at http://officeupdate.microsoft.com to download any security patches
for Access. This is a critical step.
46650880.doc 17
on your system to access data on a MySQL server running on another computer. Dividing
the package into a server and clients separates the actual data from the interface.
We'll create a database called employees that contains details of employees of our
company Bignet. The details we plan to store would be names, salaries, age, addresses,
emails, birth dates, hobbies, phone numbers etc.
1. Start the MySQL server (this step is not necessary if MySQL is set up as a service
during installation)
2. Invoke the mysql client program by double-clicking on the shortcut icon created
earlier
3. A DOS window is presented with this mysql> prompt.
4. Type: create database employees;
(Note: The command ends with a semi-colon).
5. The MySQL server responds with something like:
Query OK, 1 row affected (0.00 sec)
6. This means that you have successfully created the database. Now, let's see how
many databases you have on your system. Issue the following command.
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.
7. To come back to the DOS prompt, type quit at the mysql prompt.
46650880.doc 18
Name Age Country Email
Manish Sharma 28 India manish@simplygraphix.com
John Doe 32 Australia j.dow@nowhere.com
John Wayne 48 U.S.A. jw@oldwesterns.com
Alexander 19 Greece alex@conqueror.com
The table above contains four columns that store the name, age, country and email. Each
row contains data for one individual. This is called a record. To find the country and
email of Alexander, you'd first pick the name from the first column and then look in the
third and fourth columns of the same row.
A database can have many tables; it is tables that contain the actual data. Hence, we can
segregate related (or unrelated) data in different tables. For our employees database we'll
have one table that stores company details of the employees. The other table would
contain personal information. Let's make the first table.
The SQL command for creating tables looks complex when you view it for the first time.
Don't worry if you get confused, we'll be discussing this in more detail in later sessions.
The CREATE TABLE keywords are followed by the name of the table we want to
create, employee_data. Each line inside the parenthesis represents one column. These
columns store the employee id, first name, last name, title, age, years of service with the
company, salary, perks and emails of our employees and are given descriptive names
emp_id, f_name, l_name, title, age, yos, salary, perks and email, respectively.
Each column name is followed by the column type. Column types define the type of data
the column is set to contain. In our example, columns, f_name, l_name, title and email
46650880.doc 19
would contain small text strings, so we set the column type to varchar, which means
variable characters. The maximum number of characters for varchar columns is
specified by a number enclosed in parenthesis immediately following the column name.
Columns age, yos, salary and perks would contain numbers (integers), so we set the
column type to int.
Our first column (emp_id) contains an employee id. Its column type looks really mean,
yeh? Let's break it down.
int: specifies that the column type is an integer (a number).
unsigned: determines that the number will be unsigned (positive integer).
not null: specifies that the value cannot be null (empty); that is, each row in the column
would have a value.
auto_increment: When MySQL comes across a column with an auto_increment
attribute, it generates a new value that is one greater than the largest value in the column.
Thus we don't need to supply values for this column. Also, it follows that each value in
this column would be unique. (We'll discuss the benefits of having unique values very
shortly).
primary key: helps in indexing the column that contribute to faster searches. Each value
has to be unique.
Using a Database
We've already created our employees database. Now let's start the mysql client program
and select our database. Once at the mysql prompt, issue the command:
SELECT DATABASE();
Specifying the database name at the start; type the following at the system prompt:
46650880.doc 20
mysql employees
Specifying the database with the USE statement at the mysql prompt:
mysql>USE employees;
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.
46650880.doc 21
MySQL Lesson - 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 us with a command that displays the column details of the tables.
Issue the following command at the mysql prompt:
DESCRIBE employee_data;
46650880.doc 22
INSERT INTO employee_data
(f_name, l_name, title, age, yos, salary, perks, email)
values
("Manish", "Sharma", "CEO", 28, 4, 200000,
50000, "manish@bignet.com");
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, "manish@bignet.com");
Query OK, 1 row affected (0.00 sec)
Inserting additional records requires separate INSERT statements. In order to make life
easy, I've packed all INSERT statements into the employee.dat file.
Our table contains 21 entries (20 from employee.dat file and one from the INSERT
statement we issued at the beginning).
46650880.doc 23
SELECT f_name, l_name from employee_data;
The statement tells MySQL to list all the rows from columns f_name and l_name.
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;
Some of you might recognize the * in the above statement as the wildcard. Though we
don't use that term for the character here, it serves a very similar function. The * means
'ALL columns'. Thus, the above statement lists all the rows of all columns.
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 |
+---------+------------+------+
46650880.doc 24
| 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)
I
1. Write the complete SQL statement for creating a new database called
addressbook
2. Which statement is used to list the information about a table? How do you use this
statement?
3. How would you list all the databases available on the system?
4. Write the statement for inserting the following data in employee_data table
First name: Rudolf
Last name: Reindeer
Title: Business Analyst
Age: 34
Years of service: 2
Salary: 95000
Perks: 17000
email: rudolf@bugnet.com
5. Give two forms of the SELECT statement that will list all the data in
employee_data table.
6. What will select f_name, email from employee_data; display?
7. Write the statement for listing data from salary, perks and yos columns of
employee_data table.
8. How can you find the number of rows in a table using the SELECT statement?
9. What will select salary, l_name from employee_data; display?
46650880.doc 25
MySQL Tutorial - 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 Comparison Operators.
+--------+------------+
| 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 comparisons 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 |
46650880.doc 26
| 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.
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 |
46650880.doc 27
| Arthur | Hoopla |
| Kim | Hunter |
| Roger | Lewis |
| Danny | Gibson |
| Mike | Harper |
| Hal | Simlai |
| Joseph | Irvine |
+--------+----------+
10 rows in set (0.00 sec)
+--------+------------+------+--------+
| 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 |
+--------+----------+
46650880.doc 28
10 rows in set (0.00 sec)
Displays employee names who have less than or equal to 2 years of service in the
company.
II
1. Write the SELECT statement to extract the ids of employees who are more than
30 years of age.
2. Write the SELECT statement to extract the first and last names of all web
designers.
3. What will the following SELECT statement display:
SELECT * from employee_data where salary <=100000;
4. How will you display the salaries and perks for employees who have more than
$16000 as perks?
5. List all employee names (last name followed by first name) that hold the title of
Marketing Executive.
+--------+------------+
| 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)
46650880.doc 29
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)
III
1. List all employees whose last names begin with P.
2. Display the names of all employees in the marketing division.
3. What will the following statement display
SELECT f_name, l_name, salary from
employee_data where f_name like '%k%';
4. List the last names and titles of all programmers
46650880.doc 30
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 |
+--------+----------+------+
46650880.doc 31
| 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 is meant to separate
the various logical conditions and remove any ambiguity.
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)
+--------+------------+
| f_name | l_name |
+--------+------------+
| John | Hagan |
| Ganesh | Pillai |
| John | MacFarland |
| Peter | Champion |
+--------+------------+
4 rows in set (0.00 sec)
46650880.doc 32
IV
1. List the first and last names of all employees who draw less than or equal to
$90000 and are not Programmes, Senior programmers or Multimedia
programmers.
2. What does the following statement display?
SELECT l_name, f_name from employee_data
where title NOT LIKE '%marketing%'
AND age < 30;
3. List all ids and names of all employees between 32 and 40 years of age.
4. Select names of all employees who are 32 years of age and are not programmers.
+---------+--------+----------------------+
| 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)
46650880.doc 33
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 |
+---------+------------+------+
46650880.doc 34
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)
V
1. List all employees who hold the titles of "Senior Programmer" and "Multimedia
Programmer".
2. List all employee names with salaries for employees who draw between $70000
and $90000.
3. What will the following statement display?
SELECT f_name, l_name, title from
employee_data where title NOT IN
('Programmer', 'Senior Programmer',
'Multimedia Programmer');
4. Here is a more complex statement that combines both BETWEEN and IN. What
will it display?
SELECT f_name, l_name, title, age
from employee_data where
title NOT IN
('Programmer', 'Senior Programmer',
'Multimedia Programmer') AND age
NOT BETWEEN 28 and 32;
46650880.doc 35
MySQL Tutorial - Ordering Data
This section of the 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 the 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)
+---------+------------+------+
46650880.doc 36
| 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)
+---------+
| f_name |
+---------+
| Shahida |
| Roger |
| Peter |
| Paul |
| Monica |
| Mike |
| Mary |
| Manish |
| Kim |
| Joseph |
| John |
46650880.doc 37
| John |
| Hassan |
| Hal |
| Ganesh |
| Fred |
| Edward |
| Danny |
| Arthur |
| Anamika |
| Alok |
+---------+
21 rows in set (0.00 sec)
VI
1. Order all employees on the basis of the salary they draw.
2. List all employees in descending order of their years of service.
3. What does the following statement display?
SELECT emp_id, l_name, title, age
from employee_data ORDER BY
title DESC, age ASC;
4. Display employees (last names followed by first names) who hold the title of
either "Programmer" or "Web Designer" and sort their last names alphabetically.
+---------+--------+
| f_name | l_name |
+---------+--------+
| Manish | Sharma |
| John | Hagan |
| Ganesh | Pillai |
| Anamika | Pandit |
| Mary | Anchor |
+---------+--------+
5 rows in set (0.01 sec)
46650880.doc 38
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, eh?
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)
46650880.doc 39
This extracts 3 rows starting from the sixth row.
VII
1. List the names of the 5 youngest employees in the company.
2. Extract the next 5 entries starting with the 10th row.
3. Display the names and salary of the employee who draws the largest salary.
4. What does the following statement display?
SELECT emp_id, age, perks
from employee_data ORDER BY
perks DESC LIMIT 10;
+----------------------------+
| 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)
46650880.doc 40
You'll notice that the display contains multiple occurrences 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)
+------+
| 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.
46650880.doc 41
VIII
1. How many unique salary packages does our company, Bignet, offer? List them is
descending order.
2. How many distinct first names do we have in our database?
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)
IX
1. List the minimum perks package.
2. List the maximum salary given to a "Programmer".
3. Display the age of the oldest "Marketing Executive".
4. (Tricky!) Find the first and last names of the oldest employee.
46650880.doc 42
SQL Tutorial - 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)
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;
46650880.doc 43
+-------------+
| avg(salary) |
+-------------+
| 95095.2381 |
+-------------+
1 row in set (0.00 sec)
X
1. Display the sum of ages of employees working at Bignet.
2. How would you calculate the total of years of service the employees of Bignet
have in the company?
3. Calculate the sum of salaries and the average age of employees who hold
"Programmer" title.
4. What do you understand from the following statement?
select (SUM(perks)/SUM(salary) * 100)
from employee_data;
+----------------+
| Average Salary |
+----------------+
| 95095.2381 |
+----------------+
1 row in set (0.00 sec)
Such pseudo names will make the display names more clear to users. The important thing
to remember here is that if you assign pseudo names that contain spaces, enclose the
names in quotes. Here is another example:
select (SUM(perks)/SUM(salary) * 100)
AS 'Perk Percentage' from
employee_data;
+-----------------+
| Perk Percentage |
+-----------------+
| 19.53 |
+-----------------+
1 row in set (0.00 sec)
46650880.doc 44
MySQL Training - Counting
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)
+----------------------------+
| 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)
46650880.doc 45
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.
+----------------------------+--------+
| 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|
46650880.doc 46
| Programmer | 4|
+----------------------------+--------+
11 rows in set (0.00 sec)
XI
1. Count the number of employees who have been with Bignet for four or more
years.
2. Count employees based on their ages.
3. Modify the above so that the ages are listed in a descending order.
4. Find the average age of employees in different departments (titles).
5. Change the above statement so that the data is displayed in a descending order of
average ages.
6. Find and list the percentage perk (perk/salary X 100) for each employee with the
% perks sorted in a descending order.
+----------------------------+-------------+
| 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;
46650880.doc 47
+----------------------------+-------------+
| 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)
+-----------+
| version() |
+-----------+
| 3.22.32 |
+-----------+
1 row in set (0.00 sec)
+---------------------+
| now() |
+---------------------+
| 2001-05-31 00:36:24 |
+---------------------+
1 row in set (0.00 sec)
SELECT MONTH(CURRENT_DATE);
46650880.doc 48
+---------------------+
| 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)
46650880.doc 49