0% found this document useful (0 votes)
75 views

Lab 8 Data Manipulation Language (Select Where, Order, Distinct, Limit)

This document provides an overview of the SELECT statement in SQL for manipulating data in a database. It discusses selecting data using criteria like WHERE clauses, comparison operators, pattern matching with LIKE/NOT LIKE, logical operators, and sorting/limiting results. The lab aims to teach students how to query a database using the SELECT statement and its various clauses to filter and organize result sets. Key concepts covered include selecting columns, filtering rows, joining tables, comparison operators, pattern matching, logical operators, and sorting/limiting results.

Uploaded by

Daniyal Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Lab 8 Data Manipulation Language (Select Where, Order, Distinct, Limit)

This document provides an overview of the SELECT statement in SQL for manipulating data in a database. It discusses selecting data using criteria like WHERE clauses, comparison operators, pattern matching with LIKE/NOT LIKE, logical operators, and sorting/limiting results. The lab aims to teach students how to query a database using the SELECT statement and its various clauses to filter and organize result sets. Key concepts covered include selecting columns, filtering rows, joining tables, comparison operators, pattern matching, logical operators, and sorting/limiting results.

Uploaded by

Daniyal Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Lab Manual for Introduction to Database Systems

Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)


Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

Contents

1. Introduction 3

2. Activity Time boxing 3

3. Objective of the experiment 3

4. Concept Map 3
4.1. Reading the data from database using SELECT statement. 4
4.2. Specifying some criteria with WHERE clause 4
4.3. Comparison Operators 4
4.4. String Pattern Matching - LIKE and NOT LIKE 5
4.5. IS NULL, IS NOT NULL 6
4.6. Logical Operators - AND, OR: 6
4.7. BETWEEN, NOT BETWEEN 6
5.1 SELECT Advanced 7
5.2 Sorting the ResultSet with ORDER BY Clause 7
5.3 Limiting the Result Set using LIMIT Clause 7
5.4 Listing distinct elements of a column using DISTINCT keyword 8

5. Homework before Lab 8


5.1. Task 1 8

6. Procedure & Tools 8


6.1. Starting MySQL CLI [Expected time =5mins] 8
6.2. Walkthrough Tasks [Expected time =60mins] 8
5.1.1. Sorting ResultSet 11
5.1.2. Showing limited Rows From a ResultSet 12
5.1.3. Selecting Distinct values of a column 12

7. Practice Tasks 13
7.1. Practice Task 1 [Expected time = 50mins] 13
7.2. Outcomes 15

8. Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 15

9. Evaluation criteria 15

10. Further Reading 15


10.1. Books 15
10.2. Slides 15

11. REFERENCES: 16

Department of Computer Science, Page 1


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

11.1. SQL-99 Complete, Really, by Peter Gulutzan & Trudy Pelzer. 16

Department of Computer Science, Page 2


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

Lab 8: Data Manipulation Language (SELECT WHERE,


ORDER, DISTINCT, LIMIT)
1. Introduction
You will learnthe select command of Data Manipulation Language (DML)with different built in
function in this lab. The SELECT statement is used to select data from a database.The data
returned is stored in a result table, called the result-set.
A SELECT statement retrieves information from the database. Using a SELECT statement, you
can do the following:
• Projection: You can use the projection capability in SQL to choose the columns in a
table that you want returned by your query. You can choose as few or as many columns
of the table as you require.
• Selection: You can use the selection capability in SQL to choose the rows in a table that
you want returned by a query. You can use various criteria to restrict the rows that you
see.
• Joining: You can use the join capability in SQL to bring together data that is stored in
different tables by creating a link between them. You learn more about joins in a later
lesson.
Relevant Lecture Material:
a) Text Book: Database Systems, A practical approach to design, implementation
and management by Thomas Connolly, Carolyn Begg, Addison Wesley , Fifth
Edition,
1. Read URL:

• https://www.w3schools.com/sql/sql_select.asp

2. Activity Time boxing


Task Activity Name Activity time Total Time
No.
6.2 Setup MySQL CLI 20mins 20mins
6.3 Walkthrough Tasks 60mins 60mins
7 Practice tasks 5 mins for each task 50mins
8 Evaluation Task 60mins for all assigned 40mins
task
Table 1:Activity Time Boxing

3. Objective of the experiment


• Tolearn how to query from a database using SELECT statement.

4. Concept Map
In this section, a brief overview of the concepts is presented, those will be used in this lab
Department of Computer Science, Page 3
C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

afterwards.

4.1.Reading the data from database using SELECTstatement.


The most common, and important task is to query a database for a subset of data that meets your
needs with the SELECT statement. The output of the select statement is a two-dimensional table,
known as the ResultSet.

The SELECT command has the following syntax:

SELECT column1Name, column2Name, ... FROM tableName;

For example, if we want to displays all columns and all rows of the DEPARTMENTS table we
have just write the query like given below:

SELECT department_id, department_name, manager_id, location_id FROM departments;

4.2.Specifying some criteria with WHERE clause


Some criteria can be applied using WHERE clause in the SELECT statement to filter the results
of a query. The Syntax of SELECT statement with WHERE clause is:

SELECT column1Name, column2Name, ... FROM tableName WHERE criteria

For Example,
If we want to select all employeeswhose salary is greater than 10,000 from the table
employeesthe query for the statement is written as follows:

SELECT * from employees WHERE salary > 10000

4.3.Comparison Operators
For numbers (INT, DECIMAL, FLOAT), you can use comparison operatorsto compare two
numbers, Table 2 enlists some basic comparison operators.

Operator Name
= equal to
<> or != not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Table 2: Comparison Operator

Department of Computer Science, Page 4


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

For example: (For less than sign)


If we want to select all employees whose salary is less than 10,000 from the table employees the
query for the statement is written as follows:

SELECT * from employees WHERE salary< 10000

For example: (For equal sign)


If we want to select all departments whose location id is 1700, the query for the statement is
written as follows:

SELECT * from departments WHERE location_id =1700

For example: (For not equal sign)


If we want to select all departments whose manager id is not 200, the query for the statement is
written as follows:

SELECT * from departments WHERE manager_id !=200

For example: (For less than or equal sign)


If we want to select all countries whose region_id is less or equal to 2, the query for the
statement is written as follows:

SELECT * from countries WHERE region_id<=2

4.4.String Pattern Matching - LIKE and NOT LIKE


For strings, in addition to full matching using operators like '=' and '<>', we can perform pattern
matching using operator LIKE (or NOT LIKE) with wildcard characters.

The wildcard '_'matches any single character; '%' matches any number of characters (including
zero). See Table 3For examples of some patterns.

Pattern Matches to
'abc%' strings beginning with 'abc'
'%xyz' strings ending with 'xyz'
'%aaa%' strings containing 'aaa'
'___' strings containing exactly three characters
'a_b%' strings beginning with 'a', followed by any
single character, followed by 'b', followed by
zero or more characters.
Table 3: Pattern examples for LIKE and NOT LIKE operators

Department of Computer Science, Page 5


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

For examples:
To select all employees whose first namebegins with 'a':

SELECT * FROM employees WHERE first_name LIKE 'a%';

For examples:
To select all employees whose first name end with 'a':

SELECT * FROM employees WHERE first_name LIKE '%a';

4.5.IS NULL, IS NOT NULL


NULL is a special value, which represent "no value", "missing value" or "unknown value". You
can checking if a column contains NULL by IS NULL or IS NOT NULL.

For example:
To select all departments whose manager_idis NULL.

SELECT * FROM departments WHERE manager_id IS NULL;

4.6.Logical Operators - AND, OR:


You can combine multiple conditions with logical operators AND, OR, XOR. You can also
invert a condition using operator NOT.

For examples:
To select all employees whose salary is greater than 10,000 and first name starts with ‘a%’ the
query for the statement is written as follows:

SELECT * FROM employees WHERE salary > 10000 AND first_name LIKE 'N%';

For examples:
To select all employees whose salary is greater than 5000 or the first name end with ‘%a’ the
query for the statement is written as follows:

SELECT * FROM employees WHERE salary >5000 OR first_name LIKE 'a %';

4.7.BETWEEN, NOT BETWEEN


To check if the value is within a range, you can use BETWEEN operator. This is easier and
clearer than the equivalent AND-OR expression.

For example:
To select all employees whose salary is between 500 and 20,000, the query for the statement is
written as follows:

Department of Computer Science, Page 6


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

SELECT * FROM employees WHERE salary between 500 and 20,000;

5.1 SELECT Advanced


You can select data according to the requirements There are more techniques available to
retrieve the data according to our need i.e. sorting the result set, limiting records, Grouping etc.
In this lab, you will learn three clauses i.e. ORDER BY, DISTINCT, and LIMIT for better
selection of the records from a database.

5.2 Sorting the ResultSet with ORDER BY Clause


You can order the rows selected using ORDER BY clause with SELECT statement, with the
following syntax:

SELECT column1,…,columnN FROM tableName


WHERE criteria
ORDER BY columnA ASC|DESC, columnB ASC|DESC, ...

The selected row will be ordered according to the values in columnA, in either ascending (ASC)
(default) or descending (DESC) order. If several rows have the same value in columnA, it will be
ordered according to columnB, and so on.

For Example:
To select all thecountriesfrom the countries table and sort the result set by region id in ascending
order, the following statement can be written:

SELECT * FROM countries Order BY region_id

5.3 Limiting the Result Set using LIMIT Clause


A SELECT query on a large database may produce many rows. The LIMIT clause can be used to
show specific number of records from a result set, the syntax is:

SELECT column1,…,columnN FROM tableName


[WHERE criteria]
[ORDER BY columnA ASC|DESC, columnB ASC|DESC, ...]
[LIMIT [offset,] no_of_rows ]

Offset is the index of record in the result set, indexes starts from zero (0).
For Example:
To shows first 10 employees from employee table, the query of a statement can be written as:

SELECT * FROM employees LIMIT 10


Department of Computer Science, Page 7
C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

For Example:
To show first_name and last_name of employee, 3nd to 4threcords of the result set of employees
table, an offset can be defined along with required number of rows, the following statement can
be written as:

SELECT first_name, last_nameFROM employeesLIMIT 2,2

5.4 Listing distinct elements of a column using DISTINCT keyword


A column may have duplicate values, DISTINCT keyword can be used to select only distinct
values.
For examples:

If you want to retrieve a unique salaries from the employee table so we can write the query for
the statements is given below:

SELECT DISTINCT salary AS `Salaries` FROM employees;

5. Homework before Lab


You must solve the following problems at home before the lab.

5.1.Task 1
Read Data Manipulation Language (DML).

6. Procedure& Tools
In this section, procedure of the tasks and setup of required tools is defined.

6.1.StartingMySQL CLI [Expected time =5mins]


Refer to Lab 1 sec 6.1.

6.2.Walkthrough Tasks [Expected time =60mins]


This section defines the tasks with examples to better understand the concepts and experiments
we are going to perform in this lab.

6.2.1. Select statement for all rows and all columns.


To select all rows and all columns of countries, execute the following query, see Figure 4.

SELECT * from countries;

Department of Computer Science, Page 8


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

Figure 1: Select all rows for all columns

6.2.2. Select command for specific column.


To select all rows and country_id, country_name, of a country table, execute the following
query, see Figure 5.

SELECT country_id,country_namefrom countries;

Figure 2: Select Statement for Specific Column.


Department of Computer Science, Page 9
C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

6.2.3. Specifying some criteria with WHERE and conditional operator


If we want to select all employees first name and last name whose salary is greater than 10,000
from the table employees the query for the statement is written as follows:

SELECT first_name, last_name from employees WHERE salary > 10,000

Figure 3: Example of Where Clause

6.2.4. String Pattern Matching - LIKE


To select salary of employees whose first name begins with 'a':

SELECT salary FROM employees WHERE first_name LIKE 'a%';

Figure 4: Example of Like Operator

Department of Computer Science, Page 10


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

6.2.5. Logical Operators

To select all employeesfirst_name and last_name whose salary is greater than 10,000 and first
name starts with ‘a%’ the query for the statement is written as follows:

SELECT first_name, last_name FROM employees WHERE quantity > 5000 AND name LIKE 'a
%';

Figure 5: Example of Logical Operator

6.2.6. BETWEEN, NOT BETWEEN

To select all employeesfirst_name and last_name whose salary is between 10,000 and 20,000,
the query for the statement is written as follows:

SELECT first_name,last_name FROM employees WHERE salary between 10,000 and 20,000;

Figure 6: Example of Between Operator

5.1.1. Sorting ResultSet


To select all thecountries from the countries table and sort the result set by region id in

Department of Computer Science, Page 11


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

ascending order, the following statement can be written See Figure 5:

SELECT * FROM countries Order BY region_id

Figure 7: Showing products ordered by quantityInStock.

5.1.2. Showing limited Rows From a ResultSet


To shows first 10 employeesfrist_name and last_name from employee table, the query of a
statement can be written as, See Figure 5:
SELECT first_name, last_name FROM employees LIMIT 10

Figure 8: Show the 10 lowest quantity products

5.1.3. Selecting Distinct values of a column


To select unique data from a specific column you have use distinct keywords like:
For example:
Department of Computer Science, Page 12
C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

Showing unique salary from employees table we have write the query like given below:

Select distinct salary from employees.

Figure 9: Distinct

7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\fs\assignments$

7.1.Practice Task 1 [Expected time = 50mins]


If the following database not exist in your system first your import the database (See lab2
appendix section)of oracle_db (which is present in your teacher folder), See Figure 10to
understand the schema.

Department of Computer Science, Page 13


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

Figure 10: Database Design Diagram for "Oracle_db" Schema

Practice the following SQL queries:

1. Createaquerytodisplaythelastnameandsalaryofemployeesearningmorethan12,000 Rupees.
2. Createaquerytodisplaytheemployeelastnameanddepartmentnumberforemployeenumber
176.
3. Displaytheemployeelastname,jobID,andstartdateofemployeeshiredbetweenFebruary20, 1998, and
May 1, 1998. Order the query in ascending order by startdate
4. Displaythelastnameanddepartmentnumberofallemployeesindepartments20and50in
alphabetical order byname.
5. Show the list of last name and salary of employees who earn between 5,000 and 12,000Rupees, and
are in department 20 or 50. Label the columns Employeeand Monthly Salary,
respectively
6. Display the last name and hire date of every employee who was hired in1994.
7. Display the last name and job title of all employees who do not have amanager.
8. Displaythelastname,salary,andcommissionforallemployeeswhoearncommissions.Sort
data in descending order of salary andcommissions.
9. Displaythelastnamesofallemployeeswherethethirdletterofthenameisana
Department of Computer Science, Page 14
C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

10. Displaythelastnameofallemployeeswhohaveanaandaneintheirlastname.
11. Displaythelastname,job,andsalaryforallemployeeswhosejobissalesrepresentativeorstock clerk and
whose salary is not equal to 2,500, 3,500, or7,000 Rupees.
12. Displaythelastname,salary,andcommissionforallemployeeswhose commission amount is 20%

7.2.Outcomes
After completing this lab, student will be able to understand the use of DML statements and
importing and exporting a database.

8. Evaluation Task (Unseen) [Expected time = 55mins for two tasks]


The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task Description Marks
No
1 6 Procedures and Tools 05
2 7 Practice tasks and Testing 15
3 8 Evaluation Tasks (Unseen) 80

10. Further Reading

This section provides the references to further polish your skills.

10.1. Books

Text Book:

• Database Systems, A practical approach to design, implementation and management by


Thomas Connolly, Carolyn Begg, Addison Wesley , Fifth Edition,

10.2. Slides

The slides and reading material can be accessed from the folder of the class instructor available
at \\fs\lectures$\

Department of Computer Science, Page 15


C.U.S.T.
Lab 8: Data Manipulation Language (SELECT WHERE, ORDER, DISTINCT, LIMIT)

11. REFERENCES:

11.1. SQL-99 Complete, Really, by Peter Gulutzan& Trudy Pelzer.

• More examples for the SELECT command:


http://dev.mysql.com/doc/mysql/en/select.html
• MySQL operators:
http://dev.mysql.com/doc/mysql/en/non-typed_operators.html
• Built-in functions:
http://dev.mysql.com/doc/mysql/en/functions.html
• Joining tables:
http://www.melonfire.com/community/columns/trog/article.php?id=148
• Using subqeries:
http://www.melonfire.com/community/columns/trog/article.php?id=204

Department of Computer Science, Page 16


C.U.S.T.

You might also like