Structured Query Language Introduction To SQL
Structured Query Language Introduction To SQL
History of SQL
The history of SQL begins where SQL was developed in the late 1970s in an IBM laboratory. It was
originally developed for IBM's DB2 product. An ISO standard now exists for SQL, making it both the
formal and de facto standard language for relational databases. ORACLE was probably the first
commercial RDBMS based on SQL.
So the ANSI-SQL group has published three standards over the years:
• SQL89 (SQL1)
• SQL92 (SQL2)
• SQL99 (SQL3)
The vast majority of the language has not changed through these updates. We can all profit from the fact
that almost all of the code we wrote to SQL standards of 1989 is still perfectly usable. Or in other words,
as a new student of SQL there is over ten years of SQL code out there that needs your expertise to
maintain and expand.
Most DBMS are designed to meet the SQL92 standard. Virtually all of the material in this book was
available in the earlier standards as well. Since many of the advanced features of SQL92 have yet to be
implemented by DBMS vendors, there has been little pressure for a new version of the standard.
Nevertheless a SQL99 standard was developed to address advanced issues in SQL. All of the core
functions of SQL, such as adding, reading and modifying data, are the same.
The Relational Model defines two root languages for accessing a relational database -- Relational
Algebra and Relational Calculus.
Relational Algebra is a low-level, operator-oriented language. Creating a query in Relational
Algebra involves combining relational operators using algebraic notation.
Relational Calculus is a high-level, declarative language. Creating a query in Relational Calculus
involves describing what results are desired.
SQL is about data and results, each SQL statement returns a result, whether that result be a query, an
update to a record or the creation of a database table. SQL is most often used to address a relational
database, which is what some people refer to as a SQL database.
Main characteristics of SQL
SQL allows you to access a database
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert new records in a database
SQL can delete records from a database
-1-
ZAMBIA ICT COLLEGE BIT 260 @DMS
SQL can update records in a database
It also supports simple and complex queries. It must perform these tasks with minimal user
effort.
The command structure and syntax must be easy to learn.
It is portable.
Importance of SQL
SQL is different from other programming languages such as Java, C++, Visual Basic and other Third
Generation Languages (3GL) which are considered to be procedural or object oriented. SQL is a non-
procedural or declarative language, which means instead of you controlling how the program should run,
you tell the program what you want and it figures out how that should be achieved.
SQL is split into four sub languages, each dealing with specific parts of the Codd‘s original requirements
list of the common language, being creation of the database, manipulation of the data and management of
security. The four sub languages are.
1. Data Definition Language (DDL) allows for the design (Schema) of the database to be defined.
Creating tables, fields and rules for data entry are some of the main functions of the DDL. DDL
statements are used to define the database structure or schema. Some examples:
2. Data Manipulation Language (DML) allows for the querying and manipulation of the data in the
database. Questions can be posed of the data and results of such queries returned. Select, update,
insert and delete are common requests found within the sublanguage. DML statements are used for
managing data within schema objects. Some examples:
3. Data Control Language (DCL) tends to be something the database administrator would use to
handle security of the database. DCL statements. Some examples:
4. Transaction Control (TCL) statements are used to manage the changes made by DML statements.
It allows statements to be grouped together into logical transactions.
o SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use
-4-
ZAMBIA ICT COLLEGE BIT 260 @DMS
SQL queries to Truncate, Drop or Rename a Table
Truncate command
Truncate command removes all records from a table. But this command will not destroy the table's
structure. When we apply truncate command on a table its Primary key is initialized.
Truncate command is different from delete command. Delete command will delete all the rows from a table
whereas truncate command re-initializes a table (like a newly created table).
________________________________________
4) Drop command
drop query completely removes a table from database. This command will also destroy the table structure.
Following is its Syntax,
drop table table-name
________________________________________
B) DML: Data Manipulation Language
Data Manipulation Language (DML) statements are used for managing data in database. DML commands
are not auto-committed. It means changes made by DML command are not permanent to database, it can be
rolled back.
________________________________________
1) INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
INSERT into table-name values(data1,data2,..)
Lets see an example,
Consider a table Student with following fields.
S_id S_Name age
-5-
ZAMBIA ICT COLLEGE BIT 260 @DMS
________________________________________
Example to Insert NULL value to a column
Both the statements below will insert NULL value into age column of the Student table.
INSERT into Student(id,name) values(102,'Alex');
Or,
INSERT into Student values(102,'Alex',null);
The above command will insert only two column value other column is set to null.
S_id S_Name age
101 Adam 15
102 Alex
________________________________________
Example to Insert Default value to a column
INSERT into Student values(103,'Chris',default)
-6-
ZAMBIA ICT COLLEGE BIT 260 @DMS
Consider the following Student table
S_id S_Name age
101 Adam 15
102 Alex 18
103 Abhi 17
DELETE from Student where s_id=103;
The above command will delete the record where s_id is 103 from Student table.
S_id S_Name age
101 Adam 15
102 Alex 18
________________________________________
This point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to
login (with his username and password), they will not be able to reach the MySQL shell.
Therefore, the first thing to do is to provide the user with access to the information they will need.
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
The asterisks in this command refer to the database and table (respectively) that they can access—this
specific command allows to the user to read, edit, execute and perform all tasks across all the databases and
tables.
-7-
ZAMBIA ICT COLLEGE BIT 260 @DMS
Once you have finalized the permissions that you want to set up for your new users, always be sure to
reload all the privileges.
FLUSH PRIVILEGES;
Your changes will now be in effect.
To provide a specific user with a permission, you can use this framework:
GRANT [type of permission] ON [database name].[table name] TO ‗[username]‘@'localhost‘;
If you want to give them access to any database or to any table, make sure to put an asterisk (*) in the place
of the database name or table name.
Each time you update or change a permission be sure to use the Flush Privileges command.
If you need to revoke a permission, the structure is almost identical to granting it:
REVOKE [type of permission] ON [database name].[table name] FROM‗[username]‘@‗localhost‘;
Just as you can delete databases with DROP, you can use DROP to delete a user altogether:
DROP USER ‗demo‘@‗localhost‘;
SQL expresses queries in declarative way – queries specify the properties of the result, not the way to
obtain it. Queries are translated by the query optimizer into the procedural language internal to the
DBMS. The programmer should focus on readability, not on efficiency.
A query in SQL can consist of up to six clauses, but only the first two are mandatory.
A query is evaluated by first applying the WHERE-clause, then GROUP BY and HAVING, and finally
the SELECT-clause. The order of the clauses cannot be changed. The following is a brief description of
each of the reserved words:
The two table instances below are used to illustrate various queries. An employee name (first plus
surname) is unique. The department name is unique. An employee must work in one department.
EMPLOYEE
FirstName Surname Dept Office Salary City
Mary Brown Administration 10 45 London
Charles White Production 20 36 Toulouse
Gus Green Administration 20 40 Oxford
Jackson Neri Distribution 16 45 Dover
Charles Brown Planning 14 80 London
Laurence Chen Planning 7 73 Worthing
Pauline Bradshaw Administration 75 40 Brighton
Alice Jackson Production 20 46 Toulouse
DEPARTMENT
DeptName Address City
Administration Bond Street London
Production Rue Victor Hugo Toulouse
Distribution Pond Road Brighton
Planning Bond Street London
Research Sunset Street San José
The rest of this section presents various sample queries, their SQL solutions and expected output
based on the above schema:
FirstName Surname
in:FirstNam Green
Gus
e
Q7: Using predicate disjunction
Find the first names and surnames of the employees who work in either the
Administration or the Production department.
SELECT FirstName, Surname
FROM Employee
WHERE Dept = ‘Administration‘ OR
Dept = ‘Production‘;
This results in:
FirstName Surname
Mary Brown
Charles White
Gus Green
Pauline Bradshaw
Alice Jackson
- 12 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
WHERE Surname LIKE ‘_r%n‘;
This results in:
FirstName Surname Dept Office Salary City
Mary Brown Administration 10 45 London
Gus Green Administration 20 40 Oxford
Charles Brown Planning 14 80 London
We will use another example to illustrate other concepts of SQL queries. The schema
below presents a database snapshot (i.e. a schema instance) for an estate agent2.
Owner
Ono FNam LNam Addres Tel_No
e
CO40 Tina e
Murphy s
63 Well St, Shawlands, Glasgow G42 0971728
CO46 Joe Keogh 2 Fergus Dr, Banchory, Aberdeen 26861212
CO87 Carol Farrel 6AB2 7SXSt, Glasgow G32 9DX
Achray 457419
CO93 Tony Shaw 12 Park Pl, Hillhead, Glasgow G4 687025
Branch 0Q4
Bno Street Area City Pcode Tel_no Fax_no MgrN
B2 56 Clover London NW10 6661030 997992 o
SG5
B3 163Dr Main St Patrick Glasgow G11 6EU 9QX 7772178 45564439 SL21
B4 32 Manse Leigh Bristol BS99 1NZ 9001170 561114 SL21
B5 Rd 22 Deer Rd Sidcup London SW1 4EH 7881212 9812149 SG5
B7 16 Argyll Dyce Aberdee AB2 3SU 6777980 56889009 SG5
Property n
Pno Street Area City Pcode Typ Room Rent Ono Sno Bno
PA1 16 Holhead Dee Aberdee AB7 e
H s 6 £650.0 CO46 SA9 B7
PG1 5 Novar Dr Hyndlan Glasgown 5SU
G12 F 0
4 £450.0 CO93 SG14 B3
d
PG2 8 Dale Rd Hyndlan Glasgow G12 9AX H 0
5 £600.0 CO87 SG37 B3
PG3 2 Manor Rd d Glasgow G32 F 0
3 £375.0 CO93 SG37 B3
PG4 6 Lawrence Patrick Glasgow G11 4QX F 0
3 £350.0 CO40 SG14 B3
St
PL9 6 Argyll St Kilburn London NW2 9QX F 0
4 £400.0 CO87 SL41 B5
4
Renter 0
Rno FNam LNam Addres Tel_No Pref_Typ Max_Re
e
CR5 Aline e
Stewart s
64 Fern Dr, Pollock, Glasgow, 6799089 e
Flat nt $350.0
6
CR6 Mary Tergear 5G42 Tarbot Rd, Kildary, 7888965 Flat 0
$600.0
2
CR7 Mike Ritchie 18 Aberdeen
Tain St,AB9
Gourock PA1G 459908 House 0
$750.0
4CR7 John Kay 1YQ
56 High St, Puttney, London 4589006 Flat 0$425.0
6
Viewing SW1 0
Pno Rno Date Comment
PA14 CR56 24-May-95 too small
PA14 CR62 14-May-95 no dining room
PG36 CR56 28-Apr-95
PG4 CR56 26-May-95
PG4 CR76 20-Apr-95 too remote
Staff
Sno FName LName Address Tel_No Position Sex Salary DOB NIN Bno
SA9 Mary Howe 2 Elm Pl, Aberdeen Assistant F £9,000.0 19/2/70 WM5321 B7
SG1 David Ford AB2
63 Ashby St, Partick, 4582177 Deputy M £18,000. 24/3/58 WL22065 B3
SG3 Ann Beech 81 George St, Glasgow, 67777 Snr Asst F £12,000. 10/11/6 WL44201 B3
SG5 Susan Brand 5 Gt Western Rd, 6772001 Manager F £24,000. 3/6/40 WK5889 B3
Glasgow
- 13 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
SL2 John White 19 Taylor St, Cranford, 01775112 Manager M £30,000. 1/10/45 WL43251 B5
SL4 Julie Lee 28 Mavlvern St, 788 Assistant F £9,000.0 13/6/65 WA2905 B5
- 14 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
WHERE position in ('Manager', 'Deputy');
Aggregation
ISO standard defines five aggregate functions. These are:
COUNT returns number of values in a specified column.
SUM returns sum of values in a specified column.
AVG returns average of values in a specified column.
MIN returns smallest value in a specified column.
MAX returns largest value in a specified column.
Each operates on a single column of a table and return single value. The functions COUNT, MIN, and
MAX apply to numeric and non-numeric fields, but SUM and AVG may be used on numeric fields only.
Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null
values. COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur.
One can use DISTINCT before column name to eliminate duplicates. DISTINCT has no effect with
MIN/MAX, but may have with SUM/AVG. Aggregate functions can be used only in SELECT list and in
HAVING clause. If SELECT list includes an aggregate function and there is no GROUP BY clause, then
SELECT list cannot reference a column without an aggregate function. For example, following is illegal:
SELECT sno, COUNT(salary) FROM staff;
All column names in the SELECT list must appear in the Group By clause unless the name is used only
in an aggregate function. We will illustrate the use of these functions through examples using the estate
agent database.
Grouping results
We use the GROUP BY clause to get sub-totals. The two clauses SELECT and GROUP BY are closely
integrated: each item in SELECT list must be single- valued per group, and SELECT clause may only
contain: column names, aggregate functions, constants or an expression involving combinations of the
above.
All column names in the SELECT list must appear in the GROUP BY clause unless the name is used
only in an aggregate function. If the WHERE clause is used with the GROUP BY, then the WHERE is
applied first, followed by the formation of the groups from remaining rows that satisfy the predicate.
SQL-92 considers two nulls to be equal for purposes of GROUP BY.
whereas HAVING filters groups. The column names in HAVING clause must also appear in the
GROUP BY list or be contained within an aggregate function.
PRACTICAL
Given the following database schema for a library
- 16 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
Implement using MYSQL . Write the SQL statements to create a database called zictcdb and all the
tables.
Insert data into the tables
CREATE DATABASE zictcdb;
USE zictcdb;
- 18 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
INSERT INTO BOOK_COPIES VALUES (3, 4, 11);
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to Jun 2017
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data manipulation
operation.
4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.
5. Create a view of all books and its number of copies that are currently available in the Library.
NOTE: Each student has to demonstrate to Mr. Sinyangwe . You can try as many queries as possible
The company is organized into departments. Each department has a unique name, a unique number, and a
particular employee who manages the department. We keep track of the start date when that employee
began managing the department. A department may have several locations.
A department controls a number of projects, each of which has a unique name, a unique number, and a
single location.
We store each employee‘s name, Social Security number, address, salary, sex (gender), and birth date. An
employee is assigned to one department, but may work on several projects, which are not necessarily
controlled by the same department. We keep track of the current number of hours per week that an
employee works on each project. We also keep track of the direct supervisor of each employee (who is
another employee).
We want to keep track of the dependents of each employee for insurance purposes. We keep each
dependent‘s first name, sex, birth date, and relationship to the employee.
(a) Draw the ERD
(b) Convert the ERD to relational schema
(c) Write the SQL statements to answer the questions that follows.
SOLUTION
- 19 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
(a) ERD
Query 0: Retrieve the birth date and address of the employee whose name is 'John B. Smith'.
- 20 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
SELECT BDATE, ADDRESS FROM EMPLOYEE
WHERE FNAME='John' AND MINIT='B‗ AND LNAME='Smith‗
Query 1: Retrieve the name and address of all employees who work for the 'Research' department.
SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE
DNAME='Research' AND DNUMBER=DNO
Query 2: For every project located in 'Stafford', list the project number, the controlling de partment
number, and the department manager's last name, address, and birth date.
SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROM PROJECT, DEPARTMENT,
EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford'
Query 3: For each employee, retrieve the employee's name, and the name of his or her immediate
supervisor.
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S WHERE
E.SUPERSSN=S.SSN
OR
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN
Retrieve all the attribute values of EMPLOYEES who work in department 5.
SELECT * FROM EMPLOYEE WHERE DNO=5
Retrieve all the attributes of an employee and attributes of DEPARTMENT he works in for every
employee of ‘Research’ department.
SELECT * FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNO=DNUMBER
Query 5: Make a list of all project numbers for projects that involve an employee whose last name is
'Smith' as a worker or as a manager of the department that controls the project.
(SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER
AND MGRSSN=SSN AND LNAME='Smith')
Query 6: Retrieve the name and address of all employees who work for the 'Research' department.
SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT WHERE DNAME='Research' )
Query 7: Retrieve the name of each employee who has a dependent with the same first name as the
employee.
SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM
DEPENDENT WHERE ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME)
Query 8: Retrieve the names of employees who have no dependents .
SELECT FNAME, LNAME FROM EMPLOYEE
WHERE NOT EXISTS
(SELECT * FROM DEPENDENT WHERE SSN=ESSN)
- 21 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
Query 9: Retrieve the social security numbers of all employees who work on project number 1, 2, or
3.
SELECT DISTINCT ESSN FROM WORKS_ON WHERE PNO IN (1, 2, 3)
Query 10: Retrieve the names of all employees who do not have supervisors.
SELECT FNAME, LNAME FROM EMPLOYEE
WHERE SUPERSSN IS NULL
Query 11: Find the maximum salary, the minimum salary, and the average salary among all
employees.
SELECT MAX (SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
Query 12: Find the maximum salary, the minimum salary, and the average salary among employees
who work for the 'Research' department.
SELECT MAX (SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research'
Queries 13 and 14: Retrieve the total number of employees in the company (Q13), and the number of
employees in the 'Research' department (Q14).
Q13: SELECT COUNT (*) FROM EMPLOYEE
Q14: SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research‗
Query 15: For each department, retrieve the department number, the number of employees in the
department, and their average salary.
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE GROUP BY DNO
Query 16: For each project, retrieve the project number, project name, and the number of
employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
Query 17: For each project on which more than two employees work, retrieve the project number,
project name, and the number of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
- 22 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2
Query 18: Retrieve all employees whose address is in Houston, Texas. Here, the value of the
ADDRESS attribute must contain the substring 'Houston,TX‘ in it.
SELECT FNAME, LNAME
FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%'
Query 19: Show the effect of giving all employees who work on the 'ProductX' project a 10% raise.
SELECT FNAME, LNAME, 1.1*SALARY
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN
AND PNO=PNUMBER AND PNAME='ProductX‗
Query 20: Retrieve a list of employees and the projects each works in, ordered by the employee's
department, and within each department ordered alphabetically by employee last name.
SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNO
AND SSN=ESSN
AND PNO=PNUMBER
ORDER BY DNAME, LNAME ASC
- 23 -