+ All Categories
Home > Documents > SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database...

SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database...

Date post: 26-Mar-2015
Category:
Upload: jason-flynn
View: 219 times
Download: 0 times
Share this document with a friend
Popular Tags:
29
SQL – Lesson II SQL – Lesson II Grade 12 Grade 12
Transcript
Page 1: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

SQL – Lesson IISQL – Lesson IIGrade 12Grade 12

Page 2: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

The SELECT statement The SELECT statement

The The SELECTSELECT statement is used to query the database and retrieve data that statement is used to query the database and retrieve data that matches the criteria that you specify matches the criteria that you specify

The The SELECTSELECT statement has five main clauses to choose from… statement has five main clauses to choose from…

SELECTSELECT statement format: statement format:

SELECTSELECT [ALL | DISTINCT] [ALL | DISTINCT] ccolumn1olumn1[,[,column2column2]]FROMFROM table1table1[,[,table2table2]]

[[WHEREWHERE "conditions"] "conditions"][[GROUP BYGROUP BY "column-list"] "column-list"][[HAVINGHAVING "conditions] "conditions][[ORDER BYORDER BY "column-list" "column-list"

[[ASC | DESCASC | DESC] ] ] ]

Page 3: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Lets’ break it down…Lets’ break it down…

The above statement will select all of the values in the name, The above statement will select all of the values in the name, age, and salary columns from the employee table whose age age, and salary columns from the employee table whose age

is greater than 50.is greater than 50.

Example:Example: SELECTSELECT name, age, salary name, age, salary FROM FROM employee employee WHERE WHERE age > 50; age > 50;

Comparison OperatorsComparison Operators

== EqualEqual

>> Greater thanGreater than

<< Less thanLess than

>=>= Greater than or equal toGreater than or equal to

<=<= Less than or equal toLess than or equal to

<> or !=<> or != Not equal toNot equal to

LIKELIKE String comparison testString comparison test

Page 4: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Like what?Like what?

The The LIKELIKE “matching” operator can also be used in the conditional selection of the where “matching” operator can also be used in the conditional selection of the where clause…clause…

Example:Example:

SELECTSELECT name, title, dept name, title, dept FROM FROM employee employee WHERE WHERE title title LIKE LIKE 'Pro%';'Pro%';

……are keywords used to select either are keywords used to select either ALLALL (default) (default) or the “or the “DISTINCTDISTINCT" / unique records in your query results. " / unique records in your query results.

ALLALL and and DISTINCT?DISTINCT?So what about :So what about :

Let’s try a few…Let’s try a few…

Page 5: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

1.1. From the “From the “itemsOrdereditemsOrdered”” table, select a list of all items purchased for table, select a list of all items purchased for ““customerIdcustomerId” 10449. Display the customerid, item, and price for this ” 10449. Display the customerid, item, and price for this customer. customer.

2.2. Select all columns from the Select all columns from the itemsOrdereditemsOrdered table for whoever purchased a table for whoever purchased a TentTent. .

3.3. Select the Select the customerIdcustomerId, orderDate, and item values from the , orderDate, and item values from the itemsOrdereditemsOrdered table for any items in the item column that start with the letter "S". table for any items in the item column that start with the letter "S".

4.4. Select the distinct items in the Select the distinct items in the itemsOrdereditemsOrdered table. In other words, display a table. In other words, display a listing of each of the unique items from the listing of each of the unique items from the itemsOrdereditemsOrdered table. table.

ExercisesExercises

Answers :Answers :#1 #1

SELECTSELECT customerId, item, price customerId, item, price FROM FROM itemsOrdered itemsOrdered WHERE WHERE customerId=10449; customerId=10449;

#2 #2 SELECTSELECT * * FROM FROM items_ordered items_ordered WHERE WHERE item = 'Tent'; item = 'Tent';

#3 #3 SELECT SELECT customerId, orderDate, item customerId, orderDate, item FROM FROM itemsOrdered itemsOrdered WHERE WHERE item item LIKE LIKE 's%'; 's%';

#4 #4 SELECT DISTINCT SELECT DISTINCT itemitem FROM FROM itemsOrdered;itemsOrdered;

Page 6: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Aggregate Functions Aggregate Functions

MINMIN returns the smallest value in a given columnreturns the smallest value in a given column

MAXMAX returns the largest value in a given columnreturns the largest value in a given column

SUMSUM returns the sum of the numeric values in a given columnreturns the sum of the numeric values in a given column

AVGAVG returns the average value of a given columnreturns the average value of a given column

COUNTCOUNT returns the total number of values in a given columnreturns the total number of values in a given column

COUNT(*)COUNT(*) returns the number of rows in a tablereturns the number of rows in a table

We need to understand these functions before we can cover the "GROUP BY“clause. We need to understand these functions before we can cover the "GROUP BY“clause.

For example: For example:

Aggregate functions are used to “Aggregate functions are used to “compare Tocompare To” a returned column of numeric data".” a returned column of numeric data".

Page 7: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

SELECT AVG(salary) FROM employee;

SELECT AVG(salary) FROM employee WHERE title = 'Programmer';

SELECT Count(*) FROM employees;

This statement will return the number of rows in the employees table.

Exercises

1. Select the maximum price of any item ordered in the “itemsOrdered” table. Hint: Select the maximum price only.>

2. Select the average price of all of the items ordered that were purchased in the month of Dec.

3. What are the total number of rows in the itemsOrdered table?

4. For all of the tents that were ordered in the itemsOrdered table, what is the price of the lowest tent? Hint: Your query should return the price only.

Page 8: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

AnswersAnswers #1 #1 SELECTSELECT max(price) max(price) FROM FROM itemsOrdered;itemsOrdered;

#2 #2 SELECT SELECT avg(price) avg(price) FROM FROM itemsOrdered itemsOrdered WHERE WHERE orderDate orderDate LIKE LIKE '%Dec%'; '%Dec%';

#3 #3 SELECTSELECT count(*) count(*) FROM FROM itemsOrdered; itemsOrdered;

#4 #4 SELECT SELECT min(price) min(price) FROM FROM itemsOrdered itemsOrdered WHERE WHERE item = 'Tent'; item = 'Tent';

Page 9: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

The GROUP BY clause…The GROUP BY clause…

..will gather all of the rows together that contain data in the specified column(s)...will gather all of the rows together that contain data in the specified column(s).

Let's say you want to retrieve a list of the highest paid salaries in each dept:

GROUP BY dept;

Let’s look at the syntax:Let’s look at the syntax:SELECT column1, SUM(column2) FROM "list-of-tables“ GROUP BY "column-list";

The above statement selects the maximum salary for the people in each unique department. The above statement selects the maximum salary for the people in each unique department.

It will also allow aggregate functions to be performed on the one or more columns. It will also allow aggregate functions to be performed on the one or more columns.

For example: For example:

SELECTSELECT max(salary), max(salary),dept dept FROMFROM employee employee

Page 10: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

GROUP BY - Multiple Grouping Columns - What if?GROUP BY - Multiple Grouping Columns - What if?

What if you ALSO want to display their last name for the query below: What if you ALSO want to display their last name for the query below:

SELECT max(salary), dept FROM employee GROUP BY dept; SELECT max(salary), dept FROM employee GROUP BY dept;

What you'll need to do is:What you'll need to do is:

SELECT surname, max(salary), dept FROM employee GROUP BY dept, surname; SELECT surname, max(salary), dept FROM employee GROUP BY dept, surname;

This is a called "This is a called "multiple grouping columnsmultiple grouping columns". ".

Let's say you want to group everything of quantity 1 together, everything of quantity 2 together, everything of quantity 3 together, etc.

If you would like to determine what the largest cost item is for each grouped quantity (all quantity 1's, all quantity 2's, all quantity 3's, etc.), you would enter:

SELECTSELECT quantity, max(price) quantity, max(price) FROM FROM items items GROUP BY GROUP BY quantity; quantity;

Another example?Another example? Show them items table.

Page 11: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Exercises Exercises

1. How many people are in the various provinces in the customers table? Select the province and display the number of people in each.

Hint: count is used to count rows in a column, sum works on numeric data only.

2. From the itemsOrdered table, select the item, maximum price, and minimum price for each specific item in the table. Hint: The items will need to be broken up into separate groups.

3. How many orders did each customer make? Use the itemsOrdered table. Select the customerId, number of orders they made, and the sum of their orders.

Answers #1 SELECT province, count(province) FROM customers GROUP BY province;

#2 SELECT item, max(price), min(price) FROM itemsOrdered GROUP BY item;

#3 SELECT customerId, count(customerId), sum(price) FROM itemsOrdered GROUP BY customerId;

Page 12: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

The HAVING clause…The HAVING clause…

……allows you to specify conditions on the rows for each group.allows you to specify conditions on the rows for each group.

In other words, which rows should be selected will be based on the conditions you specify. In other words, which rows should be selected will be based on the conditions you specify.

SELECTSELECT column1, column1, SUMSUM(column2)(column2)FROMFROM "list-of-tables" "list-of-tables"

GROUP BYGROUP BY "column-list" "column-list"HAVINGHAVING "condition"; "condition";

Let’s look at the syntax:Let’s look at the syntax:

HAVINGHAVING can best be described by example. can best be described by example.

SELECTSELECT dept, avg(salary) dept, avg(salary)FROMFROM employee employeeGROUP BYGROUP BY dept; dept;

But, let's say that you want to ONLY calculate & display the average if their salary is over 20000: But, let's say that you want to ONLY calculate & display the average if their salary is over 20000:

SELECTSELECT dept, avg(salary) dept, avg(salary) FROM FROM employee employee GROUP BY GROUP BY dept dept HAVING HAVING avg(salary) avg(salary) > 20000; > 20000;

Page 13: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

ExercisesExercises  

1.1. How many people are in each province in the customers.tbl that have more than one person How many people are in each province in the customers.tbl that have more than one person in the province? in the province? Select province and display the number of how many people are in each if it's greater than 1.Select province and display the number of how many people are in each if it's greater than 1.

2.2. From the itemsOrdered.tbl, select the item, maximum price, and minimum price for each From the itemsOrdered.tbl, select the item, maximum price, and minimum price for each specific item in the table. specific item in the table. Only display the results if the maximum price for one of the items is greater than 190.00.Only display the results if the maximum price for one of the items is greater than 190.00.

3.3. How many orders did each customer make? Use the itemsOrdered table. How many orders did each customer make? Use the itemsOrdered table. Select customerId, number of orders they made, and the sum of their orders if they Select customerId, number of orders they made, and the sum of their orders if they purchased more than 1 item.purchased more than 1 item.

Page 14: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

AnswersAnswers

#1#1SELECTSELECT province, count(province) province, count(province) FROM FROM customers customers GROUP BY GROUP BY provinceprovinceHAVING HAVING count(province) > 1;count(province) > 1;

#2#2SELECTSELECT item, max(price), min(price) item, max(price), min(price) FROM FROM itemsOrdered itemsOrdered GROUP BY GROUP BY item item HAVING HAVING max(price) > 190.00;max(price) > 190.00;

#3 #3 SELECT SELECT customerId, count(customerId), sum(price) customerId, count(customerId), sum(price) FROM FROM itemsOrdered itemsOrdered GROUP BY GROUP BY customerId customerId HAVING HAVING count(customerId) > 1;count(customerId) > 1;

Page 15: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

The ORDER BY clause…The ORDER BY clause…

is an optional clause which allows you to display the results of your query in a sorted order… 

Let’s look at the syntax:Let’s look at the syntax:

SELECTSELECT column1, SUM(column2) column1, SUM(column2)FROM FROM "list-of-tables""list-of-tables"ORDER BY ORDER BY "column-list" [ASC | "column-list" [ASC | DESC]; DESC];

For example:

SELECTSELECT employeeId, dept, name, age, salary employeeId, dept, name, age, salaryFROM FROM employeeInfoemployeeInfo

WHEREWHERE dept = 'Sales' dept = 'Sales'ORDER BY ORDER BY salary; salary;

Or, if you would like to order based on 2 or more columns…Or, if you would like to order based on 2 or more columns…

SELECTSELECT employee_id, dept, name, age, salary employee_id, dept, name, age, salaryFROM FROM employee_infoemployee_infoWHEREWHERE dept = 'Sales' dept = 'Sales'

ORDER BY ORDER BY salary, age salary, age DESCDESC; ;

Page 16: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

ExercisesExercises

1.1. Select the surname, firstname, and city for all customers in the customers table. Display the Select the surname, firstname, and city for all customers in the customers table. Display the results in Ascending Order according to the lastname.results in Ascending Order according to the lastname.

2.2. Same thing as above, but display the results in Descending order.Same thing as above, but display the results in Descending order.

3.3. Select the item and price for all of the items in the itemsOrdered table that the price is Select the item and price for all of the items in the itemsOrdered table that the price is greater than 10.00. Display the results in Ascending order based on the price.greater than 10.00. Display the results in Ascending order based on the price.

Answers

#1#1SELECT lastname, firstname, city FROM customers ORDER BY lastname;SELECT lastname, firstname, city FROM customers ORDER BY lastname;

#2#2SELECT lastname, firstname, city FROM customers ORDER BY lastname DESC;SELECT lastname, firstname, city FROM customers ORDER BY lastname DESC;

#3#3SELECT item, price FROM itemsOrdered WHERE price > 10.00 ORDER BY price SELECT item, price FROM itemsOrdered WHERE price > 10.00 ORDER BY price ASC;ASC;

Page 17: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Combining conditions and Boolean OperatorsCombining conditions and Boolean Operators

The The ANDAND operator can be used to join two or more conditions in the operator can be used to join two or more conditions in the WHEREWHERE clause. clause.

Both sides of the Both sides of the ANDAND condition must be true in order for the condition to be met condition must be true in order for the condition to be met

SELECTSELECT column1, SUM(column2) column1, SUM(column2)FROMFROM "list-of-tables" "list-of-tables"WHEREWHERE "condition1" "condition1" ANDAND "condition2"; "condition2";

The OR operator can be used to join two or more conditions in the WHERE clause also.

Similarly…

For example

SELECTSELECT employeeId, firstname, surname, title, salary employeeId, firstname, surname, title, salaryFROM FROM employeeInfoemployeeInfoWHEREWHERE salary >= 50000.00 salary >= 50000.00 AND AND title = 'Programmer'; title = 'Programmer';

SELECTSELECT employeeId, firstname, surname, title, salary employeeId, firstname, surname, title, salaryFROMFROM employeeInfo employeeInfoWHEREWHERE salary >= 50000.00 salary >= 50000.00 ANDAND title = 'Programmer'; title = 'Programmer';

Please feel free to use brackets to separate your conditions…it makes it easier to read…Please feel free to use brackets to separate your conditions…it makes it easier to read…

Page 18: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

And/ OR continued…And/ OR continued…

Another ExampleAnother Example: SELECTSELECT firstname, surname, title, salary firstname, surname, title, salaryFROM FROM employeeInfoemployeeInfoWHEREWHERE (title = 'Sales') OR (title = 'Programmer'); (title = 'Sales') OR (title = 'Programmer');

Some few Exercises …Some few Exercises …

1.1. Select the customerId, orderDate, and item from itemsOrdered.tblSelect the customerId, orderDate, and item from itemsOrdered.tblfor all items unless they are 'Shoes‘ or ‘Shot-Guns'. for all items unless they are 'Shoes‘ or ‘Shot-Guns'.

Display the rows as long as they are not either of these two items.Display the rows as long as they are not either of these two items.

2.2. Select the item and price of all items that start with the letters 'S', 'P', or 'F'.Select the item and price of all items that start with the letters 'S', 'P', or 'F'.

Page 19: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

#1#1SELECT SELECT customerId, orderDate, item customerId, orderDate, item FROM FROM itemsOrdered itemsOrdered WHERE WHERE (item <> (item <> 'shoes') 'shoes') AND AND (item <> ‘shot-guns');(item <> ‘shot-guns');

NB: NB: You do want to use an AND here. If you were to use an OR here, then You do want to use an AND here. If you were to use an OR here, then either side of the OR will be true, and EVERY row will be displayed. For either side of the OR will be true, and EVERY row will be displayed. For example, when it encounters ' shot-guns ', it will evaluate to True since ' example, when it encounters ' shot-guns ', it will evaluate to True since ' shot-guns ' are not equal to 'shoes'.shot-guns ' are not equal to 'shoes'.

#2#2SELECT SELECT item, price item, price FROM FROM itemsOrdered itemsOrdered WHERE WHERE (item (item LIKE LIKE 'S%') 'S%') OR OR (item (item LIKE LIKE 'P%') 'P%') OR OR (item (item LIKE LIKE 'F%');'F%');

AnswersAnswers

Page 20: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

IN and BETWEEN Conditional Operators…IN and BETWEEN Conditional Operators…

SELECT col1, SUM (col2)FROM "list-of-tables"

WHERE col3 IN (list-of-values);

SELECT col1, SUM(col2)FROM "list-of-tables"

WHERE col3 BETWEEN value1 AND value2;

……are used to test whether or not a value is "in" the list of values provided are used to test whether or not a value is "in" the list of values provided after the keyword after the keyword ININ

An example: An example: SELECTSELECT employeeId, surname, salary employeeId, surname, salaryFROM FROM employeeInfoemployeeInfoWHERE WHERE surname surname ININ (Naidoo', ‘Naidu', ‘Moodley', ‘Pompilio'); (Naidoo', ‘Naidu', ‘Moodley', ‘Pompilio');

SELECTSELECT employeeId, surname, salaryF employeeId, surname, salaryFROM ROM employee_infoemployee_infoWHEREWHERE surname = Naidoo' surname = Naidoo' OR OR surname = ‘Naidu' surname = ‘Naidu' OR OR surname = ‘Moodley' surname = ‘Moodley' OROR lastname = ‘Pompilio'; lastname = ‘Pompilio';

Alternatively…Alternatively…

You can also use You can also use NOT INNOT IN to exclude the rows in your list.  to exclude the rows in your list.

Page 21: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

The BETWEEN operator The BETWEEN operator

……is used to test to see whether or not a value is “between” a value!?is used to test to see whether or not a value is “between” a value!?

For example: For example:

SELECTSELECT employeeId, age, surname, salary employeeId, age, surname, salaryFROMFROM employeeInfo employeeInfoWHEREWHERE age age BETWEEN BETWEEN 30 AND 40; 30 AND 40;

Alternatively…Alternatively…

SELECTSELECT employeeId, age, surname, salary employeeId, age, surname, salaryFROMFROM employeeInfo employeeInfoWHEREWHERE age >= 30 age >= 30 ANDAND age <= 40; age <= 40;

NB.:NB.: You can also use  You can also use NOT BETWEENNOT BETWEEN to exclude the values between your range.  to exclude the values between your range.

Let’s try a few…Let’s try a few…

Page 22: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Exercises…Exercises…

Select the date, item, and price from the itemsOrdered table for all of the rows that Select the date, item, and price from the itemsOrdered table for all of the rows that have a price value ranging from 10.00 to 80.00.have a price value ranging from 10.00 to 80.00.

Select the firstName, city, and province from the customers table for all of the rows Select the firstName, city, and province from the customers table for all of the rows where the state value is either: KZN, WC, EC, Gauteng, or Northern Cape .where the state value is either: KZN, WC, EC, Gauteng, or Northern Cape .

Answers

#1#1SELECTSELECT orderDate, item, price orderDate, item, price FROM FROM itemsOrdered itemsOrdered WHERE WHERE price price BETWEEN BETWEEN 10.00 AND 80.00;10.00 AND 80.00;

#2#2SELECTSELECT firstName, city, province firstName, city, province FROM FROM customers customers WHERE WHERE province IN (KZN', ‘WC', ‘EC', ‘Gauteng', ‘Northern Cape');province IN (KZN', ‘WC', ‘EC', ‘Gauteng', ‘Northern Cape');

Page 23: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Mathematical OperatorsMathematical Operators

++ additionaddition

-- subtractionsubtraction

**multiplicatiomultiplicationn

// divisiondivision

%% modulomodulo

ABS(x)ABS(x) returns the absolute value of xreturns the absolute value of x

SIGN(x)SIGN(x) returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively)returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively)

MOD(x,y)MOD(x,y) modulo - returns the integer remainder of x divided by y (same as x%y)modulo - returns the integer remainder of x divided by y (same as x%y)

FLOOR(x)FLOOR(x) returns the largest integer value that is less than or equal to xreturns the largest integer value that is less than or equal to x

CEILING(x) or CEIL(x)CEILING(x) or CEIL(x) returns the smallest integer value that is greater than or equal to xreturns the smallest integer value that is greater than or equal to x

POWER(x,y)POWER(x,y) returns the value of x raised to the power of yreturns the value of x raised to the power of y

ROUND(x)ROUND(x) returns the value of x rounded to the nearest whole integerreturns the value of x rounded to the nearest whole integer

ROUND(x,d)ROUND(x,d) returns the value of x rounded to the number of decimal places specified by the value dreturns the value of x rounded to the number of decimal places specified by the value d

SQRT(x)SQRT(x) returns the square-root value of xreturns the square-root value of x

Example: Example:

Some few others…

The basics…The basics…

SELECT round(salary), firstnameSELECT round(salary), firstnameFROM employee_info FROM employee_info

Page 24: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Now you try…

Select the item and per unit price for each item in the items_ordered table. Select the item and per unit price for each item in the items_ordered table. Hint: Divide the price by the quantity. Hint: Divide the price by the quantity.

The answer: Exercise #1Exercise #1select item, sum(price)/sum(quantity)select item, sum(price)/sum(quantity)

from items_orderedfrom items_orderedgroup by item;group by item;

Page 25: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Table Joins, a mustTable Joins, a must

To put it simply, the "Join" makes relational database systems "relational". To put it simply, the "Join" makes relational database systems "relational".

A "Join" can be recognized in a SQL SELECT statement if it has more than one table after the FROM keyword. A "Join" can be recognized in a SQL SELECT statement if it has more than one table after the FROM keyword.

NB.:Joins can be explained easier by demonstrating what would happen if you worked with one table only NB.:Joins can be explained easier by demonstrating what would happen if you worked with one table only

NB>:Let's say you have a one-table database that is used to keep track of all of your customers and what they purchase from your store: NB>:Let's say you have a one-table database that is used to keep track of all of your customers and what they purchase from your store:

id first lastaddress

citystate

zipdate

item price

unnecessary "redundant data" unnecessary "redundant data" id first last

address            

citystate

zip date item price

10982Wolfgang

Schultz 300 N. 1st Ave Yuma AZ 85002 032299 snowboard 45.00

10982Wolfgang

Schultz 300 N. 1st Ave Yuma AZ 85002 082899 snow shovel 35.00

10982Wolfgang

Schultz 300 N. 1st Ave Yuma AZ 85002 091199 gloves 15.00

10982Wolfgang

Schultz 300 N. 1st Ave Yuma AZ 85002 100999 lantern 35.00

10982Wolfgang

Schultz 300 N. 1st Ave Yuma AZ 85002 022900 tent 85.00

An ideal database would have two tables:An ideal database would have two tables:One for keeping track of your customersOne for keeping track of your customers

And the other to keep track of what they purchase:And the other to keep track of what they purchase:

NormalistatNormalistation…ion…

Page 26: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

"Customer_info" table:

customer_numberfirstname

lastname

address

citystate

zip

"Purchases" table:

customer_numberdate

item price

Notice 

This column, which contains the unique customer number will be used to This column, which contains the unique customer number will be used to JOINJOIN the two tables.  the two tables.

SELECT customer_info.firstname, customer_info.lastname, purchases.itemSELECT customer_info.firstname, customer_info.lastname, purchases.itemFROM customer_info, purchasesFROM customer_info, purchasesWHERE customer_info.customer_number = purchases.customer_number; WHERE customer_info.customer_number = purchases.customer_number;

his particular "Join" is known as an "Inner Join his particular "Join" is known as an "Inner Join The correct syntax though would be..The correct syntax though would be..

SELECT customer_info.firstname, customer_info.lastname, purchases.itemSELECT customer_info.firstname, customer_info.lastname, purchases.itemFROM customer_info INNER JOIN purchasesFROM customer_info INNER JOIN purchasesON customer_info.customer_number = purchases.customer_number; ON customer_info.customer_number = purchases.customer_number;

Page 27: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Another example and an exercise…

SELECT employee_info.employeeid, employee_info.lastname, employee_sales.comissionSELECT employee_info.employeeid, employee_info.lastname, employee_sales.comissionFROM employee_info, employee_salesFROM employee_info, employee_salesWHERE employee_info.employeeid = employee_sales.employeeid; WHERE employee_info.employeeid = employee_sales.employeeid;

employeeidemployeeid employeeidemployeeidemployee_salesemployee_salesemployee_infoemployee_info

Exercises

1.1. Write a query using a join to determine which items were ordered by each of the customers Write a query using a join to determine which items were ordered by each of the customers in the customers table.in the customers table. Select the customerid, firstname, lastname, order_date, item, and Select the customerid, firstname, lastname, order_date, item, andprice for everything each customer purchased in the items_ordered table.price for everything each customer purchased in the items_ordered table.

2.2. Repeat exercise #1, however display the results sorted by state in descending order.Repeat exercise #1, however display the results sorted by state in descending order.

Page 28: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

Answers

Exercise #1Exercise #1 SELECT customers.customerid, customers.firstname, customers.lastname, SELECT customers.customerid, customers.firstname, customers.lastname, 

items_ordered.order_date, items_ordered.item, items_ordered.price items_ordered.order_date, items_ordered.item, items_ordered.price FROM customers, items_ordered FROM customers, items_ordered WHERE customers.customerid = items_ordered.customerid;WHERE customers.customerid = items_ordered.customerid;

Exercise #2Exercise #2 SELECT customers.customerid, customers.firstname, customers.state, SELECT customers.customerid, customers.firstname, customers.state,

items_ordered.item items_ordered.item FROM customers, items_ordered FROM customers, items_ordered WHERE customers.customerid = items_ordered.customerid WHERE customers.customerid = items_ordered.customerid ORDER BY customers.state DESC;ORDER BY customers.state DESC;

So, what about OUTER JOINS?

Page 29: SQL – Lesson II Grade 12. The SELECT statement The SELECT statement is used to query the database and retrieve data that matches the criteria that you.

NEXT YEAR LOSERS!!!


Recommended