2 The SELECT statementThe SELECT statement is used to query the database and retrieve data that matches the criteria that you specifyThe SELECT statement has five main clauses to choose from…SELECT statement format:SELECT [ALL | DISTINCT] column1[,column2] FROM table1[,table2][WHERE "conditions"] [GROUP BY "column-list"] [HAVING "conditions] [ORDER BY "column-list"[ASC | DESC] ]
3 Lets’ break it down… Example: SELECT name, age, salary FROM employee WHERE age > 50;The above statement will select all of the values in the name, age, and salary columns from the employee table whose age is greater than 50.Comparison Operators=Equal>Greater than<Less than>=Greater than or equal to<=Less than or equal to<> or !=Not equal toLIKEString comparison test
4 Like what? So what about : The LIKE “matching” operator can also be used in the conditional selection of the where clause…Example:SELECT name, title, dept FROM employee WHERE title LIKE 'Pro%';So what about :ALL and DISTINCT?…are keywords used to select either ALL (default)or the “DISTINCT" / unique records in your query results.Let’s try a few…
5 items_orderedExercisesFrom the “itemsOrdered” table, select a list of all items purchased for “customerId” Display the customerid, item, and price for this customer.Select all columns from the itemsOrdered table for whoever purchased a Tent.Select the customerId, orderDate, and item values from the itemsOrdered table for any items in the item column that start with the letter "S".Select the distinct items in the itemsOrdered table. In other words, display a listing of each of the unique items from the itemsOrdered table.Answers :#1SELECT customerId, item, price FROM itemsOrdered WHERE customerId=10449;#2SELECT * FROM items_ordered WHERE item = 'Tent';#3SELECT customerId, orderDate, item FROM itemsOrdered WHERE item LIKE 's%';#4SELECT DISTINCT item FROM itemsOrdered;
6 Aggregate FunctionsAggregate functions are used to “compare To” a returned column of numeric data".MINreturns the smallest value in a given columnMAXreturns the largest value in a given columnSUMreturns the sum of the numeric values in a given columnAVGreturns the average value of a given columnCOUNTreturns the total number of values in a given columnCOUNT(*)returns the number of rows in a tableWe need to understand these functions before we can cover the "GROUP BY“clause.For example:
7 Exercises 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.ExercisesSelect 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.
8 Answers #1 SELECT max(price) FROM itemsOrdered; #2 SELECT avg(price) FROM itemsOrdered WHERE orderDate LIKE '%Dec%';#3SELECT count(*) FROM itemsOrdered;#4SELECT min(price) FROM itemsOrdered WHERE item = 'Tent';
9 The GROUP BY clause…..will gather all of the rows together that contain data in the specified column(s).It will also allow aggregate functions to be performed on the one or more columns.For example:Let's say you want to retrieve a list of the highest paid salaries in each dept:SELECT max(salary),dept FROM employeeGROUP BY dept;The above statement selects the maximum salary for the people in each unique department.Let’s look at the syntax:SELECT column1, SUM(column2) FROM "list-of-tables“ GROUP BY "column-list";
10 GROUP BY - Multiple Grouping Columns - What if? What if you ALSO want to display their last name for the query below:SELECT max(salary), dept FROM employee GROUP BY dept;What you'll need to do is:SELECT surname, max(salary), dept FROM employee GROUP BY dept, surname;This is a called "multiple grouping columns".Another example?Show them items table.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:SELECT quantity, max(price) FROM items GROUP BY quantity;
11 ExercisesHow 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.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#1SELECT province, count(province) FROM customers GROUP BY province;#2SELECT item, max(price), min(price) FROM itemsOrdered GROUP BY item;#3SELECT customerId, count(customerId), sum(price) FROM itemsOrdered GROUP BY customerId;
12 The HAVING clause……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.Let’s look at the syntax:SELECT column1, SUM(column2) FROM "list-of-tables" GROUP BY "column-list" HAVING "condition";HAVING can best be described by example.SELECT dept, avg(salary) FROM employee GROUP BY dept;But, let's say that you want to ONLY calculate & display the average if their salary is over 20000:SELECT dept, avg(salary) FROM employee GROUP BY dept HAVING avg(salary) > 20000;
13 Exercises 1. How many people are in each province in the customers.tbl that have more than one person in the province?Select province and display the number of how many people are in each if it's greater than 1.2. From the itemsOrdered.tbl, select the item, maximum price, and minimum price for each specific item in the table.Only display the results if the maximum price for one of the items is greater than3. 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 purchased more than 1 item.
14 Answers#1SELECT province, count(province) FROM customers GROUP BY provinceHAVING count(province) > 1;#2SELECT item, max(price), min(price) FROM itemsOrdered GROUP BY item HAVING max(price) > ;#3SELECT customerId, count(customerId), sum(price) FROM itemsOrdered GROUP BY customerId HAVING count(customerId) > 1;
15 The ORDER BY clause… For example: is an optional clause which allows you to display the results of your query in a sorted order… Let’s look at the syntax:SELECT column1, SUM(column2) FROM "list-of-tables" ORDER BY "column-list" [ASC | DESC];For example:SELECT employeeId, dept, name, age, salary FROM employeeInfo WHERE dept = 'Sales' ORDER BY salary;Or, if you would like to order based on 2 or more columns…SELECT employee_id, dept, name, age, salary FROM employee_info WHERE dept = 'Sales' ORDER BY salary, age DESC;
16 ExercisesSelect the surname, firstname, and city for all customers in the customers table. Display the results in Ascending Order according to the lastname.Same thing as above, but display the results in Descending order.Select the item and price for all of the items in the itemsOrdered table that the price is greater than Display the results in Ascending order based on the price.Answers#1SELECT lastname, firstname, city FROM customers ORDER BY lastname;#2SELECT lastname, firstname, city FROM customers ORDER BY lastname DESC;#3SELECT item, price FROM itemsOrdered WHERE price > ORDER BY price ASC;
17 Combining conditions and Boolean Operators The AND operator can be used to join two or more conditions in the WHERE clause.Both sides of the AND condition must be true in order for the condition to be metSELECT column1, SUM(column2) FROM "list-of-tables" WHERE "condition1" AND "condition2";Similarly…The OR operator can be used to join two or more conditions in the WHERE clause also.For exampleSELECT employeeId, firstname, surname, title, salary FROM employeeInfo WHERE salary >= AND title = 'Programmer';Please feel free to use brackets to separate your conditions…it makes it easier to read…SELECT employeeId, firstname, surname, title, salary FROM employeeInfo WHERE salary >= AND title = 'Programmer';
18 And/ OR continued… Another Example: Some few Exercises … SELECT firstname, surname, title, salary FROM employeeInfo WHERE (title = 'Sales') OR (title = 'Programmer');Some few Exercises …Select the customerId, orderDate, and item from itemsOrdered.tblfor all items unless they are 'Shoes‘ or ‘Shot-Guns'.Display the rows as long as they are not either of these two items.2. Select the item and price of all items that start with the letters 'S', 'P', or 'F'.
19 Answers#1SELECT customerId, orderDate, item FROM itemsOrdered WHERE (item <> 'shoes') AND (item <> ‘shot-guns');NB: 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 example, when it encounters ' shot-guns ', it will evaluate to True since ' shot-guns ' are not equal to 'shoes'.#2SELECT item, price FROM itemsOrdered WHERE (item LIKE 'S%') OR (item LIKE 'P%') OR (item LIKE 'F%');
20 IN and BETWEEN Conditional Operators… You can also use NOT IN to exclude the rows in your list.…are used to test whether or not a value is "in" the list of values provided after the keyword INSELECT 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;An example:SELECT employeeId, surname, salary FROM employeeInfo WHERE surname IN (Naidoo', ‘Naidu', ‘Moodley', ‘Pompilio');Alternatively…SELECT employeeId, surname, salaryFROM employee_info WHERE surname = Naidoo' OR surname = ‘Naidu' OR surname = ‘Moodley'OR lastname = ‘Pompilio';
21 The BETWEEN operator For example: Alternatively… …is used to test to see whether or not a value is “between” a value!?For example:SELECT employeeId, age, surname, salary FROM employeeInfo WHERE age BETWEEN 30 AND 40;Alternatively…SELECT employeeId, age, surname, salary FROM employeeInfo WHERE age >= 30 AND age <= 40;NB.: You can also use NOT BETWEEN to exclude the values between your range.Let’s try a few…
22 Exercises…Select the date, item, and price from the itemsOrdered table for all of the rows that have a price value ranging from toSelect 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 .Answers#1SELECT orderDate, item, price FROM itemsOrdered WHERE priceBETWEEN AND 80.00;#2SELECT firstName, city, province FROM customers WHERE province IN (KZN', ‘WC', ‘EC', ‘Gauteng', ‘Northern Cape');
23 Mathematical Operators The basics…+addition-subtraction*multiplication/division%moduloSome few others…ABS(x)returns the absolute value of xSIGN(x)returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively)MOD(x,y)modulo - returns the integer remainder of x divided by y (same as x%y)FLOOR(x)returns the largest integer value that is less than or equal to xCEILING(x) or CEIL(x)returns the smallest integer value that is greater than or equal to xPOWER(x,y)returns the value of x raised to the power of yROUND(x)returns the value of x rounded to the nearest whole integerROUND(x,d)returns the value of x rounded to the number of decimal places specified by the value dSQRT(x)returns the square-root value of xExample:SELECT round(salary), firstname FROM employee_info
24 Now you try… The answer: Select the item and per unit price for each item in the items_ordered table.Hint: Divide the price by the quantity.The answer:Exercise #1select item, sum(price)/sum(quantity) from items_ordered group by item;
25 Table Joins, a mustTo 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.NB.:Joins can be explained easier by demonstrating what would happen if you worked with one table onlyNB>: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:idfirstlastaddresscitystatezipdateitempriceunnecessary "redundant data"idfirstlastaddress citystatezipdateitemprice10982WolfgangSchultz300 N. 1st AveYumaAZ85002032299snowboard45.00082899snow shovel35.00091199gloves15.00100999lantern022900tent85.00An ideal database would have two tables:One for keeping track of your customersAnd the other to keep track of what they purchase:Normalistation…
26 This column, which contains the unique customer number will be used to JOIN the two tables. "Customer_info" table:customer_numberfirstnamelastnameaddresscitystatezipNotice "Purchases" table:customer_numberdateitempriceSELECT customer_info.firstname, customer_info.lastname, purchases.item FROM customer_info, purchases WHERE customer_info.customer_number = purchases.customer_number;his particular "Join" is known as an "Inner JoinThe correct syntax though would be..SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM customer_info INNER JOIN purchases ON customer_info.customer_number = purchases.customer_number;
27 Another example and an exercise… SELECT employee_info.employeeid, employee_info.lastname, employee_sales.comission FROM employee_info, employee_sales WHERE employee_info.employeeid = employee_sales.employeeid;employee_salesemployee_infoemployeeidemployeeidExercisesWrite a query using a join to determine which items were ordered by each of the customersin the customers table. Select the customerid, firstname, lastname, order_date, item, andprice for everything each customer purchased in the items_ordered table.2. Repeat exercise #1, however display the results sorted by state in descending order.
28 Answers So, what about OUTER JOINS? Exercise #1 SELECT customers.customerid, customers.firstname, customers.lastname, items_ordered.order_date, items_ordered.item, items_ordered.price FROM customers, items_ordered WHERE customers.customerid = items_ordered.customerid;Exercise #2SELECT customers.customerid, customers.firstname, customers.state, items_ordered.item FROM customers, items_ordered WHERE customers.customerid = items_ordered.customerid ORDER BY customers.state DESC;So, what about OUTER JOINS?