1 querying a single table structured query language (sql) - part ii
TRANSCRIPT
1
Querying a Single TableQuerying a Single Table
Structured Query Language (SQL) - Part II
2SELECTSELECT
SELECT allows you to query the database We will first consider SELECT statements with one
table
SELECT [DISTINCT | ALL] {* | select_list}FROM {table_name [alias] | view_name}
[{table_name [alias] | view_name}] …[WHERE condition][GROUP BY condition_list][HAVING condition][ORDER BY {column_name [ASC | DESC]} …]
3SELECTSELECT
Employee TableEID Ename Department Salary1001 John Finance 400001002 Jacob Finance 450001003 Joe Accounting 350001004 Jane Marketing 500001005 Jill Accounting 300001006 Jeb Marketing 350001007 Judy Info Tech 400001008 Josh Info Tech 50000
SELECT EID, Ename FROM Employee;
EID ENAME1001 John1002 Jacob1003 Joe1004 Jane1005 Jill1006 Jeb1007 Judy1008 Josh
4SELECTSELECT
Rules for specifying column names column names must match the name in the data dictionary column names must be separated by a comma column names selected must belong to the table named in the
FROM clause Column names may be specified using mixed case - the system
is not case sensitive
5SELECTSELECT
SELECT * FROM Employee;
EID Ename Department Salary1001 John Finance 400001002 Jacob Finance 450001003 Joe Accounting 350001004 Jane Marketing 500001005 Jill Accounting 300001006 Jeb Marketing 350001007 Judy Info Tech 400001008 Josh Info Tech 50000
SELECT ename name, salary FROM Employee;
Name SalaryJohn 40000Jacob 45000Joe 35000Jane 50000Jill 30000Jeb 35000Judy 40000Josh 50000
A column aliasAll Columns
6SELECTSELECT
DepartmentFinanceFinanceAccountingMarketingAccountingMarketingInfo TechInfo Tech
SELECT departmentFROM Employee;
SELECT DISTINCT departmentFROM Employee;
Use of the DISTINCT clause,the default is ALL
DepartmentAccountingFinanceInfo TechMarketing
7SELECT with WHERE ClauseSELECT with WHERE Clause
WHERE clause is followed by a condition Oracle offers nine different comparison operators:
= < > >= <= != <> !> !<
Character strings or date values must be enclosed within single quotation marks
8SELECT with WHERE ClauseSELECT with WHERE Clause
SELECT *FROM EmployeeWHERE salary > 40000;
EID Ename Department Salary1002 Jacob Finance 450001004 Jane Marketing 500001008 Josh Info Tech 50000
SELECT *FROM EmployeeWHERE department = Accounting;
Error - Invalid Column Name
9SELECT with WHERE ClauseSELECT with WHERE Clause
SELECT *FROM EmployeeWHERE department = “Accounting”;
Error - Invalid Column Name
/* Enclose char data within single quotes /*SELECT *FROM EmployeeWHERE department = ‘Accounting’;
EID Ename Department Salary 1003 Joe Accounting 350001005 Jill Accounting 30000
10AND ConditionAND Condition
SELECT ename, salaryFROM EmployeeWHERE department = ‘Finance’ AND salary > 40000;
Ename SalaryJacob 45000
SELECT *FROM EmployeeWHERE department = ‘Accounting’
AND salary > 40000;
no rows selected
11OR ConditionOR Condition
SELECT ename, department, salaryFROM EmployeeWHERE department = ‘Finance’
OR department = ‘Marketing’;
Ename Department SalaryJohn Finance 40000Jacob Finance 45000Jane Marketing 50000Jeb Marketing 35000
12Combining AND with ORCombining AND with OR
/* Be careful when you combine AND with OR */SELECT ename, department, salaryFROM EmployeeWHERE department = ‘Finance’
OR department = ‘Marketing’AND salary > 40000;
Ename Department SalaryJohn Finance 40000Jacob Finance 45000Jane Marketing 50000
13Combining AND with ORCombining AND with OR
SELECT ename, department, salaryFROM EmployeeWHERE (department = ‘Finance’
OR department = ‘Marketing’)AND salary > 40000;
Ename Department SalaryJacob Finance 45000Jane Marketing 50000
14ORDER BY ClauseORDER BY Clause
ORDER BY is used when you want to sort the result of a query
ORDER BY is followed by one or more column names (max 16) separated by commas
The default sorting order is ascending (low to high) You can sort the result in descending order (high to
low) by using the optional keyword DESC ASC or DESC keywords follow the respective
column names specified in the ORDER BY clause
15ORDER BY ClauseORDER BY Clause
SELECT ename, deaprtment, salaryFROM EmployeeWHERE salary >= 40000ORDER BY department;
Ename Department SalaryJohn Finance 40000Jacob Finance 45000Judy Info Tech 40000Josh Info Tech 50000Jane Marketing 50000
16ORDER BY ClauseORDER BY Clause
SELECT ename, deaprtment, salaryFROM EmployeeWHERE salary >= 40000ORDER BY salary desc,
department;
Ename Department SalaryJosh Info Tech 50000Jane Marketing 50000Jacob Finance 45000John Finance 40000Judy Info Tech 40000
17Condition - IN and NOT INCondition - IN and NOT IN
IN and NOT IN operators are used to create condition expressions that compare a column name to a set of values.
Values are listed within parentheses and are separated by commas
Character constants are enclosed within single quotes
18Condition - IN and NOT INCondition - IN and NOT IN
SELECT ename, departmentFROM EmployeeWHERE department = ‘Accounting’
OR department = ‘Finance’ OR department = ‘Marketing’;
SELECT ename, departmentFROM EmployeeWHERE department IN (‘Accounting’, ‘Finance’, ‘Marketing’);
Ename DepartmentJoe AccountingJill AccountingJohn FinanceJacob FinanceJane MarketingJeb Marketing
19Condition - IN and NOT INCondition - IN and NOT IN
Ename DepartmentJudy Info TechJosh Info Tech
SELECT ename, departmentFROM EmployeeWHERE department NOT IN (‘Accounting’, ‘Finance’, ‘Marketing’);
/* The above query is equivalent to the following */
SELECT ename, departmentFROM EmployeeWHERE (department <> ‘Accounting’
AND department <> ‘Finance’ AND department <> ‘Marketing’);
20BETWEEN and NOT BETWEEN BETWEEN and NOT BETWEEN
Between is used to specify an inclusive range for comparison
SELECT ename, salaryFROM EmployeeWHERE salary BETWEEN 35000 AND 45000;
Ename SalaryJohn 40000Jacob 45000Joe 35000Jeb 35000Judy 40000
/* The above query is equivalent to the following */
SELECT ename, salaryFROM EmployeeWHERE salary >= 35000 AND salary <= 45000;
21BETWEEN and NOT BETWEENBETWEEN and NOT BETWEEN
SELECT enameFROM EmployeeWHERE ename BETWEEN ‘Joe’ AND ‘Josh’;
EnameJohnJoeJosh
SELECT ename, salaryFROM EmployeeWHERE salary NOT BETWEEN 35000 AND 45000;
Name SalaryJane 50000Jill 30000Josh 50000
22LIKE - String and Character MatchingLIKE - String and Character Matching
LIKE is used to match a character string (%) or a single character ( _ )
You may mix % with _ in the same pattern
/* Find names starting with Jo */
SELECT enameFROM EmployeeWHERE ename LIKE ‘Jo%’;
NameJohnJoeJosh
SELECT ename, salary FROM EmployeeWHERE salary LIKE ‘3_000’;
Name SalaryJoe 35000Jill 30000Jeb 35000
23LIKE - String and Character MatchingLIKE - String and Character Matching
/* Find 3 lettered names starting with J */
SELECT enameFROM EmployeeWHERE ename LIKE ‘J__ ’;
NameJoeJeb
/* LIKE treats a blank space as a character *//* You must pad the pattern with blank spaces for proper execution of this query */
SELECT enameFROM EmployeeWHERE ename LIKE ‘J__ ’;
No rows selected
Note: J followed by 3 underscores and required number of blank spaceswill select all 1,2,3 and 4 lettered names starting with J.
24NULL ValuesNULL Values
A NULL value is treated as undefined If it participates in an arithmetic operation the result is always
NULL NULL values can be checked using the statement
WHERE <col name> IS [NOT] NULL
SalesAgentID Name Salary Bonus1001 John Super 20000 500001002 Jeb Broke 10000 NULL1003 Super Seller 20000 60000
SELECT nameFROM SalesAgentWHERE bonus IS NULL;
NameJeb Broke
25NULL ValuesNULL Values
SELECT Name, Salary+BonusFROM SalesAgent;
Name Salary+BonusJohn Super 70000Jeb Broke NULLSuper Seller 80000
SELECT NameFROM SalesAgentWHERE bonus IS NOT NULL;
NameJohn SuperSuper Seller
26AGGREGATE FUNCTIONSAGGREGATE FUNCTIONS
COUNT, SUM, AVG, MAX, MIN COUNT (*) : returns the number of selected rows COUNT ([ALL | DISTINCT] <expression>)
ALL is the default DISTINCT count distinct values Usually expression refers to a column name NULL values in expression are not counted - so it
counts all (distinct) non null values in the expression.
SalesAgentID Name Salary Bonus1001 John Super 20000 500001002 Jeb Broke 10000 NULL1003 Super Seller 20000 60000
27COUNT - ExamplesCOUNT - Examples
SELECT COUNT(*)FROM SalesAgentWHERE salary > 15000;
Count(*) 2
SELECT COUNT(DISTINCT salary)FROM SalesAgent;
Count(Distinct salary) 2
/* Null value is not counted */SELECT COUNT(bonus)FROM SalesAgent;
Count(bonus) 2
SELECT COUNT(salary)FROM SalesAgent;
Count(salary) 3
SELECT COUNT(*)FROM SalesAgent;
Count(*) 3
28SUMSUM
SUM ([ALL | DISTINCT] expression) total of all (distinct) values in a numeric column NULL values are excluded from computation empty column returns NULL
SELECT SUM(salary) FROM SalesAgent;
Sum(salary) 50000
SELECT SUM(DISTINCT salary) FROM SalesAgent;
Sum(Distinct salary) 30000
29SUMSUM
/* Compute the total salary and bonus paid to all salesagents */
Sum(salary+bonus) 150000
SELECT SUM(salary+bonus) FROM SalesAgent;
SELECT SUM(salary) + SUM(bonus) FROM SalesAgent;
Sum(salary)+Sum(bonus)160000
Why are the above results different?
/* Total salary paid to employees in the Finance department */
SELECT SUM(salary)FROM EmployeeWHERE department = ‘Finance’;
Sum(salary) 95000
30AVGAVG
AVG ([ALL | DISTINCT] expression) average of all (distinct) values in a numeric column NULL values are excluded from computation
SUM(x)/COUNT(*) will give different result from AVG(x) when x has null values
empty column returns NULL
SELECT AVG(salary)FROM SalesAgent;
SELECT AVG(bonus)FROM SalesAgent;
SELECT SUM(bonus)/COUNT(*)FROM SalesAgent;
AVG(salary)16666.6667
AVG(bonus) 55000
SUM(bonus)/COUNT(*)36666.6667
31MIN and MAXMIN and MAX
MIN (expression) - the lowest value in the expression MAX (expression) - the highest value in the expression MIN and MAX work with numeric as well as character data
SELECT MIN(salary)FROM SalesAgent;
SELECT MAX(salary)FROM SalesAgent;
SELECT MIN(name)FROM SalesAgent;
MIN(salary)10000
MAX(salary)20000
MIN(name)Jeb Broke
32GROUP BYGROUP BY
GROUP BY <col name> : allows grouping results column name must be from the table specified in the
FROM clause produces one line in the result for each unique value
in the specified column if this column has null values null is treated as a
group No aggregate function is allowed in the GROUP BY
clause GROUP BY AVG(salary) is not permitted
You may specify an expression listed in the SELECT clause after Group By (see pp.36 Bordoloi)
33GROUP BY- ExamplesGROUP BY- Examples
EmployeeEID Ename Department Salary1001 John Finance 400001002 Jacob Finance 450001003 Joe Accounting 350001004 Jane Marketing 500001005 Jill Accounting 300001006 Jeb Marketing 350001007 Judy Info Tech 400001008 Josh Info Tech 50000
SQL standard does not require Group By to sort the result - though a specific implementation may do so
Result may be sorted using the ORDER BY clause We will use the following table in the examples
34GROUP BY- ExamplesGROUP BY- Examples
SELECT department, COUNT(*), AVG(salary)FROM EmployeeGROUP BY department;
Department COUNT(*) AVG(salary)Accounting 2 32500Finance 2 42500Info Tech 2 45000Marketing 2 42500
SELECT department, COUNT(*), AVG(salary)FROM EmployeeGROUP BY departmentORDER BY AVG(salary) DESC;
Department COUNT(*) AVG(salary)Info Tech 2 45000Finance 2 42500Marketing 2 42500Accounting 2 32500
35GROUP BY with HAVINGGROUP BY with HAVING
HAVING condition HAVING is used with GROUP BY. HAVING clause uses group characteristics in the condition. aggregate functions are not allowed in the WHERE clause. HAVING applies a condition to groups the way WHERE
applies a condition to rows.
36HAVING - ExampleHAVING - Example
SELECT department, COUNT(*), AVG(salary)FROM EmployeeGROUP BY departmentHAVING AVG(salary) > 40000;
Department COUNT(*) AVG(salary)Finance 2 42500Info Tech 2 45000Marketing 2 42500
SELECT department, AVG(salary)FROM EmployeeWHERE department != ‘Finance’GROUP BY departmentHAVING AVG(salary) < 45000;
Department AVG(salary)Accounting 32500Marketing 42500
37ExampleExample
SELECT department, AVG(salary)FROM EmployeeWHERE department != ‘Finance’GROUP BY departmentHAVING AVG(salary) < 45000ORDER BY AVG(salary) DESC;
Department AVG(salary)Marketing 42500Accounting 32500
38SELF TESTSELF TEST
Use the Student and the Majors table that you created before in the following queries 1. List all rows in Student table 2. List names, majors and gpas of all students 3. List names, majors and gpas of all students sorted by major in
ascending order and by gpa within major in descending order 4. Print distinct major names from the student file 5. Print student count and average gpa for all students 6. Print student counts and average gpas by major Continued ….
39SELF TESTSELF TEST
Continued from previous slide 7. Print names and gpas of all students that are INSY majors and
have a gpa above 3.0 8. Print names and gpas of all students that are INSY or
Marketing majors and have a gpa above 3.0 9. What are the minimum and maximum gpas? 10. What are the minimum and maximum gpas of INSY
majors?