0% found this document useful (0 votes)
174 views23 pages

Structured Query Language Introduction To SQL

SQL (Structured Query Language) is a language used to manage data in relational databases. It was developed in the 1970s and became a standard through the SQL standards published between 1989-1999. SQL allows users to define schemas, manipulate data, and manage security. It is made up of four sublanguages: DDL for defining schemas, DML for manipulating data, DCL for security, and TCL for transactions. SQL statements use keywords and a simple syntax to retrieve, insert, update, and delete data from databases.

Uploaded by

Code Zero
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
174 views23 pages

Structured Query Language Introduction To SQL

SQL (Structured Query Language) is a language used to manage data in relational databases. It was developed in the 1970s and became a standard through the SQL standards published between 1989-1999. SQL allows users to define schemas, manipulate data, and manage security. It is made up of four sublanguages: DDL for defining schemas, DML for manipulating data, DCL for security, and TCL for transactions. SQL statements use keywords and a simple syntax to retrieve, insert, update, and delete data from databases.

Uploaded by

Code Zero
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

ZAMBIA ICT COLLEGE BIT 260 @DMS

STRUCTURED QUERY LANGUAGE


Introduction to SQL
SQL (Structured Query Language) is a database sublanguage for querying and modifying relational
databases. It is the main language for relational DBMSs. Structured Query Language, commonly
abbreviated to SQL and pronounced as ―sequel‖, is not a conventional computer programming language in
the normal sense of the phrase. It allows users to access data in relational database management systems.
SQL is a keyword based language. Each statement begins with a unique keyword. SQL statements consist
of clauses which begin with a keyword. SQL syntax is not case sensitive.

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

 It is the only standard database language to gain widespread acceptance.


 Huge investment from both vendors and users.
 Used as the basis for other standards.

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:

o CREATE - to create objects in the database


o ALTER - alters the structure of the database
o DROP - delete objects from the database
o TRUNCATE - remove all records from a table, including all spaces allocated for the records
are removed
o COMMENT - add comments to the data dictionary
o RENAME - rename an object

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:

o SELECT - retrieve data from the a database


o INSERT - insert data into a table
o UPDATE - updates existing data within a table
o DELETE - deletes all records from a table, the space for the records remain
o MERGE - UPSERT operation (insert or update)
o CALL - call a PL/SQL or Java subprogram
o EXPLAIN PLAN - explain access path to data
o LOCK TABLE - control concurrency

3. Data Control Language (DCL) tends to be something the database administrator would use to
handle security of the database. DCL statements. Some examples:

o GRANT - gives user's access privileges to database


-2-
ZAMBIA ICT COLLEGE BIT 260 @DMS
o REVOKE - withdraw access privileges given with the GRANT command

Eg GRANT privileges ON tbl_name TO user [IDENTIFIED BY ‘password’];

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 COMMIT - save work done


o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT

o SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use

Basic structure of SQL commands


SQL statement consists of reserved words and user-defined words. Reserved words are a fixed part of
SQL and must be spelt exactly as required and cannot be split across lines. User-defined words are made
up by user and represent names of various database objects such as relations, columns and views.

A) DDL: Data Definition Language


All DDL commands are auto-committed. That means it saves all the changes permanently in the database.
Create is a DDL command used to create a table or a database.
1) Creating a Database
To create a database in RDBMS, create command is uses. Following is the Syntax,
create database database-name;
________________________________________
Example for Creating Database
create database Test;
The above command will create a database named Test.
________________________________________
2) Creating a Table
Create command is also used to create a table. We can specify names and data types of various columns
along. Following is the Syntax,
create table table-name
(
column-name1 datatype1,
column-name2 datatype2,
column-name3 datatype3,
column-name4 datatype4
);
create table command will tell the database system to create a new table with given table name and column
information.
________________________________________
Example for creating Table
create table Student(id int(3), name varchar(15) not null, age int);
The above command will create a new table Student in database system with 3 columns, namely id, name
and age.
3) Alter command
Alter command is used for alteration of table structures. There are various uses of alter command, such as,
• to add a column to existing table
• to rename any existing column
-3-
ZAMBIA ICT COLLEGE BIT 260 @DMS
• to change datatype of any column or to modify its size.
• alter is also used to drop a column.
________________________________________
To Add Column to existing Table
Using alter command we can add a column to an existing table. Following is the Syntax,

alter table table-name add(column-name datatype);

Here is an Example for this,


alter table Student add(address varchar(50);
The above command will add a new column address to the Student table
________________________________________
To Add Multiple Column to existing Table
Using alter command we can even add multiple columns to an existing table. Following is the Syntax,
alter table table-name add(column-name1 datatype1, column-name2 datatype2, column-name3
datatype3);

Here is an Example for this,


alter table Student add(father-name varchar(60), mother -name varchar(60), dob date);
The above command will add three new columns to the Student table
________________________________________
To Add column with Default Value
alter command can add a new column to an existing table with default values. Following is the Syntax,
alter table table-name add(column-name1 datatype1 default data);

Here is an Example for this,


alter table Student add(dob date default '1 -Jan-99');
The above command will add a new column with default value to the Student table
________________________________________
To Modify an existing Column
alter command is used to modify data type of an existing column . Following is the Syntax,
alter table table-name modify(column-name datatype);

Here is an Example for this,


alter table Student modify(address varchar(30));
The above command will modify address column of the Student table
________________________________________
To Rename a column
Using alter command you can rename an existing column. Following is the Syntax,
alter table table-name rename old-column-name to column-name;

Here is an Example for this,


alter table Student rename address to Location;
The above command will rename address column to Location.
________________________________________
To Drop a Column
alter command is also used to drop columns also. Following is the Syntax,

alter table table-name drop(column-name);


Here is an Example for this,

alter table Student drop(address);


The above command will drop address column from the Student table

-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.

Following is its Syntax,


truncate table table-name

Here is an Example explaining it.


truncate table Student;
The above query will delete all the records of Student table.

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

Here is an Example explaining it.


drop table Student;
The above query will delete the Student table completely. It can also be used on Databases. For Example,
to drop a database,
drop database Test;
The above query will drop a database named Test from the system.
________________________________________
Rename query
Rename command is used to rename a table. Following is its Syntax,
rename table old-table-name to new-table-name

Here is an Example explaining it.


rename table Student to Student -record;
The above query will rename Student table to Student-record.

________________________________________
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

INSERT into Student values(101,'Adam',15);


The above command will insert a record into Student table.

S_id S_Name age


101 Adam 15

-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)

S_id S_Name age


101 Adam 15
102 Alex
103 chris 14
Suppose the age column of student table has default value of 14.
Also, if you run the below query, it will insert default value into the age column, whatever the default value
may be.
INSERT into Student values(103,'Chris')
________________________________________
2) UPDATE command
Update command is used to update a row of a table. Following is its general syntax,
UPDATE table-name set column-name = value where condition;
Lets see an example,
update Student set age=18 where s_id=102;

S_id S_Name age


101 Adam 15
102 Alex 18
103 chris 14
________________________________________
Example to Update multiple columns
UPDATE Student set s_name='Abhi',age=17 where s_id=103;
The above command will update two columns of a record.
S_id S_Name age
101 Adam 15
102 Alex 18
103 Abhi 17
________________________________________
3) Delete command
Delete command is used to delete data from a table. Delete command can also be used with condition to
delete a particular row. Following is its general syntax,
DELETE from table-name;
________________________________________
Example to Delete all Records from a Table
DELETE from Student;
The above command will delete all the records from Student table.
________________________________________
Example to Delete a particular Record from a Table

-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

________________________________________

C) DCL: Data Control Language


Data Control Language (DCL) is used to control privilege in Database. To perform any operation in the
database, such as for creating tables, sequences or views we need privileges. Privileges are of two types:
 System : creating session, table etc are all types of system privilege.
 Object : any command or query to work on tables comes under object privilege.
DCL defines two commands,
 Grant : Gives user access privileges to database.
 Revoke : Take back permissions from user.
________________________________________
To Allow a User to create Session
grant create session to username;
________________________________________
To Allow a User to create Table
grant create table to username;
________________________________________
To Grant permission to Create any Table
grant create any table to username
________________________________________
To Grant permission to Drop any Table
grant drop any table to username
________________________________________
To take back Permissions
revoke create table from username

Create a New User


Creating a new user within the MySQL shell:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

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.

Grant Different User Permissions


Here is a short list of other common possible permissions that users can enjoy.
 ALL PRIVILEGES- this would allow a MySQL user all access to a designated database (or if no
database is selected, across the system)
 CREATE- allows them to create new tables or databases
 DROP- allows them to them to delete tables or databases
 DELETE- allows them to delete rows from tables
 INSERT- allows them to insert rows into tables
 SELECT- allows them to use the Select command to read through databases
 UPDATE- allow them to update table rows
 GRANT OPTION- allows them to grant or remove other users' privileges

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‘;

To test out your new user, log out by typing


quit
and log back in with this command in terminal:
mysql -u [username]-p

D) TCL: Transaction Control Language


Transaction Control Language (TCL) commands are used to manage transactions in database. These are
used to manage the changes made by DML statements. It also allows statements to be grouped together into
logical transactions.
________________________________________
Commit command
Commit command is used to permanently save any transaaction into database.
Following is Commit command's syntax,
commit;
________________________________________
Rollback command
This command restores the database to last commited state. It is also use with savepoint command to jump
to a savepoint in a transaction.
Following is Rollback command's syntax,
rollback to savepoint-name;
________________________________________
-8-
ZAMBIA ICT COLLEGE BIT 260 @DMS
Savepoint command
savepoint command is used to temporarily save a transaction so that you can rollback to that point
whenever necessary.
Following is savepoint command's syntax,
savepoint savepoint-name;
________________________________________
Example of Savepoint and Rollback
Following is the class table,
ID NAME
1 abhi
2 adam
4 alex
Lets use some SQL queries on the above table and see the results.
INSERT into class values(5,'Rahul');
commit;
UPDATE class set name='abhijit' where id='5';
savepoint A;
INSERT into class values(6,'Chris');
savepoint B;
INSERT into class values(7,'Bravo');
savepoint C;

SELECT * from class;

The resultant table will look like,


ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris
7 bravo

Now rollback to savepoint B


rollback to B;
SELECT * from class;

The resultant table will look like


ID NAME
1 abhi
2 adam
4 alex
5 abhijit
6 chris

Now rollback to savepoint A


rollback to A;
SELECT * from class;

The result table will look like


ID NAME
1 abhi
2 adam
4 alex
-9-
ZAMBIA ICT COLLEGE BIT 260 @DMS
5 abhijit

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.

SELECT [DISTINCT | ALL]


{* | [column_expression [AS new_name]] [,...] } FROM
table_name [alias] [, ...]
[WHERE condition]
[GROUP BY column_list] [HAVING condition] [ORDER BY
column_list]

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:

SELECT specifies which columns are to appear in output. FROM


specifies table(s) to be used.
WHERE filters rows.
GROUP BY forms groups of rows with same column value. HAVING filters
groups subject to some condition. ORDER BY specifies the order of the
output.

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:

Q1: Specific Columns, Specific Rows.


Find the salaries of employees named Brown.
- 10 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
SELECT Salary as Remuneration
FROM Employee
WHERE Surname = ‘Brown‘; This results in:
Remuneration
45
80

Q2: All Columns, Specific Rows.


Find all the information relating to employees named Brown.
SELECT *
FROM Employee
WHERE Surname = ‘BROWN‘;
The ―*‖ is used as an abbreviation for 'all columns'. This results in:

FirstName Surname Dept Office Salary City


Mary Brown Administration 10 45 London
Charles Brown Planning 14 80 London
Q3: Attribute expressions (calculated field)
Find the monthly salary of the employees named White.
SELEC Salary / 12 as MonthlySalary
T
FROM Employee
WHERE Surname = ‘White‘;
This results in:
MonthlySalary
3.00

Q4: Simple join query


Find the names of the employees and the cities in which they work.
SELECT Employee.FirstName, Employee.Surname,
Department.City
FROM Employee, Department
WHERE Employee.Dept = Department.DeptName;
This results in:
FirstName Surname City
Mary Brown London
Charles White Toulouse
Gus Green London
Jackson Neri Brighton
Charles Brown London
Laurence Chen London
Pauline Bradshaw London
Alice Jackson Toulouse

Q5: Using table aliases


Find the names of the employees and the cities in which they work (using an alias).
– SELECT E.FirstName, E.Surname, D.City
FROM Employee E, Department D
WHERE E.Dept = D.DeptName;
This results in:
FirstName Surname City
Mary Brown London
- 11 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
Charles White Toulouse
Gus Green London
Jackson Neri Brighton
Charles Brown London
Laurence Chen London
Pauline Bradshaw London
Alice Jackson Toulouse

Q6: Using predicate conjunction


Find the first names and surnames of the employees who work in office number
20 of the Administration department.
SELECT FirstName, Surname
FROM Employee
WHERE Office = ‘20‘ AND Dept = ‘Administration‘;
This results in:

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

Q8: Using complex logical expression


Find the first names of the employees named Brown who work in the
Administration department or the Production department.
SELECT FirstName
FROM Employee
WHERE Surname = ‘Brown‘ AND (Dept =
‘Administration‘ OR Dept = ‘Production‘);
This results in:
FirstName
Mary

Q9: Using the operator like


Find the employees with surnames that have ‘r‘ as the second letter and end in
‘n‘.
SELECT *
FROM Employee

- 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

Q10: Null search condition


List the details of all viewings on property PG4 where a comment has not been supplied.
SELECT viewing.pno, viewing.rno, Date
FROM viewing
WHERE pno='PG4' AND comment IS NULL; This results in:
pno rno Date
PG4 CR5 26-May-

Q11: Sorting results


Produce an abbreviated list of properties arranged in order of property type.
SELECT Pno, Type, Rooms, Rent
FROM Property
ORDER BY Type; This results in:
Pno type rooms rent
PL94 F 4 £400.00
PG4 F 3 £350.00
PG36 F 3 £375.00
PG16 F 4 £450.00
PG21 H 5 £600.00
PA14 H 6 £650.00

Q12: Comparison search condition


List all staff with a salary greater than 10,000.
SELECT Staff.Sno, Staff.Fname, Staff.Lname, Position, Salary
FROM Staff
WHERE Salary > 10000;

This results in:


Sno First Last positio salary
SG14 David Ford Deputy £18,00
SG37 Ann Beech Snr £12,00
SG5 Susan Brand Manage £24,00
SL21 John White Manage £30,00

Q13: Range search condition


List all staff with a salary between 20,000 and 30,000.
SELECT staff.Sno, staff.FName, staff.LName, staff.Position, staff.Salary
FROM staff
WHERE staff.Salary BETWEEN 20000 AND 30000;

This results in:


Sno First Last Positio Salary
SG5 Susan Brand Manage £24,00
SL21 John White Manage £30,00
Q14: Set membership search condition
List all Managers and Deputy Managers.
SELECT staff.Sno, staff.FName, staff.LName, staff.Position
FROM staff

- 14 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
WHERE position in ('Manager', 'Deputy');

This results in:


Sno First Last Positio
SG14 David Ford Deputy
SG5 Susan Brand Manage
SL21 John White Manage

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.

Q16: The Count function


How many properties cost more than £350 per month for rent?
SELECT Count(*) AS count
FROM property
WHERE property.Rent > 350;
This results in:
count
5
Q17: The Count function with distinct
How many different properties were viewed in May 1995?
SELECT COUNT (DISTINCT Pno) AS COUNT
FROM viewing
WHERE Date BETWEEN ‘05/1/95‘ AND ‘05/31/95‘;
This results in:
count
2

Q18: The Max, Min and Avg function


Find the minimum, maximum and average staff salary.
SELECT MIN(salary) AS MIN, MAX(salary)
AS MAX, AVG(salary) AS AVG
FROM staff;
- 15 -
ZAMBIA ICT COLLEGE BIT 260 @DMS

This results in:


min max avg
$9,000.00 $30,000.00 $17,000.00

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.

Q19: Using the Group By clause


Find the number of staff working in each branch and the total of their salaries.
SELECT bno, COUNT(sno) AS count, SUM(salary) AS sum
FROM staff GROUP BY
bno ORDER BY bno;
This results in:
bno count sum
B3 3 $54,000.00
B5 2 $39,000.00
B7 1 $9,000.00

Restricted Grouping (Having clause)


The HAVING clause is designed for use with GROUP BY clause to restrict groups that appear in
final result table. It is similar to WHERE, but WHERE filters individual rows

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.

Q20: Using predicates on grouping results


For each branch office with more than one member of staff, find the number of staff working in
each branch and the sum of their salaries.
SELECT bno, COUNT(sno) AS count, SUM(salary) AS sum
FROM staff
GROUP BY bno
HAVING COUNT(SNO) > 1;
This results in:
bno count sum
B3 3 $54,000.00
B5 2 $39,000.00

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;

CREATE TABLE PUBLISHER


(NAME VARCHAR(20) PRIMARY KEY,
PHONE VARCHAR(20),
ADDRESS VARCHAR(20));

CREATE TABLE BOOK


(BOOK_ID INTEGER PRIMARY KEY,
TITLE VARCHAR(20),PUBLISHER_NAME VARCHAR(20),
PUB_YEAR VARCHAR(20),
FOREIGN KEY (PUBLISHER_NAME) REFERENCES PUBLISHER(NAME) ON DELETE CASCADE);

CREATE TABLE BOOK_AUTHORS


(AUTHOR_NAME VARCHAR(20),BOOK_ID INTEGER,
- 17 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
FOREIGN KEY (BOOK_ID) REFERENCES BOOK(BOOK_ID) ON DELETE CASCADE,
PRIMARY KEY (BOOK_ID, AUTHOR_NAME));

CREATE TABLE LIBRARY_BRANCH


(BRANCH_ID INTEGER PRIMARY KEY,
BRANCH_NAME VARCHAR(50),
ADDRESS VARCHAR(50));

CREATE TABLE BOOK_COPIES


(NO_OF_COPIES INTEGER, BOOK_ID INTEGER,BRANCH_ID INTEGER,
FOREIGN KEY (BOOK_ID) REFERENCES BOOK(BOOK_ID) ON DELETE CASCADE,
FOREIGN KEY (BRANCH_ID) REFERENCES LIBRARY_BRANCH(BRANCH_ID) ON DELETE
CASCADE, PRIMARY KEY(BOOK_ID, BRANCH_ID));

CREATE TABLE CARD


(CARD_NO INTEGER PRIMARY KEY);

CREATE TABLE BOOK_LENDING


(DATE_OUT DATE,DUE_DATE DATE,BOOK_ID INTEGER,BRANCH_ID INTEGER,CARD_NO
INTEGER, FOREIGN KEY (BOOK_ID) REFERENCES BOOK(BOOK_ID) ON DELETE CASCADE,
FOREIGN KEY (BRANCH_ID) REFERENCES LIBRARY_BRANCH(BRANCH_ID) ON DELETE
CASCADE, FOREIGN KEY(CARD_NO) REFERENCES CARD(CARD_NO) ON DELETE CASCADE,
PRIMARY KEY(BOOK_ID, BRANCH_ID, CARD_NO));

INSERT INTO PUBLISHER VALUES ('MCGRAW-HILL', '9989076587', 'BANGALORE');


INSERT INTO PUBLISHER VALUES ('PEARSON', '9889076565', 'NEWDELHI');
INSERT INTO PUBLISHER VALUES ('RANDOM HOUSE', '7455679345', 'HYDRABAD');
INSERT INTO PUBLISHER VALUES ('HACHETTE LIVRE', '8970862340', 'CHENAI');
INSERT INTO PUBLISHER VALUES ('GRUPO PLANETA', '7756120238', 'BANGALORE');

INSERT INTO BOOK VALUES (1,'DBMS','JAN-2017', 'MCGRAW-HILL');


INSERT INTO BOOK VALUES (2,'ADBMS','JUN-2016','MCGRAW-HILL');
INSERT INTO BOOK VALUES (3,'CN','SEP-2016', 'PEARSON');
INSERT INTO BOOK VALUES (4,'CG','SEP-2015', 'GRUPO PLANETA');
INSERT INTO BOOK VALUES (5,'OS','MAY-2016', 'PEARSON');

INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 1);


INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 2);
INSERT INTO BOOK_AUTHORS VALUES ('TANENBAUM', 3);
INSERT INTO BOOK_AUTHORS VALUES ('EDWARD ANGEL', 4);
INSERT INTO BOOK_AUTHORS VALUES ('GALVIN', 5);

INSERT INTO LIBRARY_BRANCH VALUES (10,'RR NAGAR','BANGALORE');


INSERT INTO LIBRARY_BRANCH VALUES (11,'RNSIT','BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (12,'RAJAJI NAGAR', 'BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (13,'NITTE','MANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (14,'MANIPAL','UDUPI');

INSERT INTO BOOK_COPIES VALUES (10, 1, 10);


INSERT INTO BOOK_COPIES VALUES (5, 1, 11);
INSERT INTO BOOK_COPIES VALUES (2, 2, 12);
INSERT INTO BOOK_COPIES VALUES (5, 2, 13);
INSERT INTO BOOK_COPIES VALUES (7, 3, 14);
INSERT INTO BOOK_COPIES VALUES (1, 5, 10);

- 18 -
ZAMBIA ICT COLLEGE BIT 260 @DMS
INSERT INTO BOOK_COPIES VALUES (3, 4, 11);

INSERT INTO CARD VALUES (100);


INSERT INTO CARD VALUES (101);
INSERT INTO CARD VALUES (102);
INSERT INTO CARD VALUES (103);
INSERT INTO CARD VALUES (104);

INSERT INTO BOOK_LENDING VALUES ('01/01/17','01/06/17', 1, 10, 101);


INSERT INTO BOOK_LENDING VALUES ('11/01/17','11/03/17', 3, 14, 101);
INSERT INTO BOOK_LENDING VALUES ('21/02/17','21/04/17', 2, 13, 101);
INSERT INTO BOOK_LENDING VALUES ('15/03/17','15/07/17', 4, 11, 101);
INSERT INTO BOOK_LENDING VALUES ('12/04/17','12/05/17', 1, 11, 104);

Write SQL queries to


1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in each
branch, etc.

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

EXAMPLE 2: THE COMPANY DB

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

(b) ERD to relational schema

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 -

You might also like