You are on page 1of 25

Use Basic Structured Query

Language
Level III

Prepared by Moges Tesfaye(MSc in ICT)


Learning Outcomes and Assessment Criteria
Unit of Competence : Use Basic Structured Query Language
Module Title EIS DBA3 M09 0517 Using Basic Structured Query Language
LO 1 Write an SQL statement to retrieve and sort data
Assessment Criteria  All the data from a table is retrieved following work
procedure.
 Data from specific columns in a single table is
retrieved.
 'Order by' is used to sort query output.
 Number of rows restricted is retrieved by placing
criteria in the 'where' clause.
 Number of rows restricted is retrieved by placing
specific criteria in the select statement.
 Comparison operators in the 'where' clause is used
to compare numeric, character, string, date and time
data
 Boolean operators is used with the correct
precedence
 Criteria in the 'where' clause is used to check for a
range of values, to select values from a list, and to
check for values that match a pattern
 SQL syntax is used to suppress duplicate values
from query results
 Action is taken to exclude null values from a query
result

LO 2 Write SQL statements that use functions
Assessment Criteria Arithmetical operators is used with the correct
precedence
String functions and operators is used to obtain the
required query output
Mathematical functions is used to obtain the required
output, where required
Date functions are used to obtain the required output
SQL aggregate functions are used to obtain the required
output

LO 3 Write SQL statements that use aggregation and filtering
Assessment Criteria  'Group by' used to aggregate data by multiple
columns
 Aggregated data is sorted in the query output
 Aggregated data is filtered using the 'having' clause
LO4 Write and execute SQL sub-queries
Assessment Criteria  Single and nested sub-queries are constructed
 Sub-queries are constructed that return a single row,
and multiple rows
 Correlated sub-queries are used to retrieve required
data
 Sub-queries are written that use aggregates

Training Mechanics

The Outcome-Based Training is one form of an independent learning approach. This


approach enables trainees to be master of their own environment and in charge of their
learning. It is also characterized by the integration of theory and application as two
dimensions of an effective learning process. The outcome-based system is consists of a
combination of lecture-discussion, individualized learning activities, mentoring, field
immersion and feedback.

In this competence the trainees will be given individual learning guide to go through and
accomplish. They will be instructed through this learning guide to accomplish learning activities as
part of the mechanism to transfer learning from the training situation to the job situation. For this
competence area, trainees will formulate a specific learning plan as a guide for applying their
learning to work setting and for their own continuing self-development. At this point, your role as
a trainer/facilitator is to guide the trainee in preparing and accomplishing their plan.

Lecture and discussion of the topics outlined in the session plan should be performed first before
the trainees are instructed to go to the workshop. You are also required to demonstrate the correct
steps/procedures and techniques to your trainees before you let them practice. Insure that they are
practicing safely.

Most part of the training activities will be conducted in the workshop for better development of
specific skills. Aside from motivating them to relate concepts and skills to their own work
situations, make sure to provide the necessary opportunity for competence practice and better
internalization of such concepts and techniques. The trainees should also be provided the
opportunity to blend with the actual working unit in the industry.

In this system, it is important to develop a sustained relationship with the trainees through a
continued involvement, where you are to offer support, guidance and assistance as the trainee go
through the learning activities and actual work.
With the mentoring approach, the trainees are grouped in learning teams with one facilitator-mentor
per team. Before learning session or workshop start in the morning, each team and mentor meets to
give feedback regarding their work, or how the group improves, acquire set of skills for the
members to become more effective trainees. You are also to asses them at the end of each module.
However, they have to be ready before the assessment and it should be them to request for it.

Before the training start you should conduct an orientation session to brief the trainees on how the
training will proceed.

Session Plan1 (EIS DBA3 04 0811s )

Unit of Competency : Use Basic Structured Query Language

Module Title : Using Basic Structured Query Language


LO 1 : Write an SQL statement to retrieve and sort data
Session Objectives: At the end of this session the learners shall be able to –

 Retrieve all the data from a table.


 Retrievie data from specific columns in a single table.
 Use 'Order by' to sort query output.
 Retrieve restricted number of rows using 'where' clause
 Retrieve restricted number of rows using select
statement
Nominal
Activities 20 hour Methods
Duration

10 mins Recapitulation Question & Answer

Retrieving all the data from a Lecture-discussion and


3 hr
table. demonstration

Retrieving data from specific Lecture-discussion and


2:20hr
columns in a single table. demonstration

Using 'Order by' to sort query Lecture-discussion and


2hr
output. demonstration

Retrieving restricted number of Lecture-discussion and


2 hr
rows using 'where' clause demonstration

Retrieving restricted number of Lecture-discussion and


2hr
rows using select statement demonstration
Using comparison operators in
the where clause to compare Lecture-discussion and
2hr
numeric, character, string, date demonstration
and time data
Using Boolean operators with the Lecture-discussion and
2hr
correct precedence demonstration

Using SQL syntax to suppress


duplicate values from query Lecture-discussion and
2hr
results demonstration

Evaluation 2hr Accomplishment of Lap Test Individual Activity


Discussion of Lap Test
Summary 20 mins Wrap-up and Feedback
Answers
Resources  Job specifications
 Safety manual and guide
 Reference Books
 Journals/publications/magazines
SET BY: Moges Tesfaye--------------------------
Signature ------------- Approved by-------------------------------

Signature ------------------------
Operation sheet

Operation title: reterive the information from the table


Module code: EIS DBA3 M09 0517
Purpose: -to queryinformaation based on criteria
Condition or situations for the operations:
- Install sl server 2008 R2

Equipment tool& materials


 a computer

Procedure

Step 1 create database;CREATE DATABASE databasename

Step 2: create table by using create table sttatment

Step 3: insert data by using insert into statment


Step 4:retertrive information by using select statment

Quality Criteria:
- Follow procedures in step by step
- The project must be functional
- Finishing on time

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
Lap Test
Lap test Demonsitration

Name:____________________
Date:_________________
Instruction: Answer all the questions listed below, if you have some
clarifications- feel free to ask your teacher.

Q1create the following database below


Q2 create the follwoning table below
Q3 insert the data by your own
Q4. Retrive information
The University Database
The university database stores details about university students, courses, the semester a student took a
particular course (and his mark and grade if he completed it), and what degree program each student is
enrolled in. The database is a long way from one that’d be suitable for a large tertiary institution, but it does
illustrate relationships that are interesting to query, and it’s easy to relate to when you’re learning SQL. We
explain the requirements next and discuss their shortcomings at the end of this section.
Consider the following requirements list:
The university offers one or more programs.
A program is made up of one or more courses.
A student must enroll in a program.
A student takes the courses that are part of her program.
A program has a name, a program identifier, the total credit points required to graduate, and the year it
commenced.
A course has a name, a course identifier, a credit point value, and the year it commenced.
Students have one or more given names, a surname, a student identifier, a date of birth, and the year they
first enrolled. We can treat all given names as a single object—for example, “John Paul.”
When a student takes a course, the year and semester he attempted it are recorded. When he finishes the
course, a grade (such as A or B) and a mark (such as 60 percent) are recorded.
Each course in a program is sequenced into a year (for example, year 1) and a semester (for example,
semester 1).

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
DATABASE ADMINISTRATION SERVICES
Level III
Unit of Competence : Use Basic Structured Query Language
Module Title Using Basic Structured Query Language
LO1: Write an SQL statement to retrieve and sort data
LO1. Write an SQL Statement to retrieve and sort data
1.1 Introduction to SQL
A.1.1 What is SQL?
SQL (Structured Query Language) is a programming language designed for managing data in
relational database management systems (RDBMS).
. It is a standard (main query) language for relational DBMSs, like Microsoft Access,
Microsoft SQL Server, and Oracle, that used to communicate with a database.
SQL is used to perform basic data management tasks, such as the insertion, modification, and
deletion of data from the tables using the standard SQL commands such as "Select", "Insert",
"Update", "Delete", "Create", and "Drop".
A.1.2 Categories of SQL Application
Microsoft SQL Server is a powerful and reliable data management system that delivers a rich set of
features, data protection, and light Web applications.
. Some common relational database management systems that use SQL are: Oracle, Sybase,
Microsoft SQL Server, MS- Access, etc.
. SQL Application is a database language that allow a user to:
- Define (create) the database, table structures, and controlling access to the data
using DDL.
- Perform both simple and complex queries using DML.
1.2 Installing DBMS software
1.2.1 Introduction
A database management system is the software that enables users to define, create, and maintain
the database and also provides controlled access to this database.
- Some of the most common database applications are:
- Microsoft Access
- Microsoft SQL
- Oracle, and Informix
1.2.2 Hardware Requirements
A processor with high speed of data processing and memory of large size (RAM and Hard disk
space) is required to run the DBMS software.
Example: The Minimum hardware requirements for SQL Server 2008 installations include:
. Processor
- Pentium 600 MHz or higher is required
- 1 GHz or higher is recommended.
. Memory
- 512 MB is required
- 1 GB or more is recommended
- Express Edition requires 192 MB and recommended 512 MB or more.
. Disk space
- Database components: 280 MB
- Analysis services: 90 MB
- Reporting services: 120 MB
- Integration services: 120 MB
- Client components: 850 MB
Session Plan2(EIS DBA3 04 0811s )

Unit of Competency : Use Basic Structured Query Language

Module Title : Using Basic Structured Query Language


LO 2 Write SQL statements that use functions
Session Objectives: At the end of this session the learners shall be able to –
 correct precedence by using Arithmetical operators.
 obtain the required query output by using String functions,
Mathematical functions, Date functions, aggregate functions
and operators.
Nominal
Activities 10 hour Methods
Duration

10 mins Recapitulation Question & Answer

Using arithmetical operators with Lecture-discussion and


1 hr
the correct precedence demonstration

Using string functions and Lecture-discussion and


1hr
operators demonstration
Lecture-discussion and
2hr Using mathematical functions demonstration
Lecture-discussion and
1:30hr Using date functions demonstration
Lecture-discussion and
2hr Using SQL aggregate functions demonstration

Evaluation 2hr Accomplishment of Lap Test Individual Activity


Discussion of Lap Test
Summary 20 mins Wrap-up and Feedback
Answers
Resources  Job specifications
 Safety manual and guide
 Reference Books
 Journals/publications/magazines
SET BY: Moges Tesfaye--------------------------
Signature ------------- Approved by-------------------------------

Signature ------------------------
Operation sheet

Operation title: using aggregate function perform computation


Module code: EIS DBA3 M09 0517
Purpose: -to t performs a computation on a set of values rather than on a single value
Condition or situations for the operations:
Sql server 2008 r2 installatio
Equipment tool& materials
 a computer

Procedure

Step 1 create the database

Step 2: create the table


Step 3insert the data
Step 4: use AVG, COUNT, MAX, MIN, SUM, STDEV, STDEVP,  VAR, and VARP

Quality Criteria:
- Follow procedures in step by step
- The project must be functional
- Finishing on time

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
Lap Test

Lap test Demonstration

Name:____________________
Date:_________________
Instruction: Answer all the questions listed below, if you have some
clarifications- feel free to ask your teacher.
Q1 creating employe table by your own perform aggregate function

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
DATABASE ADMINISTRATION SERVICES
Level III
Unit of Competence : Use Basic Structured Query Language
Module Title Using Basic Structured Query Language
LO2: Write SQL statements that use functions
LO2. Write SQL statements that use functions
2.1 Introduction
In SQL Server, you can design your own functions to supplement and extend the system supplied
(built-in) functions. A user-defined function takes zero, or more, input parameters and returns either
a scalar value or a table.
Input parameters can be any data type except timestamp, cursor, or table.
2.2 Select clause and Aggregation function
Introduction
The SQL SELECT statement queries data from tables in the database.
The statement begins with the SELECT keyword. The basic SELECT statement has 3 clauses:
 SELECT
 FROM
 WHERE
- The SELECT clause specifies the table columns that are retrieved.
- The FROM clause specifies the tables accessed.
- The WHERE clause specifies which table rows are used. The WHERE clause is optional; if
missing, all table rows are used.
An aggregation function is a function that performs a computation on a set of values rather than
on a single value. Example: finding the average or mean of a list of numbers is an aggregate
function.
The aggregation functions are AVG, COUNT, MAX, MIN, SUM, STDEV, STDEVP,  VAR,
and VARP
The syntax of an aggregation function is illustrated as:
Aggregation-function ([ALL | DISTINCT] expression)
Example: SELECT SUM (Employee.salary) as Total_Salary FROM Employee WHERE
Employee.Dnum =20
SELECT min(EMPLOYEE .salary )'min salary',MAX (EMPLOYEE .salary )'max salary'
FROM EMPLOYEE

This aggregation computes the total salary for department 20.


Aggregate functions are functions that are used to get summary values.
Session Plan3(EIS DBA3 04 0811s )

Unit of Competency : Use Basic Structured Query Language

Module Title : Using Basic Structured Query Language


LO 3 Write SQL statements that use aggregation and filtering
Session Objectives: At the end of this session the learners shall be able to –
 Aggregate data by multiple columns using "Group by "
 sorte Aggregated data in the query output
 filter Aggregated data by using the 'having' clause
.
Nominal
Activities 10 hour Methods
Duration

10 mins Recapitulation Question & Answer

Using 'Group by' to aggregate Lecture-discussion and


3 hr
data by multiple columns demonstration
Lecture-discussion and
!:30hr Sorting aggregated data demonstration

Filtering aggregated data using Lecture-discussion and


3hr
the 'having' clause demonstration

Evaluation 2hr Accomplishment of Lap Test Individual Activity


Discussion of Lap Test
Summary 20 mins Wrap-up and Feedback
Answers
Resources  Job specifications
 Safety manual and guide
 Reference Books
 Journals/publications/magazines
SET BY: Moges Tesfaye--------------------------
Signature ------------- Approved by-------------------------------

Signature ------------------------
Operation sheet

Operation title: Filtering aggregated data using the “having” clause

Module code: EIS DBA3 M09 0517


Purpose: -to fileter the data
Condition or situations for the operations:
Sql server 2008 r2 installatio
Equipment tool& materials
 a computer

Procedure

Step 1 create the database

Step 2: create the table


Step 3insert the data
Step 4: use AVG, COUNT, MAX, MIN, SUM, STDEV, STDEVP,  VAR, and VARP
Step 5: use HAVE clause

Quality Criteria:
- Follow procedures in step by step
- The project must be functional
- Finishing on time

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
Lap Test

Lap test Demonstration

Name:____________________
Date:_________________
Instruction: Answer all the questions listed below, if you have some
clarifications- feel free to ask your teacher.
Q1 creating employe table by your own perform aggregate function
Q2 filetet the data by HAVING cluse

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
DATABASE ADMINISTRATION SERVICES
Level III
Unit of Competence : Use Basic Structured Query Language
Module Title Using Basic Structured Query Language
LO3: Write SQL statements that use aggregation and filtering
LO3. Write SQL statements that use aggregation and filtering
3.1 Aggregating data by multiple columns using “group by”
When an aggregate function is executed, SQL Server summarizes values for an entire table or for
groups of columns within the table, producing a single value for each set of rows for the specified
columns.
- You can use aggregate functions with the SELECT statement or in combination with the
GROUP BY clause
- Use the GROUP BY clause on columns or expression to organize rows into groups and to
summarize those groups. The GROUP BY clause groups rows on the basis of similarities
between them.
When you use the GROUP BY clause, consider the following facts and guidelines:
. SQL Server returns only single rows for each group that you specify; it does not return
detail information.
. All columns that are specified in the GROUP BY clause must be included in the select list.
. If you include a WHERE clause, SQL Server groups only the rows that satisfy the search
conditions.
. Do not use the GROUP BY clause on columns that contain multiple null values.
Example: For each department, retrieve the department name, the number of employees in the
department, and their average salary.
SELECT DEPARTEMENT.Dname , COUNT (*)'number of employee', AVG (EMPLOYEE.salary)'average
salary' FROM EMPLOYEE,DEPARTEMENT
where EMPLOYEE.dnum =DEPARTEMENT.Dnumber
GROUP BY DEPARTEMENT.Dname
3.2 Sorting aggregated data in the query output:
SQL allows the user to sort rows in the result set in ascending (ASC) or descending (DESC) order
using
ORDER BY clause. Sort is in ascending order by default
- You can sort by column names, computed values, or expressions
Example: Retrieve a list of employees and ordered them alphabetically by their department name, last
name, first name.
SELECT EMPLOYEE.ID, EMPLOYEE.Fname, EMPLOYEE.Lname, EMPLOYEE.salary,
DEPARTEMENT.Dname
FROM DEPARTEMENT,EMPLOYEE
WHERE EMPLOYEE.dnum=DEPARTEMENT .Dnumber
Session Plan4(EIS DBA3 04 0811s )

Unit of Competency : Use Basic Structured Query Language

Module Title : Using Basic Structured Query Language


LO 4 . Write and execute SQL sub-queries
Session Objectives: At the end of this session the learners shall be able to –
 construct Single and nested sub-queries .
 construct Sub-queries that return a single row, and multiple
rows.
 retrieve required data by using Correlated sub-queries..

Nominal
Activities 10 hour Methods
Duration

10 mins Recapitulation Question & Answer

Constructing single and nested Lecture-discussion and


2 hr
sub-queries demonstration

Constructing sub-queries that Lecture-discussion and


2hr return a single row, and multiple demonstration
rows

Lecture-discussion and
2hr Using correlated sub-queries demonstration

1:30hr Writing sub-queries that use


aggregates
Evaluation 2hr Accomplishment of Lap Test Individual Activity
Discussion of Lap Test
Summary 20 mins Wrap-up and Feedback
Answers
Resources  Job specifications
 Safety manual and guide
 Reference Books
 Journals/publications/magazines
SET BY: Moges Tesfaye--------------------------
Signature ------------- Approved by-------------------------------

Signature ------------------------
Operation sheet

Operation title: retrive information using nested query

Module code: EIS DBA3 M09 0517


Purpose: -to query information
Condition or situations for the operations:
Sql server 2008 r2 installatio
Equipment tool& materials
 a computer

Procedure

Step 1 create the database

Step 2: create the table


Step 3insert the data
Step 4: use nested query

Quality Criteria:
- Follow procedures in step by step
- The project must be functional
- Finishing on time

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
Lap Test

Lap test Demonstration

Name:____________________
Date:_________________
Instruction: Answer all the questions listed below, if you have some
clarifications- feel free to ask your teacher.
Q1 creating employe and project table by your own perform aggregate
function
Q2 filetet the data by HAVING cluse
Q3 query using nested query

SET BY: Moges Tesfaye--------------------------


Signature ------------- Approved by-------------------------------

Signature ------------------------
DATABASE ADMINISTRATION SERVICES
Level III
Unit of Competence : Use Basic Structured Query Language
Module Title Using Basic Structured Query Language
LO4: Write and execute SQL sub-queries
LO4: Write and execute SQL Queries
4.1 Single and nested queries
What is query?
A query is a request for information from a database (Queries are Questions).
Single query is a Single Block query.
Example: SELECT distinct salary FROM Employee where Gender ='female'
A SQL nested query is a SELECT query that is nested inside a SELECT, UPDATE, INSERT, or
DELETE SQL query.
Nested Queries are queries that contain another complete SELECT statements nested within it, that
is, in the WHERE clause.
- The nested SELECT statement is called an “inner query” or an “inner SELECT.”
- The main query is called “outer SELECT” or “outer query.”
- The use of nested query in this case is to avoid explicit coding of JOIN which is a very
expensive database operation and to improve query performance.
Example: SELECT ID,LNAME, FNAME FROM EMPLOYEE
WHERE (SELECT COUNT (*) FROM DEPENDENTED WHERE DEPENDENTED.EmpID
=EMPLOYEE.ID) >= 2
4.2 Subqueries
A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement,
or inside another subquery.
- Subquery is an inner query or inner select, while the statement containing a subquery is also
called an outer query or outer select.
- You use subqueries to break down a complex query into a series of logical steps and, as a
result, to solve a problem with single statements.
- Each select statement in the subquery has its own:
. select list
. where clause
Example: For each department that has more than five employees, retrieve the department number
and the number of its employees who are
making more than $40,000.
SELECT DNUMBER, COUNT (*) FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SALARY>40000 AND
DNO IN (SELECT DNO FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT (*) > 5)
GROUP BY DNUMBER;

You might also like