Sie sind auf Seite 1von 46

2017

SQL – The Database Language

Shabani Juma Bakari


+255 688 300078
+255 717 387899
muya.shabani@yahooo.co.uk
TABLE OF CONTENTS

TABLE OF CONTENTS ................................................................................................................... i


LIST OF FIGURES ......................................................................................................................... iii
STRUCTURED QUERY LANGUAGE (SQL) ............................................................................... 1
STARTING THE WAMP SERVER ................................................................................................ 2
EXECUTING SQL STATEMENTS ................................................................................................ 3
Opening a Database ...................................................................................................................... 3
Showing Connection Status .......................................................................................................... 4
CREATING AND DELETING A DATABASE.............................................................................. 4
Creating a new Database ............................................................................................................... 4
Dropping a Database ..................................................................................................................... 5
MySQL DATA TYPE ...................................................................................................................... 6
Integer Data types ......................................................................................................................... 6
Fractional Data Type..................................................................................................................... 6
String Data Types ......................................................................................................................... 7
Date/Time Data Types .................................................................................................................. 8
CREATING AND DELETING A TABLE ...................................................................................... 8
Create Table Statement ................................................................................................................. 8
Displaying the Table Structure ..................................................................................................... 9
Displaying Create Table Structure .............................................................................................. 10
Modifying Table Structure .......................................................................................................... 10
Creating a Table with Foreign Key............................................................................................. 11
Renaming a Table ....................................................................................................................... 12
Dropping Table ........................................................................................................................... 12
MySQL STORAGE ENGINE ........................................................................................................ 12
WORKING WITH DATA IN MYSQL DATABASE ................................................................... 13
Insert Statement .......................................................................................................................... 14
Inserting Multiple Rows ............................................................................................................. 14
Update Statement ........................................................................................................................ 14
Updating with a Derived Column ............................................................................................... 15
Delete Statement ......................................................................................................................... 15
SELECT STATEMENT ................................................................................................................. 16
Retrieving Individual Columns ................................................................................................... 16
Retrieving Multiple Columns ..................................................................................................... 16
Retrieving All Columns .............................................................................................................. 17
Counting Number of Records ..................................................................................................... 17
FILTERING OUTPUT WITH WHERE CLAUSE ....................................................................... 18
Filtering on an Exact Value ........................................................................................................ 18
Filtering on a Range of Values ................................................................................................... 19
The LIKE Clause ........................................................................................................................ 20
SORTING OUTPUT WITH GROUP BY CLAUSE ..................................................................... 21
Sorting on a Single Column ........................................................................................................ 21
Sorting on Multiple Columns...................................................................................................... 23
Specifying Sort Order ................................................................................................................. 23
Combining WHERE Clauses ...................................................................................................... 24
Using the AND Operator ............................................................................................................ 24
Using the OR Operator ............................................................................................................... 25
Filtering on Multiple Values ....................................................................................................... 26
Skipping Rows ............................................................................................................................ 28
SELECTION WITH RENAME ..................................................................................................... 28
Selection with Alternative Column Name .................................................................................. 28
i
SQL – The Database Language | Shabani Juma Bakari

Selection with Alternative Table Name ...................................................................................... 29


JOINING TABLES USING WHERE CLAUSE ............................................................................ 29
JOINING TABLES USING JOIN .................................................................................................. 31
INNER JOIN (simple join) ......................................................................................................... 31
Left Outer Join ............................................................................................................................ 32
Right Outer Join .......................................................................................................................... 33
Join Statement for More Than Two Tables ................................................................................ 34
SQL GROUP BY ............................................................................................................................ 35
MySQL HAVING ........................................................................................................................... 37
SQL DISTINCT .............................................................................................................................. 39
SQL SUB-QUERIES ...................................................................................................................... 39

ii
SQL – The Database Language | Shabani Juma Bakari

LIST OF FIGURES

Figure 1, Starting the WAMP Server in MS Windows 10. .............................................................. 2


Figure 2, Selecting the MySQL Service ........................................................................................... 2
Figure 3, a command line screen for writing and running SQL Commands. ................................... 3
Figure 4, Listing databases ............................................................................................................... 3
Figure 5, Opening a database called mysql ...................................................................................... 4
Figure 6, Error message resulting from attempt to open a non-existing database ............................ 4
Figure 7, showing connection status and the name of the database in use. ...................................... 4
Figure 7, the command to create a new database called NIT ........................................................... 5
Figure 8, error message resulted from an attempt to create database that already exist ................... 5
Figure 9, using “if not exists” in create database statement. ............................................................ 5
Figure 10, listing warning messages ................................................................................................. 5
Figure 11, dropping a database called NIT ....................................................................................... 6
Figure 12, displaying the table structure ........................................................................................... 9
Figure 13, displaying the create table statement ............................................................................. 10
Figure 14, MySQL 5.7.11 supported storage engines .................................................................... 12
Figure 15; retrieving single column ................................................................................................ 16
Figure 16; retrieving multiple columns of a the same table............................................................ 17
Figure 17; retrieving all columns of a table .................................................................................... 17
Figure 18; counting number of rows (records) in a table................................................................ 18
Figure 19, filtering the output on exact value using equality operator ........................................... 18
Figure 20, filtering the output on exact value using inequality operator ........................................ 19
Figure 21, filtering the output on range of value ............................................................................ 19
Figure 22, filtering the output on range of value ............................................................................ 20
Figure 23, filtering the output on range of value reversing the operator ........................................ 20
Figure 24, sorting the output of a select statement ......................................................................... 22
Figure 25, filtering and sorting the output in the same query ......................................................... 22
Figure 26, sorting on multiple columns .......................................................................................... 23
Figure 27, specifying sort order ...................................................................................................... 24
Figure 28, Using AND logic in the WHERE clause....................................................................... 25
Figure 29, Using OR logic in the WHERE clause .......................................................................... 25
Figure 30, Filtering on multiple values of the same column using OR logic ................................. 26
Figure 31, Filtering on multiple values of the same column using IN keyword ............................ 26
Figure 32, Filtering on multiple values of the same column using BETWEEN keyword.............. 27
Figure 33, Limiting number of rows using the LIMIT keyword .................................................... 27
Figure 34a, displaying first four rows using LIMIT keyword ........................................................ 28
Figure 34b, skipping the first four rows and displaying the next five rows ................................... 28
Figure 35, Renaming Column using AS keyword in select statement ........................................... 29
Figure 36, Selection with alternative table name ............................................................................ 29
Figure 37, Joining two tables using WHERE clause ...................................................................... 30
Figure 38, Joining three tables using WHERE clause .................................................................... 30
Figure 39, SQL Inner Join .............................................................................................................. 31
Figure 40, joining two tables using inner join ................................................................................ 32
Figure 41, SQL Left Join ................................................................................................................ 32
Figure 42, joining two tables using left join ................................................................................... 33
Figure 43, SQL Right Join .............................................................................................................. 33
Figure 44, SQL Right Join .............................................................................................................. 34
iii
SQL – The Database Language | Shabani Juma Bakari

Figure 45, SQL join for three tables ............................................................................................... 35


Figure 46, retrieving the first 20 records of the enrollment table ................................................... 36
Figure 47, retrieving the first 10 records of the enrollment table by grouping on student ID ........ 37
Figure 48, retrieving the first 10 records of the enrollment table by grouping on three columns .. 37
Figure 49, filtering using HAVING keyword ................................................................................. 38
Figure 50, retrieving unique records using distinct keyword ......................................................... 39
Figure 51, using subquery in select statement ................................................................................ 41

iv
SQL – The Database Language | Shabani Juma Bakari

STRUCTURED QUERY LANGUAGE (SQL)

The Structured Query Language (SQL) is the standard language for relational databases. It can be
categorized into two categories, the Data Definition Language (DDL) and the Data Manipulation
Language (DML). Both DDL and DML are simple English like statements. DDL is used for
defining the structure of the tables (relations) including specifying the data type (Domain) for every
attribute, key(s), foreign keys and other constraints. DML is used for interacting with the relations
in the database by performing the basic database operations, insert, update, delete and retrieve.

Usually, the SQL statements (Commands) run on an SQL server which is the Database Management
Systems (DBMS). There are several DBMS in the market today. Some of them are the MS Access
and MS SQL Server both offered by the Microsoft Corporation, MySQL Server and Oracle SQL
Server. In our discussion, we will use the MySQL Server.

For standalone users, MySQL server is available in different packages like the WAMP (Window,
Apache, MySQL and PHP) and XAMP for Windows OS and XAMP and LAMP (Linux, Apache,
Mysql and PHP) for Linux OS. However there are other packages that offer the MySQL Server.

MySQL Server like many software are of different versions. However, the different versions have
an upward compatibility. That is, the new version must be able to offer all functionalities that were
offered by the previous version. In our discussion, we will use MySQL Server available in Wamp
Server 3.0.4 which is MySQL Server 5.7.11. Thus, in order to understand these notes and to run
examples available in, you need to have a computer with WAMP Server 3.0.4 offered by the
Otomatic.

If we have to consider SQL as any other programming languages like C, C++, Pascal, Java etc, then
the MySQL Server will be the compiler for the SQL. The function of the compiler is to transform
the codes (command) from the high level language to lower level machine language. The commands
may be written direct to the compiler or can be written in any standard editor and then transferred
to the compiler by either copy & paste method or by import command if available in the compiler.
Most of the DBMS have the Import/Export option. The Import option allow a database and its
contents to be shifted from the where is available to the DBMS while the Export option allow the
database available into the DBMS to be taken away to other media. In both cases, the original
database remain what is transferred is a copy of the database.

The best practice for writing the SQL commands is to write them away from the SQL Server and
then copy them to the server and run. There are many standard editors like the notepad, notepad++,
editpad, wordpad, php designer, dreamweaver, editpadlite etc. If SQL commands are to be written
in a standard editor, then the file must be saved with the extension of .sql. For example, if the file
name is SimpleLesson then it must be saved as SimpleLesson.sql. In our discussion we will use
the NotePad++ 7.3.3 as our Standard SQL Editor.

Page 1 of 45
SQL – The Database Language | Shabani Juma Bakari

STARTING THE WAMP SERVER

WAMP server is started like any other computer program by clicking the start option, then point to
all programs, select WampServer32 and then clik “start WampServer32”.

Figure 1, Starting the WAMP Server in MS Windows 10.

After clicking the start WampServer32, a new icon will appear on the bottom right area of the
notification icon. Wait until the becomes green. Then your WAMP server is online now. As its
name imply, the server act as PHP Server, MySQL Server and well as APACHE Server. Thus, in
order to use it, you have to specify the type of service you want to run. To do so, click the point
to MySQL then click the “MySQL Console”.

Figure 2, Selecting the MySQL Service

After clicking the MySQL Console, a black screen will appear prompting you enter a password. If
no password was entered during the installation, then click OK (in console screen the only OK key
is the return key, ENTER Key). So press Enter. After pressing the return key, a new screen like the
one below will be presented to you. Here is where you can write (paste) your SQL commands and
run them and do whatever you want do to that relate with the database. That is the command line
(codes) area.

2
SQL – The Database Language | Shabani Juma Bakari

Figure 3, a command line screen for writing and running SQL Commands.

NB:
1. The mysql> prompt indicates that you will now be typing commands into the mysql client
instead of the system shell.
2. Almost all SQL statements are terminated by semicolon (;)

If you want to quit (exit or close) the screen you simply click the close sign at the top-right corner
or you can run the exit command in the screen which is written as quite; or exit;

EXECUTING SQL STATEMENTS

Now let's look at how the MySQL program is used to execute a SQL statement on a MySQL
database.

Opening a Database
Like in MS Access and any other DBMS, in order to use a certain database available in that DBMS,
you need to select (open) it. Likewise, you cannot open a database unless you know its name. So
the first thing you can do is to list all available databases in order to see if the one you need is there.
This is done by running the command to list database. The command is shown in figure 1 with its
output.

From the output, we have the list of available databases and the last row read as “9 rows in set <0.00
sec>”. The number 9 shows the total number of requested records found while the 0.00 sec shows
the total time in seconds used in fetching the results.

Figure 4, Listing databases

3
SQL – The Database Language | Shabani Juma Bakari

After you have listed all the database, then you can open (select or connect) the database you want
to use. In order to select the database we use SQL command “use” followed by the name of the
database. For example, in order to use the database called mysql, we can use the following
command.

Figure 5, Opening a database called mysql

If you attempt to connect to a database which is not available, you mistype the name, an error
message will appear.

Figure 6, Error message resulting from attempt to open a non-existing database

Showing Connection Status


If you are using several databases at the same time, there is a special statement to find out which
one you are working on at any given time. This statement is called status statement. The statement
also gives the status of the connection including connection parameters. The statement and its output
are shown below.

Figure 7, showing connection status and the name of the database in use.

CREATING AND DELETING A DATABASE

Creating a new Database


You use the create database command followed by the database name to create a new database.
To create a new database named NIT, issue the following command. The output will be as shown
if the database is created successfully.

4
SQL – The Database Language | Shabani Juma Bakari

Figure 7, the command to create a new database called NIT

The database name can be up to 64 characters in length and can contain any character that is allowed
in a directory name on your underlying operating system, except for the / and \ characters. The
database name also cannot be one of the SQL reserved words.

The database name must be unique as well. If you attempt to issue a create database statement for
a database that already exists, you will see an error. The following output is produced when you
attempt to create NIT database for a second time.

Figure 8, error message resulted from an attempt to create database that already exist

The optional attribute if not exists can be added to a create database statement to avoid an error if
the database already exists. Instead, a warning is generated, which you can view using the show
warnings command.

Figure 9, using “if not exists” in create database statement.

Figure 10, listing warning messages

Dropping a Database
Use the drop database command to drop a database completely. Use this command with extreme
caution you cannot recover a dropped database unless you have a backup. For example, to drop the
database NIT you can run this command.

5
SQL – The Database Language | Shabani Juma Bakari

Figure 11, dropping a database called NIT

MySQL DATA TYPE

Before looking on how to manage tables, let us take look on the data types available in MySQL
Server. MySQL server supports many data type.

As the name suggests, numeric data types are concerned with numbers. If you have a column that
will contain nothing but numbers, chances are that you want to configure that column with a numeric
data type. The numeric data types can be integer or fractional.

Integer Data types


Data type Acceptable values Storage requirements
TINYINT Signed: –128 to 127 1 byte
Unsigned: 0 to 255
SMALLINT Signed: –32768 to 32767 2 bytes
Unsigned: 0 to 65535
MEDIUMINT Signed: –8388608 to 8388607 3 bytes
Unsigned: 0 to 16777215
INT Signed: –2147483648 to 2147483647 4 bytes
Unsigned: 0 to 4294967295
INTEGER Same values as the INT data type. INTEGER is a 4 bytes
synonym for INT.)
BIGINT Signed: –9223372036854775808 to 8 bytes
9223372036854775807
Unsigned: 0 to 18446744073709551615

Fractional Data Type


Data type Description
FLOAT An approximate numeric data type that uses 4 bytes of storage. The data
type supports the following values:
–3.402823466E+38 to –1.175494351E–38
0
1.175494351E–38 to 3.402823466E+38
DOUBLE An approximate numeric data type that uses 8 bytes of storage. The data
type supports the following values:
–1.7976931348623157E+308 to –2.2250738585072014E–308
0
2.2250738585072014E–308 to 1.7976931348623157E+308
DOUBLE Synonym for the DOUBLE data type
PRECISION
REAL Synonym for the DOUBLE data type

6
SQL – The Database Language | Shabani Juma Bakari

DECIMAL An exact numeric data type whose range storage requirements depend on
the <length> and <decimals> values specified in the column definition
DEC Synonym for the DECIMAL data type
NUMERIC Synonym for the DECIMAL data type
FIXED Synonym for the DECIMAL data type

String Data Types


The string data types provide a great deal of flexibility for storing various types of data from
individual Bits to large files. String data types are normally used to store names and titles and any
value that can include letters and numbers. MySQL supports four categories of string data types
which are character, text, list and binary.

The CHAR data type is a fixed-length character data type that can store up to 255 characters. The
<length> placeholder specifies the number of characters stored. Although the actual value can be
made up of fewer characters than the amount specified, the actual storage space is fixed at the
specified amount.

The VARCHAR data type, like the CHAR data type, can store up to 255 characters. Along with the
flexibility offered by VARCHAR, compared to CHAR, comes a performance cost. CHAR columns
are processed more efficiently than VARCHAR columns, yet CHAR columns can result in wasted
storage. Generally, for columns with values that vary widely in length, the VARCHAR data type
might often be your best choice.

Binary data types support the storage of large amounts of data, such as image and sound files. These
types are useful when you expect values to grow large or to vary widely. The four binary data types
are identical except for the maximum amount of data that each one supports. The following table
shows the maximum size of values permitted in a column configured with one of these data types.

Data type Maximum size


TINYBLOB/TINYTEXT 255 characters (355 bytes)
BLOB/TEXT 65,535 characters (64 KB)
MEDIUMBLOB/MEDIUMTEXT 16,777,215 characters (16 MB)
LONGBLOB/LONGTEXT 4,294,967,295 characters (4 GB)

The text data types also have the same size limitations and storage requirements as the binary data
types. If you refer to the previous table, you can see how the sizes correspond between the binary
data types and the text data types. The main difference between the two types is that the text data
types are associated with a specific character set. Binary columns are treated as strings, and sorting
is case sensitive. Text columns are treated according to their character sets, and sorting is based on
the collation for that character set.

Now take a look at the list data types, which are the last set of string data types. As the following
syntax shows, the list data types include ENUM and SET.

BikeColor ENUM(‘red’, ‘blue’, ‘green’, ‘yellow’)


BikeOptions SET(‘rack’, ‘light’, ‘helmet’, ‘lock’)

7
SQL – The Database Language | Shabani Juma Bakari

Notice that the list of values follows the data type. The values are enclosed in single quotes and
separated by commas, and all values are enclosed in parentheses. For an ENUM data type, you can
specify up to 65,535 values. For a SET data type, you can specify up to 64 values.

Date/Time Data Types


The final category of data types is the date/time data types. The date/time data types allow you to
specify columns that contain data specific to dates and times. The date/time data types support the
ranges and formats shown in the following table

Data type Format Range


DATE YYYY-MM-DD 1000-01-01 through 9999
TIME HH:MM:SS –838:59:59 to 838:59:59
DATETIME YYYY-MM-DD 1000-01-01 00:00:00 through 9999
HH:MM:SS
YEAR YYYY 1901 to 2155 (and 0000)
TIMESTAMP YYYY-MM-DD 1970-01-01 00:00:00 to partway through
HH:MM:SS 2037

For more on data types, visit https://dev.mysql.com/doc/refman/5.7/en/data-types.html

CREATING AND DELETING A TABLE

Use the create table command to create a new database table. A table definition consists of a
number of columns and a set of table options. Each column in the table definition is given a data
type and can also be given a constraint.

A column name can be up to 64 characters long and can contain any character. You must enclose
the column name in quotes (‘) or back ticks (`) if it contains a space. A column name cannot be one
of the MySQL keywords.

The data type of a column determines what values it can hold and the maximum size of a stored
value. For instance, a column defined as VARCHAR(6) can contain text data up to 6 characters in
length.

A column constraint is used to impose a restriction on the values stored in that column. For example,
a column defined as unique may not contain the same value more than once. If a constraint is
violated when you attempt an insert or update on the table, MySQL will return an error and your
SQL statement will fail.

Create Table Statement


Create table <table name>
(
Column_one data_type() additional_constraints,
Column_two data_type() additional contraints,
Column_three data_type additional_constraints
);

8
SQL – The Database Language | Shabani Juma Bakari

Example of create table statement for creating table called product

CREATE TABLE products


(
product_code VARCHAR(10) PRIMARY KEY,
name VARCHAR(40) NOT NULL UNIQUE,
weight DECIMAL(6,2) NOT NULL,
price DECIMAL(6,2) NOT NULL,
quality VARCHAR(30) NOT NULL DEFAULT ‘Excellent’
);

NB:
In the preceding example, product_code have been declared to be a primary key. However, a table
can have more than one primary key (composite keys). If more than one column has to be set as
primary keys, then the previous format will not work. Thus the best way to declare a primary key,
the format below is the best.

CREATE TABLE orders


(
order_id INT not null AUTO_INCREMENT,
customer_code VARCHAR(10) NOT NULL,
order_date DATE NOT NULL,
Primary key(order_id)
);

Example of table with composite primary key

Create table studentCourse


(
courseCode varchar(8) not null,
studentID varchar(15) not null,
Primary key(courseCode, studentID)
);

NB: A table cannot have more than one auto increment field. If a table have auto increment field,
then the field must be a primary key

Displaying the Table Structure


It is important to describe/view the structure of your table. A special statement called describe or
desc is available for that purpose. The syntax of the statement is:-

DESC <TABLE NAME> or DESCRIBE <TABLE NAME>

Figure 12, displaying the table structure

9
SQL – The Database Language | Shabani Juma Bakari

Displaying Create Table Structure


When using a DBMS, it is important sometimes to displaying the SQL commands used to create a
certain table. A special statement called show create table is available to serve that.

SHOW CREATE TABLE <TABLE NAME>

Figure 13, displaying the create table statement

Modifying Table Structure


You can use the alter table command to change part of a table definition. You can add, modify, or
drop a column on a live table, although, of course, you should take care to ensure that doing so will
not cause errors in an application or query that relies on the existing table structure.

To add a new column, use the add keyword followed by a column definition. For example, the
following statement adds a new column named derivery_date to the orders table, which is of data
type date.

ALTER table orders ADD DERIVERY_DATE DATE;

To drop a column from a table, use the drop keyword followed by the column name. The following
statement drops the derivery_date column from orders table:

ALTER table orders DROP DERIVERY_DATE;

To modify an existing column, use the change keyword followed by the existing column name, a
new column name, and a column definition. You can use change both to rename a column and to
change its definition.

Suppose you realize that the order_id column was supposed to be integer field and is supposed to
be varchar type column. The following statement changes the data type of order_id. Notice that the
column name appears twice in this statement because you do not want to change its name.

ALTER table orders CHANGE order_id order_id varchar(20) not null;

10
SQL – The Database Language | Shabani Juma Bakari

However, a column can be added anywhere in the table by using the add after keyword. For
example, the following statement will add a new column delivery_date in the orders table after the
order_id column.

ALTER table orders ADD derivery_date date AFTER order_id;

Creating a Table with Foreign Key


One of the features of all relational DBMSs is the ability to create relationship between tables in the
same database. Two tables can relate when they have a column with a common values (not
necessarily to have common name). For example, in higher learning institute, it is known that a
program belong to a certain department. Thus, if a department is identified by its department code,
that code should also be available in the program table so that to relate each program and the
department that own it. In that case, the value of the department code in the department will be a
primary key while the same value in the program table will be a foreign key. For this value
(department code), department table is the parent table while program table is a child table. Such
value cannot exist in a child table if it is existing in the parent table (referential integrity constrain).

Below is example of sql ctreate table statement that create the two tables, department (parent) and
program (child).

create table department


(
deptID int auto_increment,
deptCode varchar(50) not null unique,
deptName text not null,
primary key(deptID)
);

create table program


(
progID varchar(100) not null unique,
progName text not null,
capacity int(4) not null default 600,
ntaLevel int(2) not null,
department varchar(50),
primary key(progID),
foreign key(department) references department(deptCode) on update cascade on delete set null
);

The last statement in the create table program contain several keyword.
1. Foreign key  A key word that tells MySQL that the values in this field (enclosed in the
brackets, department in this case) will refers to a value in another table (parent table).
2. References  used to name the parent table followed by the field referred in the parent table.
3. On update cascade, on delete set null  tells MySQL what to do in case a value on the
parent table is updated or deleted. Cascade is a reference option which means the same
changes should be done in the child table (in this case when the value in the parent table is

11
SQL – The Database Language | Shabani Juma Bakari

update, the value on the child should also be updated). Set null means when a change is done
in the parent table, the value should be removed in the child table. In general, reference
options are restrict, cascade, set null, no action and set default.

Renaming a Table
MySQL allows the name of a table to be changed even if the table already have data. To do so, use
a statement called rename table. For example, if you want to change the name of the table orders to
be orderedItems, you simply write.

RENAME TABLE orders TO orderedItems;

Dropping Table
To drop a table, use the drop table command followed by the name of the table. Beware that a
dropped table cannot be recovered unless you have a backup.
To drop the orders table you created earlier in this lesson, use the following command.

DROP TABLE orders;

You can use drop table if exists so that no error occurs if a table does not exist. This is useful in a
batch script that creates all the tables for a database: The script will delete the existing tables before
re-creating them but will not fall over if the tables do not exist yet.

DROP TABLE IF EXISTS orders;

MySQL STORAGE ENGINE

Storage engines are MySQL components that handle the SQL operations for different table types.
InnoDB is the default and most general-purpose storage engine. To determine which storage engines
your server supports, use the show engines statement. The value in the support column indicates
whether an engine can be used. A value of yes, no, or default indicates that an engine is available,
not available, or available and currently set as the default storage engine. Through this manual, we
are going to use InnoDB storage engine. In the figure below, MyISAM is set a default engine.

Figure 14, MySQL 5.7.11 supported storage engines

You can specify your table storage engine in the create table statement after closing the closing
bracket and before the terminating semicolon. The statement below create a table called module
with MyISAM storage engine.

12
SQL – The Database Language | Shabani Juma Bakari

create table department


(
deptID int auto_increment,
deptCode varchar(50) not null unique,
deptName text not null,
primary key(deptID)
)engine=MyISAM;

Alternatively, you can skip including the engine specification in the include table statement by
setting your default storage Engine in the MySQL configuration file called my.in or my.cnf
(C:\wamp\bin\mysql\mysql5.7.11\my.in). In that file, locate line with default-storage-engine and set
it to your preferred engine.

WORKING WITH DATA IN MYSQL DATABASE

<The following tables will be used as examples>

department
deptID deptCode deptName

program
progID progName capacity ntaLevel department

student
studentID fullName gender dob nationality maritualStatus program YoE active status

courses
courseID courseCode courseName credit elective elective

enrollment
studentID courseCode semester aYear

So far we have been working with the Data definition Language (DDL) statements. From this part
on wards, we will be working with the Data Manipulation language (DML) statements. The DML
are used to perform the four basic database operations, insertion, deletion, modification and retrieve.

13
SQL – The Database Language | Shabani Juma Bakari

Insert Statement
This is a DML statement that enables you to enter (add) new row of data into your database table.
A single insert statement can add data to a single table.
The structure of the insert statement is;

INSERT INTO <table_name> (field list separated by comma) VALUES (value list inside quotes
separated by comma);

Example: The below statement is used to insert a single row of data into the table named COURSES

INSERT INTO courses (courseCode, courseName, credit, elective) VALUES


('LTU 07101', 'Road Transport Management', 15, null);

NB:
1. The into keyword is actually optional. However, you will usually see it included in insert
statements because it makes them more readable.
2. If you try to execute an insert statement with the wrong number of columns, MySQL will
give an error and the insert will fail.
3. Null Columns If you do not give a value for a column that has the not null constraint and
also does not have a default value, the insert will fail.

Inserting Multiple Rows


You can insert several rows in a single insert statement by supplying multiple lists of values. Each
list must be enclosed in parentheses and separated by a comma.

The following statement inserts four new rows into the COURSES table:

INSERT INTO courses (courseCode, courseName, credit, elective) VALUES


('LTU 07102', 'Managerial Accounting', 12, null),
('LTU 07103', 'Transport Statistics', 12, null),
('LTU 07206', 'Inter-Modal Transport', 15, null),
('LTU 07208', 'Transport Finance', 12, null);

If one of the rows in a multiple insert statement causes an error (for instance, a duplicate value in a
unique column), the insert will fail. The values are inserted in sequence, however, the rows before
the one that caused the error will have already been inserted into the database.

Update Statement
The update statement is used to change one or some of the values in a data row. You include a
where clause to indicate that this row or rows are to be updated.

NB: Leaving Where Clause

14
SQL – The Database Language | Shabani Juma Bakari

Without a where clause, update performs the same update on every row in the table. Unless this is
the result you want, always include a where clause in an update statement. You specify the values
to be changed in a list after the set keyword, separated with commas.

The following example updates the name and elective of an existing course with
courseCode = LTU 07101.

UPDATE courses SET courseName ='Surface Transport', elective ='yes' WHERE courseCode=
‘LTU 07101’;

Updating with a Derived Column


Before continuing, add a new column to the student table called EYoG (stand for Expected Year
of Graduation) with a data type of integer of size four.
Alter table student add EYoG int (4);

Then update the EYoG field of all students follows (Assuming that student graduate three years
after the year of entry (YoE))
UPDATE student SET EYoG =YoE +3;

Delete Statement
The DELETE statement is used to remove data rows from a table. You supply a table name after
the keyword FROM and use a WHERE clause to filter the rows that are to be deleted. That is

DELETE FROM <table_name> WHERE <field_name>= ‘field_value’;

NB: Leaving Where Clause


Without a WHERE clause, DELETE deletes every rows from the given table. Unless this is the
result you want, always make sure that you include a WHERE clause in a DELETE statement.

To delete only a single row from a table, you should ensure that the WHERE clause will match only
that row. Usually, you should check the value of the table's PRIMARY KEY column to ensure that
an exact match is found.

The following example deletes one of the course with code ITT 04101L that you inserted in the
previous section
DELETE FROM courses WHERE courseCode='ITT 04101L';

15
SQL – The Database Language | Shabani Juma Bakari

SELECT STATEMENT

The first SQL command you will learn, and the one you will use most frequently, is select. In this
lesson, you begin by learning how to fetch data records from a single table.

A select statement begins with the select keyword and is used to retrieve information from MySQL
database tables. You must specify the table name to fetch data from using the from key word and
one or more columns that you want to retrieve from that table.

SQL statement begins with a keyword and can contain several more keywords that must appear in
the correct, structured way known as the statement's syntax.

Retrieving Individual Columns


To retrieve individual column of a table, the syntax is:
SELECT <column_name> FROM <table_name>;

For example, the following statement will retrieve department name (deptName) column of the
department table.
SELECT deptName FROM department;

The output of the statement above is shown below

Figure 15; retrieving single column


The department table contains three columns. In this statement, we tell MySQL to fetch the value
of the deptName column; this is displayed for every record in the table.

Retrieving Multiple Columns


Now you'll try another simple SELECT statement, this time on the sellers table. You can retrieve
the values from two columns in the same query by specifying a list of columns after the SELECT
keyword, separating them with a comma. For example, the following statement will retrieve
department code (deptCode) and department name (deptName) columns of the department table
SELECT deptCode, deptName FROM department;

16
SQL – The Database Language | Shabani Juma Bakari

The output of the statement above is shown below

Figure 16; retrieving multiple columns of a the same table

Retrieving All Columns


If you want to retrieve the data from every column in a table, you do not need to specify each column
name after the select keyword. Use the asterisk character (*) in place of a column list in a select
statement to instruct MySQL to return every column from the specified table.

The following query retrieves every column and row from the department table
SELECT * FROM department;

The output of the above query is shown below

Figure 17; retrieving all columns of a table

Counting Number of Records


The SQL COUNT function is used to count the number of rows returned in a SELECT statement.
For example, the query below counts the number of records (rows) in the enrollment table.

17
SQL – The Database Language | Shabani Juma Bakari

SELECT COUNT(*) FROM enrollment;

Figure 18; counting number of rows (records) in a table

FILTERING OUTPUT WITH WHERE CLAUSE

You can add a where clause to a select statement to tell MySQL to filter the query results based on
a given rule. Rules in a where clause refer to data values returned by the query, and only rows in
which the values meet the criteria in the rule are returned.

Filtering on an Exact Value


The simplest type of filter in a where clause uses the equals operator (=) to specify that a data value
must match a given value exactly.
The following query retrieves all the programs with capacity value of 200 from program table.
SELECT progName, capacity FROM program WHERE capacity= 200;

The output of the statement above is shown here under

Figure 19, filtering the output on exact value using equality operator

In this example, rows from department are returned only if the value of capacity in that row is equal
to 200. To perform a condition using an inequality, use the != operator. This works just the same as
=, but the condition returns only rows in which the table value is not equal to the value given in the
condition.

For instance, the following query finds all program except for those with a capacity of 100
SELECT progName, capacity FROM program WHERE capacity != 1000;

The output of the statement above is shown below

18
SQL – The Database Language | Shabani Juma Bakari

Figure 20, filtering the output on exact value using inequality operator

Filtering on a Range of Values


In addition to the equality operator, you can use a set of operators to select rows based on a range
of values. Use the symbols < and > to test whether one value is less than or greater than another
value, respectively. When followed by an = symbol, these operators also match equal values. The
symbol sequence >= means "is greater than or equal to," whereas <= means "is less than or equal
to."

To find only programs for which the capacity is 100 or less, use the following query

SELECT progName, capacity FROM program WHERE capacity <= 100;

The output of the above statement is shown below

Figure 21, filtering the output on range of value

19
SQL – The Database Language | Shabani Juma Bakari

The range operators can be performed on textual data, and the results are logical. For example,
performing a greater-than comparison on the department name (deptName) field returns only values
that are alphabetically higher than the given value.
SELECT deptName FROM department WHERE deptName >= ‘S’;

The output of the statement is shown below

Figure 22, filtering the output on range of value

Although the usual convention in a where clause is where column = 'value', this ordering is not
significant. The following query demonstrates that the order can be reversed without affecting the
outcome
SELECT deptName FROM department WHERE ‘S’ >= deptName;

The output is:

Figure 23, filtering the output on range of value reversing the operator

The LIKE Clause


The SQL like clause is used to compare a value to similar values using wildcard operators. There
are two wildcards used in conjunction with the LIKE operator:
i. The percent sign (%)
ii. The underscore (_)

The percent sign represents zero, one, or multiple characters. The underscore represents a single
number or character. The symbols can be used in combinations.

20
SQL – The Database Language | Shabani Juma Bakari

Syntax:

The basic syntax of % and _ is as follows:

SELECT FROM table_name WHERE column LIKE 'XXXX%'


or
SELECT FROM table_name WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name WHERE column LIKE '_XXXX'
or
SELECT FROM table_name WHERE column LIKE '_XXXX_'

You can combine N number of conditions using AND or OR operators. Here, XXXX could be any
numeric or string value.

Example

Here are number of examples showing WHERE part having different LIKE clause with '%' and '_'
operators

Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third
positions
WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3
characters in length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and
end with a 3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2
and end with 3

SORTING OUTPUT WITH GROUP BY CLAUSE

Sorting on a Single Column


The following example retrieves all department names in order of their deptCode. The keywords
ORDER BY are followed by the name of the column on which you want to sort.
SELECT deptName FROM department ORDER BY deptCode;

21
SQL – The Database Language | Shabani Juma Bakari

Figure 24, sorting the output of a select statement

NB: The sort column specified in order by is not necessary to appear in the list of columns after
the select keyword. You can therefore specify a sort order using a column that is not retrieved by
the query.

When you want to add sorting to a query that is also filtered, the order by clause must appear after
the where clause. This example finds all students taking BCICT program in the order of their
names:
SELECT studentID, fullName, gender FROM student WHERE program= ‘BCICT’ ORDER BY
fullName;

Figure 25, filtering and sorting the output in the same query

22
SQL – The Database Language | Shabani Juma Bakari

Sorting on Multiple Columns


The order by clause is formed in a similar way to the first line of a select statement. If you want to
specify a sort order that involves more than one column in the query, separate the column names
with a comma.

The following query fetches enrolment records of a student with registration number
NIT/BCICT/2017/77 from enrollment table in academic year (aYear) order. The second sort
column, courseCode, is used to specify the sorting when the values of aYear are the same.

SELECT * FROM enrollment WHERE studentID=‘NIT/BCICT/2017/77’ ORDER BY aYear,


courseCode;

Figure 26, sorting on multiple columns

Specifying Sort Order


By default, the ordering on a column specified in the order by clause is done in ascending order,
either numerically or alphabetically, depending on the data type of the column.

To specify a descending sort direction, use the desc keyword. To specify an ascending order sort
direction (which is the default) use asc keyword. The following example sorts the names of students
taking BCICT from the students table in order of names (fullName) with the heaviest at the top of
the list.

SELECT studentID, fullName, gender FROM student WHERE program= ‘BCICT’ ORDER BY
fullName DESC;

23
SQL – The Database Language | Shabani Juma Bakari

Figure 27, specifying sort order

Combining WHERE Clauses


The examples you have seen so far perform filtering on a query based on only a single condition.
To provide greater control over a result set, MySQL enables you to combine a number of conditions
in a where clause. They are joined using the logical operator keywords and and or.

Using the AND Operator


After adding a where clause to filter a query, you can filter the results further by adding another
condition with the AND operator. This is commonly used to restrict the query results based on the
values of two or more columns.

Below is a statement used to extract program ID, department and capacity records for program with
capacity less than 500 and the department equal to CCT and its output:

SELECT progID, capacity, department FROM program WHERE capacity < 500 AND department
= ‘CCT’;

24
SQL – The Database Language | Shabani Juma Bakari

Figure 28, Using AND logic in the WHERE clause

NB: AND For a query row to be returned, the table data in question must satisfy all the conditions
separated by an AND operator. If any one condition fails for a record, that record is filtered out.

Using the OR Operator


Whereas the AND operator specifies a filter that further restricts the number of rows returned by a
query, the OR operator is used to relax the filtering criteria by specifying alternative filter
conditions. If one or more of the conditions separated by an OR operator hold true for a row in the
table, that record will appear in the query results.

Below is a statement used to extract program ID, department and capacity records for program with
capacity less than 300 or the department equal to Aviation (AVI) and its output:

SELECT progID, capacity, department FROM program WHERE capacity < 300 OR department
= ‘AVI’;

Figure 29, Using OR logic in the WHERE clause

25
SQL – The Database Language | Shabani Juma Bakari

Filtering on Multiple Values


You could use the OR operator with equals conditions to specify multiple filter values for the same
column. For example, the query below extract program ID, department and capacity records for
program with capacity 200 or 100 or 50 and its output below.
SELECT progID, capacity, department FROM program WHERE capacity = 200 OR capacity =
100 OR capacity = 50;

Figure 30, Filtering on multiple values of the same column using OR logic
However, because this is a relatively common type of filter, there is a handy shortcut. You can use
the IN (for equality) or BETWEEN (for a range) operator to perform exactly this type of filter in a
single condition. IN works like multiple equals operators and takes a comma-separated list of
values, enclosed in parentheses/brackets.
Consider the statement below which perform the same action like the previous one
SELECT progID, capacity, department FROM program WHERE capacity IN (200, 100, 50);

Figure 31, Filtering on multiple values of the same column using IN keyword

26
SQL – The Database Language | Shabani Juma Bakari

The next query extract program ID, department and capacity records for program with capacity
between 50 and 200 inclusively and its output below.
SELECT progID, capacity, department FROM program WHERE capacity BETWEEN 50 AND
200;

Figure 32, Filtering on multiple values of the same column using BETWEEN keyword

Limiting Number of Rows Returned


If you are expecting a query to still return more rows than you want, even with the filtering from a
where clause applied, you can add a limit clause to specify the maximum number of records to be
returned.

The following example retrieves all the rows from the department table, but the LIMIT clause
restricts the number of rows returned to five.

SELECT * FROM department LIMIT 5;

Figure 33, Limiting number of rows using the LIMIT keyword

27
SQL – The Database Language | Shabani Juma Bakari

Skipping Rows
If the limit clause contains two numbers separated by a comma, the first is an offset argument and
the second is the number of rows to return. The offset specifies the number of rows to skip before
returning the first record.

The next two queries show this in action. First select all the department and show just the first four
rows.
SELECT * FROM department LIMIT 4;

Figure 34a, displaying first four rows using LIMIT keyword

The next query uses an offset value to show the next five rows from the query result.
SELECT * FROM department LIMIT 4, 5;

Figure 34b, skipping the first four rows and displaying the next five rows

NB: Skipping Rows


Remember that the offset value in a LIMIT clause is the number of rows to skip, not the number of
the first row to display. LIMIT 5 is equivalent to LIMIT 0,5 not LIMIT 1,5.

SELECTION WITH RENAME

Selection with Alternative Column Name


With SQL, you can select data from table while you rename the table column header to a well
readable heading using AS keyword. For example, the statement below renames the deptID to

28
SQL – The Database Language | Shabani Juma Bakari

department ID, deptCode to department Code and deptName to department Name for the previous
query.
SELECT deptID AS ‘Department ID’, deptCode AS ‘Department Code’, deptName AS ‘Department
Name’ FROM department LIMIT 4, 5;

Figure 35, Renaming Column using AS keyword in select statement

Selection with Alternative Table Name


The AS keyword can also be used to rename the table name. For example, the statement below
renames the table department to D in the previous query.

SELECT D.deptID AS ‘Department ID’, D.deptCode AS ‘Department Code’, D.deptName AS


‘Department Name’ FROM department AS D LIMIT 4, 5;

Figure 36, Selection with alternative table name

JOINING TABLES USING WHERE CLAUSE

To join two tables, give both their names in the from clause of a select statement. To indicate the
relationship between the two tables, you must include an appropriate condition in the where clause.

The following query joins the program and department tables to produce the complete working
information from the university database. In the program table we select the program ID, capacity
and NTA Level. From the department table we take the department name. The where condition

29
SQL – The Database Language | Shabani Juma Bakari

tells MySQL that the relationship between the tables is that the department value in program table
is a reference to the deptCode column in department table. We limit the output to 10 rows.
SELECT progID, capacity, ntaLevel, deptName FROM program, department WHERE
program.department=department.deptCode ORDER BY progID LIMIT 10;

Figure 37, Joining two tables using WHERE clause

The following query joins the student, program and department tables to produce the complete
working information from the university database. In the student table, we retrieve the student ID
and full name, from the program table we select the program ID and NTA Level. From the
department table we take the department name. The where condition tells MySQL that the
relationship between student table is that the program value in the student table is a reference to the
progID in the program table and the department value in program table is a reference to the
deptCode column in department table. We limit the output to 15 rows.

SELECT S.studentID, S.fullName, P.progID, P.ntaLevel AS NTA, D.deptName FROM student AS


S, program as P, department AS D WHERE S.program=P.progID AND P.department=D.deptCode
ORDER BY D.deptCode LIMIT 15;

Figure 38, Joining three tables using WHERE clause

30
SQL – The Database Language | Shabani Juma Bakari

JOINING TABLES USING JOIN

JOIN is an SQL keyword used to query data from two or more related tables. There are different
types of MySQL joins but the common are:

i. MySQL INNER JOIN (or sometimes called simple join)


ii. MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
iii. MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)

INNER JOIN (simple join)


The most frequently used and important of the joins is the inner join. They are also referred to as
an equijoin.

The inner join creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of
table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied,
column values for each matched pair of rows of A and B are combined into a result row.

Figure 39, SQL Inner Join


Syntax
The syntax for the INNER JOIN in MySQL is:
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;

The following query select three fields from the program table and one field on the department table
using the inner join.
SELECT progID, capacity, ntaLevel, deptName FROM program INNER JOIN department
ON program.department=department.deptCode ORDER BY progID LIMIT 10;

31
SQL – The Database Language | Shabani Juma Bakari

Figure 40, joining two tables using inner join

The above query could be written without the use of the join keyword. A WHERE clause could be
used to write inner join as shown in the query below which work similar to the previous one.

SELECT progID, capacity, ntaLevel, deptName FROM program, department WHERE


program.department=department.deptCode ORDER BY progID LIMIT 10;

Left Outer Join


The SQL left join returns all rows from the left table, even if there are no matches in the right table.
This means that if the ON clause matches 0 (zero) records in right table, the join will still return a
row in the result, but with null in each column from right table.

This means that a left join returns all the values from the left table, plus matched values from the
right table or null in case of no matching join predicate.

Figure 41, SQL Left Join


Syntax:
The basic syntax of LEFT JOIN is as follows:

SELECT table1.column1, table2.column2... FROM table1 LEFT JOIN table2


ON table1.common_field = table2.common_field;

The following query select three columns from the program table and one column from the
department table joining them using the left join. The results of the query is all rows of the left table

32
SQL – The Database Language | Shabani Juma Bakari

regardless that the row contain a matching value of departmentID on the right table. The rows
without a match contain the null value.

SELECT deptName, progID, capacity, ntaLevel FROM department LEFT OUTER JOIN program
ON department.deptCode = program.department ORDER BY deptCode DESC LIMIT 10;

Figure 42, joining two tables using left join

NB: OUTER keyword


The query is written with “LEFT OUTER JOIN”. It can also be written using the “LEFT JOIN”
leaving the word OUTER and will produce the same results.

Right Outer Join


The SQL right join returns all rows from the right table, even if there are no matches in the left
table. This means that if the ON clause matches 0 (zero) records in left table, the join will still return
a row in the result, but with NULL in each column from left table. This means that a right join
returns all the values from the right table, plus matched values from the left table or NULL in case
of no matching join predicate.

Figure 43, SQL Right Join


Syntax:
The basic syntax of RIGHT JOIN is as follows:
SELECT table1.column1, table2.column2... FROM table1 RIGHT JOIN table2
ON table1.common_field = table2.common_field;

33
SQL – The Database Language | Shabani Juma Bakari

The following query select three columns from the program table and one column from the
department table joining them using the right join.
SELECT deptName, progID, capacity, ntaLevel FROM program RIGHT JOIN department ON
department.deptCode=program.department ORDER BY deptCode DESC LIMIT 10;

Figure 44, SQL Right Join

Join Statement for More Than Two Tables


Here is a general SQL query syntax to join three or more table. This SQL query should work in all
major relation database

SELECT table1.column1, table2.column2, table3.column3….. FROM table1


<JOIN> table2 ON table1.common_field = table2.common_field
<JOIN> table3 ON table2.common_field = table3.common_field

We first join table 1 and table 2 which produce a temporary table with combined data from table1
and table2, which is then joined to table3. This formula can be extended to more than 3 tables to N
tables. You just need to make sure that SQL query should have N-1 join statement in order to join
N tables.

The following query joins the student, program and department tables to produce the complete
working information from the university database. In the student table, we retrieve the student ID
and full name, from the program table we select the program ID and NTA Level. From the
department table we take the department name. We first join student table with program table to
generate a temporary table. Then we use another join statement to join the temporary table with the
department. We limit the output to 15 rows.

SELECT S.studentID, S.fullName, P.progID, P.ntaLevel AS NTA, D.deptName FROM student AS S


LEFT JOIN program as P ON S.program = P.programID LEFT JOIN department AS D ON
P.department = D.deptCode ORDER BY D.deptCode LIMIT 15;

34
SQL – The Database Language | Shabani Juma Bakari

Figure 45, SQL join for three tables

SQL GROUP BY

The SQL group by clause is used in collaboration with the select statement to arrange identical
data into groups. The group by clause follows the where clause in a select statement and precedes
the order by clause. The basic syntax of group by clause is given below.
SELECT column1, column2 FROM table_name WHERE [ conditions ]
GROUP BY column1, column2, columnN
ORDER BY column1, column2, columnN
Consider the following query that retrieve all enrolment records from the enrollment table in the
limiting the output to 20 rows.

SELECT studentID, courseCode, semester, aYear FROM enrollment LIMIT 20;

35
SQL – The Database Language | Shabani Juma Bakari

Figure 46, retrieving the first 20 records of the enrollment table

The select statement above returned the first twenty rows found in the enrollment table. However,
all rows are repeating (same studentID). With that query, it is very difficult to know how many
different different students have been enrolling in one different module.

The following query retrieve the students that have been enrolled is some module from the
enrollment table giving the total number of module each student enrolled. The query use group
keyword to group item of the same type in a single row and a count keyword to count the module
codes for every student.

SELECT studentID, count(courseCode), semester, aYear FROM enrollment GROUP BY studentID


LIMIT 10;

36
SQL – The Database Language | Shabani Juma Bakari

Figure 47, retrieving the first 10 records of the enrollment table by grouping on student ID

The results above shows that all the 10 students (each in a separate row) took 21 modules in the
first semester of the academic year 2016/2017. That output is wrong as for those students, 21
modules is a total of number of modules they enrolled in the four semesters of the two academic
years. Thus, in order to come up with the correct records of the semesters and academic years, two
more columns should be added in the group by as shown in the query below.

SELECT studentID, COUNT(courseCode), semester, aYear FROM enrollment GROUP BY


studentID, semester, aYear LIMIT 10;

Figure 48, retrieving the first 10 records of the enrollment table by grouping on three columns

MySQL HAVING

The MySQL having clause is used in the select statement to specify filter conditions for a group of
rows or aggregates.

37
SQL – The Database Language | Shabani Juma Bakari

The MySQL having clause is often used with the group by clause. When using with the group by
clause, we can apply a filter condition to the columns that appear in the group by clause. If the
group by clause is omitted, the having clause behaves like the where clause.

Notice that the having clause applies the filter condition to each group of rows, while the where
clause applies the filter condition to each individual row.

For example, we can write the a query to sum all the module taken by each student in the enrollment
table as follows.

SELECT studentID, Count(courseCode) From enrollment GROUP BY studentID ;

The output of this query is similar to the one shown in figure 47 above except that this query doesn’t
have a limit and also it omitted the two columns of semester and academic year. The we can rewrite
the same query so that to get all students with a specified number (sum/total) of courses as shown
in the query below which display student with at least 20 courses.

SELECT studentID, count(courseCode) from enrollment group by studentID HAVING


count(courseCode) >=20 ;

Figure 49, filtering using HAVING keyword

38
SQL – The Database Language | Shabani Juma Bakari

SQL DISTINCT

The SQL distinct keyword is used in conjunction with select statement to eliminate all the duplicate
records and fetching only unique records without using group by keyword.

Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:

SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition]

Consider the following query that retrieve student ID from the enrollment table in the limiting the
output to 10 rows and skipping any duplicate student ID.

SELECT DISTINCT studentID FROM enrollment LIMIT 10;

Figure 50, retrieving unique records using distinct keyword

NB: GROUP BY vs DISTINCT


Group by is more usefully when you want to perform a calculation on duplicate rows, otherwise use
distinct.

SQL SUB-QUERIES

A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.

A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.

39
SQL – The Database Language | Shabani Juma Bakari

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN etc.

There are a few rules that subqueries must follow:

1. Subqueries must be enclosed within parentheses.


2. A subquery can have only one column in the SELECT clause, unless multiple columns are
in the main query for the subquery to compare its selected columns.
3. An ORDER BY cannot be used in a subquery, although the main query can use an ORDER
BY. The GROUP BY can be used to perform the same function as the ORDER BY in a
subquery.
4. Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.
5. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.
6. A subquery cannot be immediately enclosed in a set function.
7. The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
operator can be used within the subquery.

The basic syntax is as follows:

SELECT table1.column1, table2.column2


FROM table1, table2 WHERE table.columnName OPERATOR
(SELECT table3.column3, table4.column4 FROM table3, table3 [WHERE] )

For example, the following statement uses sub-query to select enrolment records from enrollment
table for all students doing BCICT program. Because the data are extracted from enrollment table
which does not contain the program, a subquery is used to find studentID from the student table
with matching the criteria (program=BCICT) the results of this sub-query which is a list of
studentID are used as the values in the IN parenthesis of the outer query. The outer (main query)
group the output by studentID, semester and academic Year, limiting the output to 12 rows.

SELECT studentID, count(courseCode), semester, aYear FROM enrollment WHERE studentID IN


(select studentID from student WHERE program = 'BCICT') GROUP BY studentID, semester,
aYear LIMIT 12;

40
SQL – The Database Language | Shabani Juma Bakari

Figure 51, using subquery in select statement

41

Das könnte Ihnen auch gefallen