Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Lesson08-SQL Functions, Subqueries, and Joins

Uploaded by

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

Lesson08-SQL Functions, Subqueries, and Joins

Uploaded by

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

8 Lesson 8: SQL Functions, Joins, and Sub Queries

In this lesson, we shall learn how to use SQL built in functions, Sub queries, and Joins to answer
more complex questions(queries) as opposed to the simple queries described in the previous lesson.

8.1 SQL In-built Functions


The main types of SQL functions are string, numeric, date and aggregate functions. Consider our
earlier database, bikeshop.

Strings functions

String functions operate on string data types

Example 8.1 String Function Examples


SELECT LEFT(last_name,3) FROM customers ;
SELECT RIGHT(last_name,4) FROM customers ;
SELECT firstname,last_name FROM customers
WHERE LEFT(last_name,4) =’kson’ ;
SELECT firstname,last_name FROM customers
WHERE SUBSTRING(last_name,1,3) =’jac’ ;
SELECT firstname,last_name FROM customers
WHERE LENGTH(last_name)=’6’ ;

Numeric functions

Numeric functions operate on numeric data types. The function include mathematical functions like
eg. round, log, sin, acos, cos, tan, abs etc

Example 8.2
SELECT ROUND(list_price,0) FROM products;
SELECT ROUND(list_price, -2) FROM products;
SELECT ABS(list_price) FROM products;

Date functions

Date functions operate on date data types .

Example 8.3
SELECT order_id,order_date FROM orders WHERE
YEAR(order_date)=‘2016’;
SELECT order_id,order_date FROM orders WHERE MONTH(order_date)=‘2’;
SELECT order_id,order_date FROM orders WHERE DAY(order_date)=‘18’;

1
SELECT order_id,order_date FROM orders WHERE WEEK(order_date)=‘48’;
SELECT order_id,order_date FROM orders WHERE
DAYOFWEEK(order_date)=‘monday’;
SELECT order_id,order_date FROM orders WHERE MONTHNAME(order_date)=
'march';
SELECT order_id,order_date FROM orders
WHERE DATEDIFF(required_date,order_date)<'1';

Aggregate functions

Aggregate functions operate on all of the data types and produce summarized result sets

Example 8.4
SELECT product_id ,COUNT(item_id) FROM order_items GROUP BY
product_id;
SELECT product_id ,SUM(list_price) FROM order_items GROUP BY
product_id;
SELECT AVG(list_price) FROM order_items;
SELECT model_year ,MAX(list_price), MIN(list_price FROM products
GROUP BY model_year;
8.2 Subqueries
A subquery is a SQL query nested inside a larger query.

A subquery may occur in:

 A SELECT clause
 A FROM clause
 A WHERE clause

The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside
another subquery.

A subquery is usually added within the WHERE Clause of another SQL SELECT statement.

You can use the comparison operators, such as >, <, or =. The comparison operator can also be a
multiple-row operator, such as IN, ANY, or ALL.

A subquery is also called an inner query or inner select, while the statement containing a subquery is
also called an outer query or outer select.

The inner query executes first before its parent query so that the results of an inner query can be
passed to the outer query.

You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the
following tasks:

 Compare an expression to the result of the query.


 Determine if an expression is included in the results of the query.

2
 Check whether the query selects any rows.

Consider the following two database tables;

For more clarity, let us consider the following data;

lect_id Lect_name
1 James Mukiri
2 Alexander Maina
3 George Mutisya
4 Hellen Waiganjo
5 Alexander Maina
6 Sabina Mwirichia
co_id course_code lect_id
2 CIC 3425 1
By examining the relationship 3 CCS 3425 2
between the two tables, using the 4 CIT 3378 1
lect_id primary and foreign keys in 5 CIC 3426 1
6 CIT 3375 2
the lecturers and courses_offered 8 CIC 3479
table respectively, the following can 9 SMS 3275
be easily deduced. 10 UCU 3103
11 CIC 3428 1
There are 6 different lecturers in the 12 CIT 3475 2
lecturers table, and 22 different 13 CIC 3475 2
courses in the courses_offered table. 14 CIC 3476 5
15 CIT 3377 1
Lecturers 1,2, and 5 have been 16 BFB 3101 5
assigned courses, while 3,4, and 6 17 CIT 3335 5
18 CIC 3428 1
have not been assigned any courses.
19 CIT 3475 2
20 CIC 3475 2
21 CIC 3476 5
22 CIT 3377 1
23 BFB 3101 5
24 CIT 3335 5

Example 8.5
SELECT lect_id, lect_name FROM lecturers
WHERE lect_id IN (SELECT DISTINCT lect_id FROM courses_offered);

3
The above query list the IDs and names of lecturers who have been assigned courses.

Example 8.6
SELECT lect_id, lect_name FROM lecturers WHERE lect_id NOT IN
(SELECT lect_id FROM courses_offered WHERE lect_id IS NOT NULL);
The above query list the IDs and names of lecturers who have not been assigned any courses. (Recall
why omitting the last part (IS NOT NULL) in the subquery will render some invalid result.)

8.3 Joins

There are different types of joins available in SQL


Inner Join

This join returns rows when there is a match in both tables.

𝐀∩𝐁
The earlier example of listing of lecturers who have been assigned courses can be achieved using an
inner join as follows;

Example 8.7
SELECT L.lect_id, L.lect_name FROM lecturers L
INNER JOIN courses_offered C ON L.lect_id= C.lect_id;

Left Join

This join returns all rows from the left table, even if there are no matches in the right table.

𝐀 ∪ (𝐀 ∩ 𝐁)
Example 8.8
SELECT L.lect_id, L.lect_name,C.course_code FROM lecturers L
LEFT JOIN courses_offered C ON L.lect_id= C.lect_id;

Right Join

4
This join returns all rows from the right table, even if there are no matches in the left table.

𝐁 ∪ (𝐀 ∩ 𝐁)
Example 8.9
SELECT L.lect_id, L.lect_name,C.course_code FROM lecturers L
RIGHT JOIN courses_offered C ON L.lect_id= C.lect_id;

Full Join

This join returns rows when there is a match in one of the tables.

𝐀∪𝐁
Example 8.10
SELECT L.lect_id, L.lect_name FROM lecturers L
FULL JOIN courses_offered C ON L.lect_id= C.lect_id;

A FULL JOIN is not supported by MySQL, but is supported by other major SQL DBMS vendors
like Oracle and MSSQL.

The results of a FULL JOIN can be achieved in MySQL, by performing a UNION operation on
LEFT JOIN and RIGHT JOIN

Example 8.11
SELECT L.lect_id, L.lect_name,C.course_code FROM lecturers L
LEFT JOIN courses_offered C ON L.lect_id= C.lect_id
UNION
SELECT L.lect_id, L.lect_name,C.course_code FROM lecturers L
RIGHT JOIN courses_offered C ON L.lect_id= C.lect_id;
Self Join

This join is used to join a table to itself as if the table were two tables, temporarily renaming at least
one table in the SQL statement. 𝑨 ∩ 𝑨′

This join is commonly used to find entities sharing similar attributes in a relation. For Example;

5
 Different customers who live in the same address
 Different customers sharing a phone number
 Different lecturers having the same names.

Example 8.12
SELECT L1.lect_id, L1.lect_name FROM lecturers L1
INNER JOIN lecturers L2 ON L1.lect_name= L2.lect_name
WHERE L1.lect_id<> L2.lect_id;

Cartesian Join

This join returns the Cartesian product of the sets of records from the two or more joined tables.

AxB
Example 8.13
SELECT L.lect_id, L.lect_name FROM lecturers L ,courses_offered C
WHERE L.lect_id= C.lect_id;
This JOIN is computationally more inefficient than the Inner, Left, and Right joins. Without the
WHERE clause, this join returns a multiplication of rows of the first and the second table; resulting
to irrelevant information -literally!

8.4 Lab 6: Using SQL Joins and Sub Queries

1. Recall our earlier case study based on the ERD below.

(i) Write an SQL query to list the name and phone of all owners
select oname, phone from owners;
(ii) Write an SQL query to list the regno and make of all vehicles
(iii) Write an SQL query to list the name and phone of all owners who are female
select oname, phone from owners where gender=’f’;
(iv) Write an SQL query to list the regno and make of all vehicles that are red in color
select regno, make from vehicles where color=’red’;
(v) Write an SQL query to list the name of owners and the registration numbers of their
vehicles

6
select o.oname,v.regno from owners o
join vehicles v on v.oid=o.oid;
(vi) Write an SQL query to list the name and phone of all owners who do not have a
vehicle
(vii) Write an SQL query to list the name of female owners, who own vehicles that are
red in color .
select o.oname,v.regno from owners o
join vehicles v on v.oid=o.oid
where o.gender=’f’ and v.color=’red’;

2. Recall our earlier case study based on the ERD below.

(i) List the Names of patrons who have never been issued a book.
Select name from patrons where patronid not in (select patronid from issues)
(ii) List author, and title of books that have never been issued
Select author , title from books where bookid not in (select bookid from issues)
(iii) List name, and email of patrons who were issued a book on ‘2021-11-16’
select p.name,p.email from patrons p
join issues I on p.patronid=i.patronid
where i.idate=’2021-11-16’
(iv) Update the status all books that have never been borrowed to ‘Archived’
(v) List name, and email of patrons who have ever been issued with a book authored by
‘Anthony irungu’
select p.name,p.email from patrons p
join issues I on p.patronid=i.patronid
join books b on i.bookid=b.bookid;

3. Recall our earlier case study based on the ERD below.

7
Using the ERD, write SQL queries to ;

i. List the names and email of all students


SELECT sname, email from students;

ii. List the names and email of all students whose names begin with ‘MA’
SELECT sname,email from students where sname like ‘MA%’;

iii. List the names and email of all students enrolled for ‘BIT’
iv. List the names and email of all students enrolled in programs from the “IT”
department

v. List the names and email of all students enrolled in programs from SCI.

4. Recall our earlier case study on the “bikeshop” database and attempt to answer the following
questions using SQL queries.
i. How many orders are in the "orders" table?
ii. How many customers whose names begin with "Ja"?
iii. What is the average list price of the products?
iv. List all orders sorted by order date in descending order.
v. How many products of list price between 900 and 2000 and have orders on ‘2016-
02-14’?
vi. How many times has a product from the Ritchey brand been ordered by a customer
from New York (NY) state?
vii. List all products ordered by customers from the same city as the store where the
product is stocked?
viii. List the customer names and the number of orders made by each customer; but do
not show the cases where only one order was made.

You might also like