Department of Computing: CS-220: Database Systems Class: BSCS-4C
Department of Computing: CS-220: Database Systems Class: BSCS-4C
Class: BSCS-4C
Time: 10:00am-1:00 pm
Instructor: Dr.Sharifullah Khan
Introduction
Structured Query Language (SQL) is a high level query language which has inbuilt operators and
functions for different presentation/manipulation of the data that is retrieved.
Objectives
After performing this lab students should be able to:
1. Design SQL queries to retrieve data using SELECT clause and using logical operators.
2. Explore various inbuilt single row functions of SQL.
Tools/Software Requirement
MySQL Community Server 5.6
MySQL Workbench 6.1
Sakila Database
Description
3. You can save the query file and can also add comments using //, /* */ symbols.
4. On executing queries, results are displayed in the lower part of the screen.
5. Error or success messages are displayed in action output pane at the bottom.
6. Continue playing with the Workbench and SQL queries till you are comfortable with the
querying mechanism and have learnt the shortcuts to execute queries.
This lab is about querying databases. This lab will cover SQL keywords, functions and logical operators.
You will execute these queries using Sakila database. Modify the examples wrt Sakila database and
practice all operators/functions on the data in Sakila.
ORDER BY
The SQL ORDER BY clause allows you to sort the records in your result set. The SQL ORDER BY clause
can only be used in SQL SELECT statements.
SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;
The SQL ORDER BY clause sorts the result set based on the columns specified. If the ASC or DESC value
is omitted, it is sorted by ASC.
Example 1:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;
Example 2:
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY
clause as follows:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;
This SQL ORDER BY example would return all records sorted by the supplier_city field in
descending order.
SQL ORDER BY - Using both ASC and DESC attributes together
When sorting your result set using the SQL ORDER BY clause, you can use the ASC and
DESC attributes in a single SQL SELECT statement.
For example:
This SQL ORDER BY would return all records sorted by the supplier_city field in descending order, with
a secondary sort by supplier_state in ascending order.
1. Parentheses - if you group conditional SQL statements together by parentheses, SQL Server
evaluates the contents of these first.
2. Arithmetic - multiplication (using the operators *, /, or %)
3. Arithmetic - addition (using the operators + or -)
4. Other - String Concatenate (+)
5. Logical - NOT
6. Logical - AND
7. Logical - OR
Note: (The order of evaluation at the same precedence level is from left to right.)
Logical - AND
The AND condition allows you to create an SQL statement based on 2 or more conditions being met. It
can be used in any valid SQL statement - select, insert, update, or delete.
The AND condition requires that each condition be must be met for the record to be included in
the result set. In this case, column1 has to equal 'value1' and column2 has to equal 'value2'.
Example #1:
The first example that we'll take a look at involves a very simple example using the AND condition.
SELECT *
FROM suppliers
WHERE city = 'New York'
and type = 'PC Manufacturer';
This would return all suppliers that reside in New York and are PC Manufacturers. Because the * is used
in the select, all fields from the supplier table would appear in the result set.
Logical - OR
The OR condition allows you to create an SQL statement where records are returned when any one of
the conditions are met. It can be used in any valid SQL statement - select, insert, update, or delete.
SELECT columns
FROM tables
WHERE column1 = 'value1'
or column2 = 'value2';
The OR condition requires that any of the conditions be must be met for the record to be included in the
result set. In this case, column1 has to equal 'value1' OR column2 has to equal 'value2'.
Example #1:
The first example that we'll take a look at involves a very simple example using the OR condition.
SELECT *
FROM suppliers
WHERE city = 'New York'
or city = 'Newark';
This would return all suppliers that reside in either New York or Newark. Because the * is used in the
select, all fields from the suppliers table would appear in the result set.
Example #2:
The next example takes a look at three conditions. If any of these conditions is met, the record will
be included in the result set.
SELECT supplier_id
FROM suppliers
WHERE name = 'IBM'
or name = 'Hewlett Packard'
or name = 'Gateway';
This SQL statement would return all supplier_id values where the supplier's name is either IBM, Hewlett
Packard or Gateway.
1. Logical - NOT
2. Logical - AND
3. Logical - OR
The AND and OR conditions can be combined in a single SQL statement. It can be used in any valid
SQL statement - select, insert, update, or delete.
When combining these conditions, it is important to use brackets so that the database knows what
order to evaluate each condition.
Example #1:
The first example that we'll take a look at an example that combines the AND and OR conditions.
SELECT *
FROM suppliers
WHERE (city = 'New York' and name =
'IBM') or (city = 'Newark');
This would return all suppliers that reside in New York whose name is IBM and all suppliers that reside in
Newark. The brackets determine what order the AND and OR conditions are evaluated in.
Example #2:
SELECT supplier_id
FROM suppliers WHERE
(name = 'IBM')
or (name = 'Hewlett Packard' and city = 'Atlantic City')
or (name = 'Gateway' and status = 'Active' and city = 'Burma');
This SQL statement would return all supplier_id values where the supplier's name is IBM or the name
is Hewlett Packard and the city is Atlantic City or the name is Gateway, the status is Active, and the city
is Burma.
A function is similar to an operator in operation. A function is a name that performs a specific task. A
function may or may not take values (arguments) but it always returns a value as the result. If function
takes values then these values are to be given within parentheses after the function name. The
following is the general format of a function.
If the function doesn’t take any value then function name can be used alone and even parentheses
are not required.
Single-row functions return a single result row for every row of a queried table or view. These functions can
appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses, and HAVING clauses.
Arithmetic functions perform take numeric data; date functions take date type data and string
functions take strings. Conversion functions are used to convert the given value from one type to
another. Miscellaneous functions perform operations on any type of data. Group functions are used to
perform operations on the groups created by GROUP BY clause.
Character Functions
Character functions operate on values of dataype CHAR or VARCHAR.
LOWER
select LOWER(first_name)
from actor;
UPPER
Returns a given string in UPPER case.
select UPPER(first_name)
from actor;
LENGTH
select length(first_name)
from actor;
CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more arguments.
+ +
---------------------------------------------------------+ +
MySQL
CONCAT_WS(separator,str1,str2,...)
CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The first
argument is the separator for the rest of the arguments. The separator is added between the strings to
be concatenated. The separator can be a string, as can the rest of the arguments. If the separator is
NULL, the result is NULL.
SELECT CONCAT_WS(',','First name','Last Name' );
+ +
---------------------------------------------------------+ +
LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr to a length of len characters. If str is longer
than len, the return value is shortened to len characters.
SELECT LPAD('hi',4,'??');
+ +
| LPAD('hi',4,'??') |
---------------------------------------------------------+ +
| ??hi |
---------------------------------------------------------+ +
RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr to a length of len characters. If str is longer
than len, the return value is shortened to len characters.
SELECT RPAD('hi',5,'?');
+ +
| RPAD('hi',5,'?') |
---------------------------------------------------------+ +
| hi??? |
+--------------------------------------------------------- +
LTRIM(str)
| LTRIM(' lecture') |
---------------------------------------------------------+ +
| lecture |
---------------------------------------------------------+ +
REPEAT(str,count)
Returns a string consisting of the string str repeated count times. If count is less than 1, returns an
empty string. Returns NULL if str or count are NULL.
+ +
| REPEAT('MySQL', 3) |
---------------------------------------------------------+ +
| MySQLMySQLMySQL |
---------------------------------------------------------+ +
RTRIM(str)
+ +
| RTRIM('barbar ') |
---------------------------------------------------------+ +
| barbar |
---------------------------------------------------------+ +
SUBSTRING(str,pos)
SUBSTRING(str,pos,len)
SUBSTRING(str FROM pos FOR len)
The forms without a len argument return a substring from string str starting at position pos. The forms
with a len argument return a substring len characters long from string str, starting at position pos. The
forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos. In this
case, the beginning of the substring is pos characters from the end of the string, rather than the
beginning. A negative value may be used for pos in any of the forms of this function.
SELECT SUBSTRING('Quadratically',5);
+ +
| SSUBSTRING('Quadratically',5) |
---------------------------------------------------------+ +
| ratically |
---------------------------------------------------------+ +
---------------------------------------------------------+ +
| SUBSTRING('foobarbar' FROM 4) |
---------------------------------------------------------+ +
| barbar |
---------------------------------------------------------+ +
---------------------------------------------------------+ +
| SUBSTRING('Quadratically',5,6) |
---------------------------------------------------------+ +
| ratica |
---------------------------------------------------------+ +
SUBSTRING_INDEX(str,delim,count)
Returns the substring from string str before count occurrences of the delimiter delim. If count is
positive, everything to the left of the final delimiter (counting from the left) is returned. If count is
negative, everything to the right of the final delimiter (counting from the right) is returned.
SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.
+---------------------------------------------------------+
| SUBSTRING_INDEX('www.mysql.com', '.', 2) |
+ +
| www.mysql |
---------------------------------------------------------+ +
Arithmetic Operators:
Arithmetics operators and functions are available in MYSQL which are used for
arithmetic operations. You can explore them online.
LAB TASKS
Question No. 1: Select the names of employees whose salary is between 1000 and 3000, or those who do
not get commission.
Question No. 2: Write a query to display the names of employees in the following format.
Question No. 3: Generate a report titled “IBM_EmployeeReport”, showing the details of each of the
employees of “IBM Company” in the format: “Smith is a Clerk and has salary of 800$! “
Question No. 4: Write a query to display the first name and salary for all employees. Format the salary
to be 10 characters long, left-padded with the $ symbol. Label the column SALARY.
Question No. 5: Write a query to display leading zeros before low and high salary.
Question No. 6: Practice the Mathematical functions & Arithmetic operators present in MYSQL.
Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information needs as
well as snapshot of their outcome when executed over MySQL using the Workbench.