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

Lesson08-SQL Functions, Subqueries, and Joins

This document discusses SQL functions, joins, and subqueries. It provides examples of string, numeric, and date functions. It also explains different types of joins like inner joins, left joins, right joins, full joins, self joins, and cartesian joins. Examples are given to retrieve data using subqueries in the select, from, and where clauses. The document concludes with practice problems to write SQL queries using joins and subqueries based on given entity relationship diagrams.

Uploaded by

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

Lesson08-SQL Functions, Subqueries, and Joins

This document discusses SQL functions, joins, and subqueries. It provides examples of string, numeric, and date functions. It also explains different types of joins like inner joins, left joins, right joins, full joins, self joins, and cartesian joins. Examples are given to retrieve data using subqueries in the select, from, and where clauses. The document concludes with practice problems to write SQL queries using joins and subqueries based on given entity relationship diagrams.

Uploaded by

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

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.

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’;
SELECT order_id,order_date FROM orders WHERE WEEK(order_date)=‘48’;

1
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;
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 co_id course_code lect_id


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

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

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

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
This join returns all rows from the right table, even if there are no matches in the left table.

𝐁 ∪ (𝐀 ∩ 𝐁) = 𝐁

4
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 returns 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;

 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

5
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!

Lab 6: Using SQL Joins and Sub Queries

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

(i) List the Names of patrons who have never been issued a book.
(ii) List author, and title of books that have never been issued
(iii) List name, and email of patrons who were issued a book on ‘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’

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

6
Using the ERD, write SQL queries to ;

i. List the names and email of all students


ii. List the names and email of all students whose names begin with ‘MA’
iii. List the names and email of all students enrolled for ‘BMC’
iv. List the names and email of all students enrolled in programs from MATHS
department
v. List the names and email of all students enrolled in programs from computing and
maths departments.

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