SQL - The Database Language PDF
SQL - The Database Language PDF
ii
SQL – The Database Language | Shabani Juma Bakari
LIST OF FIGURES
iv
SQL – The Database Language | Shabani Juma Bakari
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
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”.
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”.
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;
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.
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.
If you attempt to connect to a database which is not available, you mistype the name, an error
message will appear.
Figure 7, showing connection status and the name of the database in use.
4
SQL – The Database Language | Shabani Juma Bakari
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.
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
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.
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
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.
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.
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.
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.
8
SQL – The Database Language | Shabani Juma Bakari
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.
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
9
SQL – The Database Language | Shabani Juma Bakari
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.
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:
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.
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.
Below is example of sql ctreate table statement that create the two tables, department (parent) and
program (child).
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.
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.
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.
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.
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
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.
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
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.
The following statement inserts four new rows into the COURSES table:
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.
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’;
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
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.
For example, the following statement will retrieve department name (deptName) column of the
department table.
SELECT deptName FROM department;
16
SQL – The Database Language | Shabani Juma Bakari
The following query retrieves every column and row from the department table
SELECT * FROM department;
17
SQL – The Database Language | Shabani Juma Bakari
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.
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;
18
SQL – The Database Language | Shabani Juma Bakari
Figure 20, filtering the output on exact value using inequality operator
To find only programs for which the capacity is 100 or less, use the following query
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’;
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;
Figure 23, filtering the output on range of value reversing the operator
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:
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
21
SQL – The Database Language | Shabani Juma Bakari
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
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.
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
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
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.
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’;
25
SQL – The Database Language | Shabani Juma Bakari
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
The following example retrieves all the rows from the department table, but the LIMIT clause
restricts the number of rows returned to five.
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;
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
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;
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;
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.
30
SQL – The Database Language | Shabani Juma Bakari
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:
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.
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
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.
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.
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;
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;
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.
34
SQL – The Database Language | Shabani Juma Bakari
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.
35
SQL – The Database Language | Shabani Juma Bakari
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.
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.
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.
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.
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:
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.
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.
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.
40
SQL – The Database Language | Shabani Juma Bakari
41