SlideShare a Scribd company logo
1 of 61
Department of Information Technology 1Data base Technologies (ITB4201)
Structured Query Language
Logical Operators
Dr. C.V. Suresh Babu
Professor
Department of IT
Hindustan Institute of Science & Technology
Department of Information Technology 2Data base Technologies (ITB4201)
Action Plan
• Logical Operators
• LISTS (IN AND NOT IN)
• RANGES (BETWEEN AND NOT BETWEEN)
• ORDER BY
• Aggregate functions
• GROUP BY and HAVING
• UNION
Department of Information Technology 3Data base Technologies (ITB4201)
LOGICAL OPERATORS
(AND, OR, AND NOT)
• AND : Joins two or more conditions, and returns results only
when all of the conditions are true.
• OR : Joins two or more conditions, and returns results when any
of the conditions are true.
• NOT : Negates the expression that follows it.
Department of Information Technology 4Data base Technologies (ITB4201)
AND OPERATOR
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_gender "Gender"
FROM employee
WHERE emp_gender = 'F' AND emp_last_name > ‘E'
ORDER BY emp_last_name;
Last Name First Name Gender
---------- ------------- ------
Joyner Suzanne F
Markis Marcia F
Prescott Sherri F
Department of Information Technology 5Data base Technologies (ITB4201)
OR OPERATOR
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_gender "Gender"
FROM employee
WHERE emp_gender = 'F' OR emp_last_name > 'M'
ORDER BY emp_last_name;
Last Name First Name Gender
--------------- --------------- ------
Joyner Suzanne F
Markis Marcia F
Prescott Sherri F
Zhu Waiman M
Department of Information Technology 6Data base Technologies (ITB4201)
NOT OPERATOR
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_dpt_number "Dept"
FROM employee
WHERE NOT emp_dpt_number = 7
ORDER BY emp_last_name;
Last Name First Name Dept
--------------- --------------- -----
Amin Hyder 3
Bordoloi Bijoy 1
Joyner Suzanne 3
Markis Marcia 3
Department of Information Technology 7Data base Technologies (ITB4201)
Combining OR and AND Operators
• When the AND operator is combined with OR,
the Oracle server will evaluate the condition
connected by the AND first before any
conditions connected with OR.
• Parenthesis must be used to force an order of
operation.
Department of Information Technology 8Data base Technologies (ITB4201)
Combining OR and AND Operators
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_dpt_number "Dept", emp_gender "Gender"
FROM employee
WHERE emp_last_name > 'E' AND emp_gender = 'F‘
OR emp_dpt_number = 1
ORDER BY emp_last_name;
Last Name First Name Dept Gender
--------------- -------------- ----- ------
Bordoloi Bijoy 1 M
Joyner Suzanne 3 F
Markis Marcia 3 F
Prescott Sherri 7 F
Department of Information Technology 9Data base Technologies (ITB4201)
Combining OR and AND Operators
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_dpt_number "Dept", emp_gender "Gender"
FROM employee
WHERE emp_last_name > 'E' AND
(emp_gender = 'F' OR emp_dpt_number = 1)
ORDER BY emp_last_name;
Last Name First Name Dept Gender
--------------- --------------- ----- ------
Joyner Suzanne 3 F
Markis Marcia 3 F
Prescott Sherri 7 F
Department of Information Technology 10Data base Technologies (ITB4201)
LISTS (IN AND NOT IN)
• There are two operators that are designed for testing to determine if data stored
in a table column is either in or not in a list or set of values.
• These are the IN and NOT IN operators.
• These operators greatly simplify the task of writing queries that might otherwise
require a large number of either OR logical operators or an unwieldy use of the
NOT logical operator.
Department of Information Technology 11Data base Technologies (ITB4201)
Using IN Operator
SELECT emp_last_name "Last Name", emp_first_name "First
Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary = 43000 OR emp_salary = 30000 OR
emp_salary = 25000
ORDER BY emp_salary;
Last Name First Name Salary
--------------- --------------- -----------
Markis Marcia $25,000.00
Amin Hyder $25,000.00
Prescott Sherri $25,000.00
Bock Douglas $30,000.00
Joyner Suzanne $43,000.00
Zhu Waiman $43,000.00
6 rows selected.
Department of Information Technology 12Data base Technologies (ITB4201)
Using IN Operator
SELECT emp_last_name "Last Name", emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary IN (43000, 30000, 25000)
ORDER BY emp_salary;
Last Name First Name Salary
--------------- --------------- -----------
Markis Marcia $25,000.00
Amin Hyder $25,000.00
Prescott Sherri $25,000.00
Bock Douglas $30,000.00
Joyner Suzanne $43,000.00
Zhu Waiman $43,000.00
6 rows selected.
Department of Information Technology 13Data base Technologies (ITB4201)
Using IN Operator
SELECT emp_last_name "Last Name", emp_first_name "First
Name",
emp_city "City"
FROM employee
WHERE emp_city IN ('Marina', 'Edwardsville', 'St. Louis')
ORDER BY emp_city;
Last Name First Name City
--------------- --------------- -------------
Bordoloi Bijoy Edwardsville
Prescott Sherri Edwardsville
Joyner Suzanne Marina
Amin Hyder Marina
Zhu Waiman St. Louis
Bock Douglas St. Louis
Department of Information Technology 14Data base Technologies (ITB4201)
Using the NOT IN Operator
• NOT can precede IN to form negative.
• To get the list of employees who did not earn the
three salary figures listed above
SELECT emp_last_name "Last Name", emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary NOT IN (43000, 30000, 25000)
ORDER BY emp_salary;
Last Name First Name Salary
--------------- --------------- -----------
Joshi Dinesh $38,000.00
Bordoloi Bijoy $55,000.00
Department of Information Technology 15Data base Technologies (ITB4201)
RANGES (BETWEEN AND NOT BETWEEN)
• SQL provides two operators, BETWEEN and NOT BETWEEN that
can simply the range of values in a query.
• This eliminates the need to use a more complex WHERE clause
involving the use of the AND logical operator.
Department of Information Technology 16Data base Technologies (ITB4201)
Using the BETWEEN Operator
• The following query uses the AND logical operator.
SELECT emp_last_name "Last Name", emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary >= 25000 AND emp_salary <= 40000
ORDER BY emp_salary;
Last Name First Name Salary
-------------- --------------- -----------
Markis Marcia $25,000.00
Amin Hyder $25,000.00
Prescott Sherri $25,000.00
Bock Douglas $30,000.00
Joshi Dinesh $38,000.00
Department of Information Technology 17Data base Technologies (ITB4201)
Using the BETWEEN Operator
• The query can be rewritten using the BETWEEN
operator.
SELECT emp_last_name "Last Name", emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary BETWEEN 25000 AND 40000
ORDER BY emp_salary;
Last Name First Name Salary
--------------- --------------- -----------
Markis Marcia $25,000.00
Amin Hyder $25,000.00
Prescott Sherri $25,000.00
Bock Douglas $30,000.00
Joshi Dinesh $38,000.00
Department of Information Technology 18Data base Technologies (ITB4201)
Using the NOT BETWEEN Operator
SELECT emp_last_name "Last Name", emp_salary "Salary"
FROM employee
WHERE emp_salary NOT BETWEEN 28000 AND 50000
ORDER BY emp_salary;
Last Name Salary
--------------- -----------
Markis $25,000.00
Amin $25,000.00
Prescott $25,000.00
Bordoloi $55,000.00
Department of Information Technology 19Data base Technologies (ITB4201)
LIKE AND NOT LIKE
• The LIKE and NOT LIKE operators can be used to
search for data rows containing incomplete or partial
character strings within a data column.
• The next query searches the employee table for
employee names that begin with the characters 'Bo'.
• The search is case-sensitive meaning that 'Bo' is not
equivalent to 'BO'.
Department of Information Technology 20Data base Technologies (ITB4201)
LIKE AND NOT LIKE
SELECT emp_last_name "Last Name", emp_first_name "First
Name"
FROM employee
WHERE emp_last_name LIKE 'Bo%';
Last Name First Name
------------- -------------
Bordoloi Bijoy
Bock Douglas
Department of Information Technology 21Data base Technologies (ITB4201)
LIKE AND NOT LIKE
Wild card Meaning
% (percent)any string of zero or more characters
_ (underscore) any single character
[ ] (brackets) any single character within a specified range such as 'a' to 'd', inclusive [a-d]
or a set of characters such as [aeiouy]
[^] (not brackets) any single character not in the specified range or set.(e.g., [^a-f] )
Oracle supports only the first two,
SQL Server and Sybase supports all four.
Department of Information Technology 22Data base Technologies (ITB4201)
MORE EXAMPLES
• LIKE '%inger' will search for every name that ends with 'inger' (Ringer,
Stringer).
• LIKE '%en%' will search for every name that has the letters 'en' in the
name (Bennet, Green, McBadden).
• LIKE '_heryl' will search for every six-letter name ending with 'heryl'
(Cheryl). Notice how this is different than '%heryl' which would return
names that are six characters or more.
Department of Information Technology 23Data base Technologies (ITB4201)
MORE EXAMPLES
• LIKE '[CK]ars[eo]n' will search for every six-letter name that
begins with a 'C' or 'K' and has the letter 'e' or 'o' between 'ars'
and 'n' (e.g., 'Carsen,' 'Karsen,' 'Carson,' and 'Karson'.
• LIKE '[M-Z]inger' will search for all the names ending with 'inger'
that begin with any single letter 'M' thru 'Z' (Ringer).
• LIKE 'M[^c]%' will search for all the names that begin with 'M'
not having 'c' as the second letter.
Department of Information Technology 24Data base Technologies (ITB4201)
MORE EXAMPLES
The SELECT statement shown below generates a result table that includes
all DISTINCT rows where the employee social security number in the
assignment table ends with the numbers 555.
SELECT DISTINCT work_emp_ssn "Emp SSN"
FROM assignment
WHERE work_emp_ssn LIKE '%555';
Emp SSN
------------
999555555
Department of Information Technology 25Data base Technologies (ITB4201)
UNKNOWN VALUES
(IS NULL AND IS NOT NULL)
• NULL value is not synonymous with "zero" (numerical values) or "blank"
(character values).
• NULL values allow users to distinguish between a deliberate entry of
zero/blank and a non-entry of data.
SELECT *
FROM assignment
WHERE work_hours IS NULL;
WORK_EMP_ WORK_PRO_NUMBER WORK_HOURS
--------- --------------- ----------
999444444 1
999666666 20
Department of Information Technology 26Data base Technologies (ITB4201)
MORE EXAMPLES
SELECT *
FROM assignment
WHERE work_hours = 0;
no rows selected
• The query did not return a result table because none of the rows in the
assignment table have a zero value for work_hours. Thus, you can see
that zero (0) is a value, not an "unknown value."
Department of Information Technology 27Data base Technologies (ITB4201)
MORE EXAMPLES
• The NOT NULL condition can also be tested.
SELECT *
FROM assignment
WHERE work_hours IS NOT NULL;
15 rows selected.
• The result table contains all the rows where work_hours column
contains a value.
Department of Information Technology 28Data base Technologies (ITB4201)
EXPRESSIONS IN SELECT CLAUSES
• An expression is formed by combining a column name or constant with an
arithmetic operator.
• The arithmetic operators used in SQL are
SYMBOL OPERATION ORDER
* Multiplication 1
/ Division 1
% Modulo 1
+ Addition 2
- Subtraction 2
Department of Information Technology 29Data base Technologies (ITB4201)
MORE EXAMPLES
SELECT emp_last_name "Last Name", emp_first_name "First
Name",
emp_salary/12 "Monthly Salary"
FROM employee
WHERE emp_salary/12 > 3500
ORDER BY emp_last_name;
Last Name First Name Monthly Salary
--------------- --------------- --------------
Bordoloi Bijoy $4,583.33
Joyner Suzanne $3,583.33
Zhu Waiman $3,583.33
Department of Information Technology 30Data base Technologies (ITB4201)
EXPRESSIONS
• When expression is used in select with a column name it has no effect on
the table’s underlying values.
• The data contained in each column must be defined as int, smallint,
tinyint, float, money, and smallmoney.
• The result of an arithmetic operation on NULL is NULL.
Department of Information Technology 31Data base Technologies (ITB4201)
Examples of Operations on Nulls
Table: Compensation
EMP# JOBCODE SALARY COMMISSION
E10 SALES 12500 32090
E11 NULL 25000 8000
E12 SALES 44000 0
E13 SALES 44000 NULL
E14 PROG 19500 NULL
E15 CLERK NULL NULL
Department of Information Technology 32Data base Technologies (ITB4201)
Examples of Operations on Nulls
List the employees whose total earnings exceed $30000.00.
SELECTEMP#
FROM COMPENSATION
WHERE JOBCODE = “SALES”
AND (SALARY + COMMISSION) > 30000
EMP#
E10
E12
E13 is missing because?
Department of Information Technology 33Data base Technologies (ITB4201)
ORDER BY
• The ORDER BY clause sorts the
results of a query
– You can sort in ascending (default) or
descending order
– Multiple columns can be given
– You cannot order by a column which isn’t in
the result
SELECT <columns>
FROM <tables>
WHERE <condition>
ORDER BY <cols>
[ASCENDING |
DESCENDING|
ASC | DESC ]
Department of Information Technology 34Data base Technologies (ITB4201)
ORDER BY Example
Grades
Name Code Mark
John DBS 56
John IAI 72
Mary DBS 60
Mark PR1 43
Mark PR2 35
Jane IAI 54
Name Code Mark
Mark PR2 35
Mark PR1 43
Jane IAI 54
John DBS 56
Mary DBS 60
John IAI 72
SELECT * FROM Grades
ORDER BY Mark
Department of Information Technology 35Data base Technologies (ITB4201)
ORDER BY Example
Grades
Name Code Mark
John DBS 56
John IAI 72
Mary DBS 60
Mark PR1 43
Mark PR2 35
Jane IAI 54
Name Code Mark
Mary DBS 60
John DBS 56
John IAI 72
Jane IAI 54
Mark PR1 43
Mark PR2 35
SELECT * FROM Grades
ORDER BY Code ASC,
Mark DESC
Department of Information Technology 36Data base Technologies (ITB4201)
Constants and Arithmetic
• As well as column names, you can
select constants, compute arithmetic
expressions and evaluate functions in
a SELECT statement
SELECT Mark/100
FROM Grades
SELECT
Salary + Bonus
FROM Employee
SELECT 1.175*Price
FROM Products
Department of Information Technology 37Data base Technologies (ITB4201)
Aggregate Functions
• Aggregate functions compute
summaries of data in a table
– Most aggregate functions (all except
COUNT) work on a single column of
numeric data
– Use an alias to name the result
• Aggregate functions
– COUNT: The number of rows
– SUM: The sum of the entries in a column
– AVG: The average entry in a column
– MIN, MAX: The minimum and maximum
entries in a column
Department of Information Technology 38Data base Technologies (ITB4201)
Aggregate Functions
Grades
Name Code Mark
John DBS 56
John IAI 72
Mary DBS 60
Mark PR1 43
Mark PR2 35
Jane IAI 54
SELECT
COUNT(*) AS Count
FROM Grades
SELECT
SUM(Mark) AS Total
FROM Grades
SELECT
MAX(Mark) AS Best
FROM Grades
Count
6
Total
320
Best
72
Department of Information Technology 39Data base Technologies (ITB4201)
Aggregate Functions
• You can combine aggregate
functions using arithmetic
SELECT
MAX(Mark)-MIN(Mark)
AS Range
FROM Grades
Grades
Name Code Mark
John DBS 56
John IAI 72
Mary DBS 60
Mark PR1 43
Mark PR2 35
Jane IAI 54
Range
37
MAX(Mark) = 72
MIN(Mark) = 35
Department of Information Technology 40Data base Technologies (ITB4201)
Example
• Find John’s average mark, weighted by
the credits of each moduleModules
Code Title Credits
DBS Database Sys. 10
GRP Group Project 20
PRG Programming 10
Grades
Name Code Mark
John DBS 60
Mark GRP 47
Mary PRG 56
SELECT
SUM(Mark*Credits)/SUM(Credits)
FROM Modules, Grades
WHERE Modules.Code=Grades.Code
AND Grades.Name = ‘John’
Department of Information Technology 41Data base Technologies (ITB4201)
GROUP BY
• Sometimes we want to apply
aggregate functions to groups of rows
• Example, find the average mark of
each student
• The GROUP BY clause does this
SELECT <cols1>
FROM <tables>
GROUP BY <cols2>
Department of Information Technology 42Data base Technologies (ITB4201)
GROUP BY
SELECT <cols1>
FROM <tables>
GROUP BY <cols2>
• Every entry in <cols1> must be in
<cols2>, be a constant, or be an
aggregate function
• You can have WHERE or ORDER BY
clauses as well as a GROUP BY clause
Department of Information Technology 43Data base Technologies (ITB4201)
GROUP BY
Grades
Name Code Mark
John DBS 56
John IAI 72
Mary DBS 60
Mark PR1 43
Mark PR2 35
Jane IAI 54
SELECT Name,
AVG(Mark) AS Average
FROM Grades
GROUP BY Name
Name Average
John 64
Mary 60
Mark 39
Jane 54
Department of Information Technology 44Data base Technologies (ITB4201)
GROUP BY
• Find the total value of the sales for
each department in each month
– Can group by Month then Department or
Department then Month
– Same results, but in a different order
Month Department Value
March Fiction 20
March Travel 30
March Technical 40
April Fiction 10
April Fiction 30
April Travel 25
April Fiction 20
May Fiction 20
May Technical 50
Sales
Department of Information Technology 45Data base Technologies (ITB4201)
GROUP BY
Month Department Total
April Fiction 60
April Travel 25
March Fiction 20
March Technical 40
March Travel 30
May Fiction 20
May Technical 50
SELECT Month, Department,
SUM(Value) AS Total
FROM Sales
GROUP BY Month, Department
Month Department Total
April Fiction 60
March Fiction 20
May Fiction 20
March Technical 40
May Technical 50
April Travel 25
March Travel 30
SELECT Month, Department,
SUM(Value) AS Total
FROM Sales
GROUP BY Department, Month
Department of Information Technology 46Data base Technologies (ITB4201)
HAVING
• HAVING is like a WHERE clause, except
that it applies to the results of a
GROUP BY query
• It can be used to select groups which
satisfy a given condition
SELECT Name,
AVG(Mark) AS Average
FROM Grades
GROUP BY Name
HAVING AVG(Mark) >= 40
Name Average
John 64
Mary 60
Jane 54
Department of Information Technology 47Data base Technologies (ITB4201)
WHERE and HAVING
• WHERE refers to the rows of tables,
and so cannot use aggregate functions
• HAVING refers to the groups of rows,
and so cannot use columns which are
not in the GROUP BY
• Think of a query being processed as
follows:
• Tables are combined
• WHERE clauses
• GROUP BY and Aggregates
• Column selection
• HAVING clauses
• ORDER BY
Department of Information Technology 48Data base Technologies (ITB4201)
UNION, etc.
• UNION, INTERSECT, and EXCEPT
– These treat the tables as sets and are the
usual set operators of union, intersection,
and difference
– We’ll concentrate on UNION
– Oracle has MINUS instead of EXCEPT
• They all combine the results from two
select statements
• The results of the two selects must
have the same columns and data types
Department of Information Technology 49Data base Technologies (ITB4201)
UNION
• Find, in a single query, the average
mark for each student, and the
average mark overallGrades
Name Code Mark
Jane IAI 52
John DBS 56
John IAI 72
Mark PR1 43
Mark PR2 35
Mary DBS 60
Department of Information Technology 50Data base Technologies (ITB4201)
UNION
• The average for each
student:
SELECT Name,
AVG(Mark) AS Average
FROM Grades
GROUP BY Name
• The average overall
SELECT
‘Total’ AS Name,
AVG(Mark) AS Average
FROM Grades
• Note - this has the same
columns as the average by
student
Department of Information Technology 51Data base Technologies (ITB4201)
UNION
SELECT Name
AVG(Mark) AS Average
FROM Grades
GROUP BY Name
UNION
SELECT
'Total' as Name,
AVG(Mark) AS Average
FROM Grades
Name Average
Jane 52
John 64
Mark 39
Mary 60
Total 53
Department of Information Technology 52Data base Technologies (ITB4201)
Tables for the Example
Student
ID First Last Year
Module
Code Title Credits
Grade
ID Code Mark YearTaken
Department of Information Technology 53Data base Technologies (ITB4201)
We’ll Need a UNION
• Finalists are treated differently
– Write one query for the finalists
– Write a second query for the first and
second years
– Use a UNION to join them together
<QUERY FOR FINALISTS>
UNION
<QUERY FOR OTHERS>
Department of Information Technology 54Data base Technologies (ITB4201)
We’ll need to Join the Tables
• Both of the subqueries need
information from all the tables
– The student ID, name and year
– The marks for each module and the year
taken
– The number of credits for each module
• This is a natural join operation
– We could use a NATURAL JOIN statement,
and hope that our version of SQL can do it
– Safer to just use a WHERE clause
Department of Information Technology 55Data base Technologies (ITB4201)
The Query So Far
SELECT <some information>
FROM Student, Module, Grade
WHERE Student.ID = Grade.ID
AND Module.Code = Grade.Code
AND <student is in third year>
UNION
SELECT <some information>
FROM Student, Module, Grade
WHERE Student.ID = Grade.ID
AND Module.Code = Grade.Code
AND <student is in first or second year>
Department of Information Technology 56Data base Technologies (ITB4201)
Information for Finalists
•We need to retrieve
– Compute average mark, weighted 40-60
across years 2 and 3
– First year marks need to be ignored
– The ID, Name, and Year are needed as they
are used for ordering
• The average is hard
– We don’t have any statement to separate
years 2 and 3 easily
– We can exploit the fact that 40 = 20*2 and
60 = 20*3, so YearTaken and the weighting
have a simple relationship
Department of Information Technology 57Data base Technologies (ITB4201)
Information for Finalists
SELECT Year, Student.ID, Last, First,
SUM((20*YearTaken/100)*Mark*Credits)/120
AS AverageMark
FROM Student, Module, Grade
WHERE Student.ID = Grade.ID
AND Module.Code = Grade.Code
AND YearTaken IN (2,3)
AND Year = 3
GROUP BY Year, Student.ID, First, Last
Department of Information Technology 58Data base Technologies (ITB4201)
Information for Other Students
• Other students are easier than finalists
– We just need to average their marks where YearTaken and Year are
the same
– As before we need the ID, Name, and Year for ordering
Department of Information Technology 59Data base Technologies (ITB4201)
Information for Other Students
SELECT Year, Student.ID, Last, First,
SUM(Mark*Credits)/120 AS AverageMark
FROM Student, Module, Grade
WHERE Student.ID = Grade.ID
AND Module.Code = Grade.Code
AND YearTaken = Year
AND Year IN (1,2)
GROUP BY Year, Student.ID, First, Last
Department of Information Technology 60Data base Technologies (ITB4201)
The Final Query
SELECT Year, Student.ID, Last, First,
SUM((20*YearTaken/100)*Mark*Credits)/120 AS AverageMark
FROM Student, Module, Grade
WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code
AND YearTaken IN (2,3) AND Year = 3
GROUP BY Year, Student.ID, First, Last
UNION
SELECT Year, Student.ID, Last, First,
SUM(Mark*Credits)/120 AS AverageMark
FROM Student, Module, Grade
WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code
AND YearTaken = Year AND Year IN (1,2)
GROUP BY Year, Student.ID, First, Last
ORDER BY Year desc, AverageMark desc, First, Last, ID
Department of Information Technology 61Data base Technologies (ITB4201)
Tutorial https://www.techonthenet.com/sql/select.php

More Related Content

What's hot

SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3Mohd Tousif
 
database language ppt.pptx
database language ppt.pptxdatabase language ppt.pptx
database language ppt.pptxAnusha sivakumar
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answersMichael Belete
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statementsVivek Singh
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQLEDB
 

What's hot (20)

SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
database language ppt.pptx
database language ppt.pptxdatabase language ppt.pptx
database language ppt.pptx
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answers
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Sql operator
Sql operatorSql operator
Sql operator
 
Triggers
TriggersTriggers
Triggers
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
set operators.pptx
set operators.pptxset operators.pptx
set operators.pptx
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statements
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
 
Sequences and indexes
Sequences and indexesSequences and indexes
Sequences and indexes
 

Similar to SQL logical operators

Similar to SQL logical operators (20)

Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.ppt
 
How did i steal your database CSCamp2011
How did i steal your database CSCamp2011How did i steal your database CSCamp2011
How did i steal your database CSCamp2011
 
Oracle examples
Oracle examplesOracle examples
Oracle examples
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
SQL query Demo
SQL query DemoSQL query Demo
SQL query Demo
 
Sql
SqlSql
Sql
 
Melbourne Groundbreakers Tour - Upgrading without risk
Melbourne Groundbreakers Tour - Upgrading without riskMelbourne Groundbreakers Tour - Upgrading without risk
Melbourne Groundbreakers Tour - Upgrading without risk
 
Sangam 18 - The New Optimizer in Oracle 12c
Sangam 18 - The New Optimizer in Oracle 12cSangam 18 - The New Optimizer in Oracle 12c
Sangam 18 - The New Optimizer in Oracle 12c
 
Sql intro
Sql introSql intro
Sql intro
 
OHarmony - How the Optimiser works
OHarmony - How the Optimiser worksOHarmony - How the Optimiser works
OHarmony - How the Optimiser works
 
SQL-examples.ppt
SQL-examples.pptSQL-examples.ppt
SQL-examples.ppt
 
SQL-examples.ppt
SQL-examples.pptSQL-examples.ppt
SQL-examples.ppt
 
SQL-examples.ppt
SQL-examples.pptSQL-examples.ppt
SQL-examples.ppt
 
Introduction to mysql part 2
Introduction to mysql part 2Introduction to mysql part 2
Introduction to mysql part 2
 
Ravi querys 425
Ravi querys  425Ravi querys  425
Ravi querys 425
 
Les02
Les02Les02
Les02
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
 
Les02.ppt
Les02.pptLes02.ppt
Les02.ppt
 

More from Dr. C.V. Suresh Babu (20)

Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
 
Association rules
Association rulesAssociation rules
Association rules
 
Clustering
ClusteringClustering
Clustering
 
Classification
ClassificationClassification
Classification
 
Blue property assumptions.
Blue property assumptions.Blue property assumptions.
Blue property assumptions.
 
Introduction to regression
Introduction to regressionIntroduction to regression
Introduction to regression
 
DART
DARTDART
DART
 
Mycin
MycinMycin
Mycin
 
Expert systems
Expert systemsExpert systems
Expert systems
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
 
Bayes network
Bayes networkBayes network
Bayes network
 
Bayes' theorem
Bayes' theoremBayes' theorem
Bayes' theorem
 
Knowledge based agents
Knowledge based agentsKnowledge based agents
Knowledge based agents
 
Rule based system
Rule based systemRule based system
Rule based system
 
Formal Logic in AI
Formal Logic in AIFormal Logic in AI
Formal Logic in AI
 
Production based system
Production based systemProduction based system
Production based system
 
Game playing in AI
Game playing in AIGame playing in AI
Game playing in AI
 
Diagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDiagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AI
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 

Recently uploaded

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 

Recently uploaded (20)

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 

SQL logical operators

  • 1. Department of Information Technology 1Data base Technologies (ITB4201) Structured Query Language Logical Operators Dr. C.V. Suresh Babu Professor Department of IT Hindustan Institute of Science & Technology
  • 2. Department of Information Technology 2Data base Technologies (ITB4201) Action Plan • Logical Operators • LISTS (IN AND NOT IN) • RANGES (BETWEEN AND NOT BETWEEN) • ORDER BY • Aggregate functions • GROUP BY and HAVING • UNION
  • 3. Department of Information Technology 3Data base Technologies (ITB4201) LOGICAL OPERATORS (AND, OR, AND NOT) • AND : Joins two or more conditions, and returns results only when all of the conditions are true. • OR : Joins two or more conditions, and returns results when any of the conditions are true. • NOT : Negates the expression that follows it.
  • 4. Department of Information Technology 4Data base Technologies (ITB4201) AND OPERATOR SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_gender "Gender" FROM employee WHERE emp_gender = 'F' AND emp_last_name > ‘E' ORDER BY emp_last_name; Last Name First Name Gender ---------- ------------- ------ Joyner Suzanne F Markis Marcia F Prescott Sherri F
  • 5. Department of Information Technology 5Data base Technologies (ITB4201) OR OPERATOR SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_gender "Gender" FROM employee WHERE emp_gender = 'F' OR emp_last_name > 'M' ORDER BY emp_last_name; Last Name First Name Gender --------------- --------------- ------ Joyner Suzanne F Markis Marcia F Prescott Sherri F Zhu Waiman M
  • 6. Department of Information Technology 6Data base Technologies (ITB4201) NOT OPERATOR SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_dpt_number "Dept" FROM employee WHERE NOT emp_dpt_number = 7 ORDER BY emp_last_name; Last Name First Name Dept --------------- --------------- ----- Amin Hyder 3 Bordoloi Bijoy 1 Joyner Suzanne 3 Markis Marcia 3
  • 7. Department of Information Technology 7Data base Technologies (ITB4201) Combining OR and AND Operators • When the AND operator is combined with OR, the Oracle server will evaluate the condition connected by the AND first before any conditions connected with OR. • Parenthesis must be used to force an order of operation.
  • 8. Department of Information Technology 8Data base Technologies (ITB4201) Combining OR and AND Operators SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_dpt_number "Dept", emp_gender "Gender" FROM employee WHERE emp_last_name > 'E' AND emp_gender = 'F‘ OR emp_dpt_number = 1 ORDER BY emp_last_name; Last Name First Name Dept Gender --------------- -------------- ----- ------ Bordoloi Bijoy 1 M Joyner Suzanne 3 F Markis Marcia 3 F Prescott Sherri 7 F
  • 9. Department of Information Technology 9Data base Technologies (ITB4201) Combining OR and AND Operators SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_dpt_number "Dept", emp_gender "Gender" FROM employee WHERE emp_last_name > 'E' AND (emp_gender = 'F' OR emp_dpt_number = 1) ORDER BY emp_last_name; Last Name First Name Dept Gender --------------- --------------- ----- ------ Joyner Suzanne 3 F Markis Marcia 3 F Prescott Sherri 7 F
  • 10. Department of Information Technology 10Data base Technologies (ITB4201) LISTS (IN AND NOT IN) • There are two operators that are designed for testing to determine if data stored in a table column is either in or not in a list or set of values. • These are the IN and NOT IN operators. • These operators greatly simplify the task of writing queries that might otherwise require a large number of either OR logical operators or an unwieldy use of the NOT logical operator.
  • 11. Department of Information Technology 11Data base Technologies (ITB4201) Using IN Operator SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_salary "Salary" FROM employee WHERE emp_salary = 43000 OR emp_salary = 30000 OR emp_salary = 25000 ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ----------- Markis Marcia $25,000.00 Amin Hyder $25,000.00 Prescott Sherri $25,000.00 Bock Douglas $30,000.00 Joyner Suzanne $43,000.00 Zhu Waiman $43,000.00 6 rows selected.
  • 12. Department of Information Technology 12Data base Technologies (ITB4201) Using IN Operator SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_salary "Salary" FROM employee WHERE emp_salary IN (43000, 30000, 25000) ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ----------- Markis Marcia $25,000.00 Amin Hyder $25,000.00 Prescott Sherri $25,000.00 Bock Douglas $30,000.00 Joyner Suzanne $43,000.00 Zhu Waiman $43,000.00 6 rows selected.
  • 13. Department of Information Technology 13Data base Technologies (ITB4201) Using IN Operator SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_city "City" FROM employee WHERE emp_city IN ('Marina', 'Edwardsville', 'St. Louis') ORDER BY emp_city; Last Name First Name City --------------- --------------- ------------- Bordoloi Bijoy Edwardsville Prescott Sherri Edwardsville Joyner Suzanne Marina Amin Hyder Marina Zhu Waiman St. Louis Bock Douglas St. Louis
  • 14. Department of Information Technology 14Data base Technologies (ITB4201) Using the NOT IN Operator • NOT can precede IN to form negative. • To get the list of employees who did not earn the three salary figures listed above SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_salary "Salary" FROM employee WHERE emp_salary NOT IN (43000, 30000, 25000) ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ----------- Joshi Dinesh $38,000.00 Bordoloi Bijoy $55,000.00
  • 15. Department of Information Technology 15Data base Technologies (ITB4201) RANGES (BETWEEN AND NOT BETWEEN) • SQL provides two operators, BETWEEN and NOT BETWEEN that can simply the range of values in a query. • This eliminates the need to use a more complex WHERE clause involving the use of the AND logical operator.
  • 16. Department of Information Technology 16Data base Technologies (ITB4201) Using the BETWEEN Operator • The following query uses the AND logical operator. SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_salary "Salary" FROM employee WHERE emp_salary >= 25000 AND emp_salary <= 40000 ORDER BY emp_salary; Last Name First Name Salary -------------- --------------- ----------- Markis Marcia $25,000.00 Amin Hyder $25,000.00 Prescott Sherri $25,000.00 Bock Douglas $30,000.00 Joshi Dinesh $38,000.00
  • 17. Department of Information Technology 17Data base Technologies (ITB4201) Using the BETWEEN Operator • The query can be rewritten using the BETWEEN operator. SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_salary "Salary" FROM employee WHERE emp_salary BETWEEN 25000 AND 40000 ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ----------- Markis Marcia $25,000.00 Amin Hyder $25,000.00 Prescott Sherri $25,000.00 Bock Douglas $30,000.00 Joshi Dinesh $38,000.00
  • 18. Department of Information Technology 18Data base Technologies (ITB4201) Using the NOT BETWEEN Operator SELECT emp_last_name "Last Name", emp_salary "Salary" FROM employee WHERE emp_salary NOT BETWEEN 28000 AND 50000 ORDER BY emp_salary; Last Name Salary --------------- ----------- Markis $25,000.00 Amin $25,000.00 Prescott $25,000.00 Bordoloi $55,000.00
  • 19. Department of Information Technology 19Data base Technologies (ITB4201) LIKE AND NOT LIKE • The LIKE and NOT LIKE operators can be used to search for data rows containing incomplete or partial character strings within a data column. • The next query searches the employee table for employee names that begin with the characters 'Bo'. • The search is case-sensitive meaning that 'Bo' is not equivalent to 'BO'.
  • 20. Department of Information Technology 20Data base Technologies (ITB4201) LIKE AND NOT LIKE SELECT emp_last_name "Last Name", emp_first_name "First Name" FROM employee WHERE emp_last_name LIKE 'Bo%'; Last Name First Name ------------- ------------- Bordoloi Bijoy Bock Douglas
  • 21. Department of Information Technology 21Data base Technologies (ITB4201) LIKE AND NOT LIKE Wild card Meaning % (percent)any string of zero or more characters _ (underscore) any single character [ ] (brackets) any single character within a specified range such as 'a' to 'd', inclusive [a-d] or a set of characters such as [aeiouy] [^] (not brackets) any single character not in the specified range or set.(e.g., [^a-f] ) Oracle supports only the first two, SQL Server and Sybase supports all four.
  • 22. Department of Information Technology 22Data base Technologies (ITB4201) MORE EXAMPLES • LIKE '%inger' will search for every name that ends with 'inger' (Ringer, Stringer). • LIKE '%en%' will search for every name that has the letters 'en' in the name (Bennet, Green, McBadden). • LIKE '_heryl' will search for every six-letter name ending with 'heryl' (Cheryl). Notice how this is different than '%heryl' which would return names that are six characters or more.
  • 23. Department of Information Technology 23Data base Technologies (ITB4201) MORE EXAMPLES • LIKE '[CK]ars[eo]n' will search for every six-letter name that begins with a 'C' or 'K' and has the letter 'e' or 'o' between 'ars' and 'n' (e.g., 'Carsen,' 'Karsen,' 'Carson,' and 'Karson'. • LIKE '[M-Z]inger' will search for all the names ending with 'inger' that begin with any single letter 'M' thru 'Z' (Ringer). • LIKE 'M[^c]%' will search for all the names that begin with 'M' not having 'c' as the second letter.
  • 24. Department of Information Technology 24Data base Technologies (ITB4201) MORE EXAMPLES The SELECT statement shown below generates a result table that includes all DISTINCT rows where the employee social security number in the assignment table ends with the numbers 555. SELECT DISTINCT work_emp_ssn "Emp SSN" FROM assignment WHERE work_emp_ssn LIKE '%555'; Emp SSN ------------ 999555555
  • 25. Department of Information Technology 25Data base Technologies (ITB4201) UNKNOWN VALUES (IS NULL AND IS NOT NULL) • NULL value is not synonymous with "zero" (numerical values) or "blank" (character values). • NULL values allow users to distinguish between a deliberate entry of zero/blank and a non-entry of data. SELECT * FROM assignment WHERE work_hours IS NULL; WORK_EMP_ WORK_PRO_NUMBER WORK_HOURS --------- --------------- ---------- 999444444 1 999666666 20
  • 26. Department of Information Technology 26Data base Technologies (ITB4201) MORE EXAMPLES SELECT * FROM assignment WHERE work_hours = 0; no rows selected • The query did not return a result table because none of the rows in the assignment table have a zero value for work_hours. Thus, you can see that zero (0) is a value, not an "unknown value."
  • 27. Department of Information Technology 27Data base Technologies (ITB4201) MORE EXAMPLES • The NOT NULL condition can also be tested. SELECT * FROM assignment WHERE work_hours IS NOT NULL; 15 rows selected. • The result table contains all the rows where work_hours column contains a value.
  • 28. Department of Information Technology 28Data base Technologies (ITB4201) EXPRESSIONS IN SELECT CLAUSES • An expression is formed by combining a column name or constant with an arithmetic operator. • The arithmetic operators used in SQL are SYMBOL OPERATION ORDER * Multiplication 1 / Division 1 % Modulo 1 + Addition 2 - Subtraction 2
  • 29. Department of Information Technology 29Data base Technologies (ITB4201) MORE EXAMPLES SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_salary/12 "Monthly Salary" FROM employee WHERE emp_salary/12 > 3500 ORDER BY emp_last_name; Last Name First Name Monthly Salary --------------- --------------- -------------- Bordoloi Bijoy $4,583.33 Joyner Suzanne $3,583.33 Zhu Waiman $3,583.33
  • 30. Department of Information Technology 30Data base Technologies (ITB4201) EXPRESSIONS • When expression is used in select with a column name it has no effect on the table’s underlying values. • The data contained in each column must be defined as int, smallint, tinyint, float, money, and smallmoney. • The result of an arithmetic operation on NULL is NULL.
  • 31. Department of Information Technology 31Data base Technologies (ITB4201) Examples of Operations on Nulls Table: Compensation EMP# JOBCODE SALARY COMMISSION E10 SALES 12500 32090 E11 NULL 25000 8000 E12 SALES 44000 0 E13 SALES 44000 NULL E14 PROG 19500 NULL E15 CLERK NULL NULL
  • 32. Department of Information Technology 32Data base Technologies (ITB4201) Examples of Operations on Nulls List the employees whose total earnings exceed $30000.00. SELECTEMP# FROM COMPENSATION WHERE JOBCODE = “SALES” AND (SALARY + COMMISSION) > 30000 EMP# E10 E12 E13 is missing because?
  • 33. Department of Information Technology 33Data base Technologies (ITB4201) ORDER BY • The ORDER BY clause sorts the results of a query – You can sort in ascending (default) or descending order – Multiple columns can be given – You cannot order by a column which isn’t in the result SELECT <columns> FROM <tables> WHERE <condition> ORDER BY <cols> [ASCENDING | DESCENDING| ASC | DESC ]
  • 34. Department of Information Technology 34Data base Technologies (ITB4201) ORDER BY Example Grades Name Code Mark John DBS 56 John IAI 72 Mary DBS 60 Mark PR1 43 Mark PR2 35 Jane IAI 54 Name Code Mark Mark PR2 35 Mark PR1 43 Jane IAI 54 John DBS 56 Mary DBS 60 John IAI 72 SELECT * FROM Grades ORDER BY Mark
  • 35. Department of Information Technology 35Data base Technologies (ITB4201) ORDER BY Example Grades Name Code Mark John DBS 56 John IAI 72 Mary DBS 60 Mark PR1 43 Mark PR2 35 Jane IAI 54 Name Code Mark Mary DBS 60 John DBS 56 John IAI 72 Jane IAI 54 Mark PR1 43 Mark PR2 35 SELECT * FROM Grades ORDER BY Code ASC, Mark DESC
  • 36. Department of Information Technology 36Data base Technologies (ITB4201) Constants and Arithmetic • As well as column names, you can select constants, compute arithmetic expressions and evaluate functions in a SELECT statement SELECT Mark/100 FROM Grades SELECT Salary + Bonus FROM Employee SELECT 1.175*Price FROM Products
  • 37. Department of Information Technology 37Data base Technologies (ITB4201) Aggregate Functions • Aggregate functions compute summaries of data in a table – Most aggregate functions (all except COUNT) work on a single column of numeric data – Use an alias to name the result • Aggregate functions – COUNT: The number of rows – SUM: The sum of the entries in a column – AVG: The average entry in a column – MIN, MAX: The minimum and maximum entries in a column
  • 38. Department of Information Technology 38Data base Technologies (ITB4201) Aggregate Functions Grades Name Code Mark John DBS 56 John IAI 72 Mary DBS 60 Mark PR1 43 Mark PR2 35 Jane IAI 54 SELECT COUNT(*) AS Count FROM Grades SELECT SUM(Mark) AS Total FROM Grades SELECT MAX(Mark) AS Best FROM Grades Count 6 Total 320 Best 72
  • 39. Department of Information Technology 39Data base Technologies (ITB4201) Aggregate Functions • You can combine aggregate functions using arithmetic SELECT MAX(Mark)-MIN(Mark) AS Range FROM Grades Grades Name Code Mark John DBS 56 John IAI 72 Mary DBS 60 Mark PR1 43 Mark PR2 35 Jane IAI 54 Range 37 MAX(Mark) = 72 MIN(Mark) = 35
  • 40. Department of Information Technology 40Data base Technologies (ITB4201) Example • Find John’s average mark, weighted by the credits of each moduleModules Code Title Credits DBS Database Sys. 10 GRP Group Project 20 PRG Programming 10 Grades Name Code Mark John DBS 60 Mark GRP 47 Mary PRG 56 SELECT SUM(Mark*Credits)/SUM(Credits) FROM Modules, Grades WHERE Modules.Code=Grades.Code AND Grades.Name = ‘John’
  • 41. Department of Information Technology 41Data base Technologies (ITB4201) GROUP BY • Sometimes we want to apply aggregate functions to groups of rows • Example, find the average mark of each student • The GROUP BY clause does this SELECT <cols1> FROM <tables> GROUP BY <cols2>
  • 42. Department of Information Technology 42Data base Technologies (ITB4201) GROUP BY SELECT <cols1> FROM <tables> GROUP BY <cols2> • Every entry in <cols1> must be in <cols2>, be a constant, or be an aggregate function • You can have WHERE or ORDER BY clauses as well as a GROUP BY clause
  • 43. Department of Information Technology 43Data base Technologies (ITB4201) GROUP BY Grades Name Code Mark John DBS 56 John IAI 72 Mary DBS 60 Mark PR1 43 Mark PR2 35 Jane IAI 54 SELECT Name, AVG(Mark) AS Average FROM Grades GROUP BY Name Name Average John 64 Mary 60 Mark 39 Jane 54
  • 44. Department of Information Technology 44Data base Technologies (ITB4201) GROUP BY • Find the total value of the sales for each department in each month – Can group by Month then Department or Department then Month – Same results, but in a different order Month Department Value March Fiction 20 March Travel 30 March Technical 40 April Fiction 10 April Fiction 30 April Travel 25 April Fiction 20 May Fiction 20 May Technical 50 Sales
  • 45. Department of Information Technology 45Data base Technologies (ITB4201) GROUP BY Month Department Total April Fiction 60 April Travel 25 March Fiction 20 March Technical 40 March Travel 30 May Fiction 20 May Technical 50 SELECT Month, Department, SUM(Value) AS Total FROM Sales GROUP BY Month, Department Month Department Total April Fiction 60 March Fiction 20 May Fiction 20 March Technical 40 May Technical 50 April Travel 25 March Travel 30 SELECT Month, Department, SUM(Value) AS Total FROM Sales GROUP BY Department, Month
  • 46. Department of Information Technology 46Data base Technologies (ITB4201) HAVING • HAVING is like a WHERE clause, except that it applies to the results of a GROUP BY query • It can be used to select groups which satisfy a given condition SELECT Name, AVG(Mark) AS Average FROM Grades GROUP BY Name HAVING AVG(Mark) >= 40 Name Average John 64 Mary 60 Jane 54
  • 47. Department of Information Technology 47Data base Technologies (ITB4201) WHERE and HAVING • WHERE refers to the rows of tables, and so cannot use aggregate functions • HAVING refers to the groups of rows, and so cannot use columns which are not in the GROUP BY • Think of a query being processed as follows: • Tables are combined • WHERE clauses • GROUP BY and Aggregates • Column selection • HAVING clauses • ORDER BY
  • 48. Department of Information Technology 48Data base Technologies (ITB4201) UNION, etc. • UNION, INTERSECT, and EXCEPT – These treat the tables as sets and are the usual set operators of union, intersection, and difference – We’ll concentrate on UNION – Oracle has MINUS instead of EXCEPT • They all combine the results from two select statements • The results of the two selects must have the same columns and data types
  • 49. Department of Information Technology 49Data base Technologies (ITB4201) UNION • Find, in a single query, the average mark for each student, and the average mark overallGrades Name Code Mark Jane IAI 52 John DBS 56 John IAI 72 Mark PR1 43 Mark PR2 35 Mary DBS 60
  • 50. Department of Information Technology 50Data base Technologies (ITB4201) UNION • The average for each student: SELECT Name, AVG(Mark) AS Average FROM Grades GROUP BY Name • The average overall SELECT ‘Total’ AS Name, AVG(Mark) AS Average FROM Grades • Note - this has the same columns as the average by student
  • 51. Department of Information Technology 51Data base Technologies (ITB4201) UNION SELECT Name AVG(Mark) AS Average FROM Grades GROUP BY Name UNION SELECT 'Total' as Name, AVG(Mark) AS Average FROM Grades Name Average Jane 52 John 64 Mark 39 Mary 60 Total 53
  • 52. Department of Information Technology 52Data base Technologies (ITB4201) Tables for the Example Student ID First Last Year Module Code Title Credits Grade ID Code Mark YearTaken
  • 53. Department of Information Technology 53Data base Technologies (ITB4201) We’ll Need a UNION • Finalists are treated differently – Write one query for the finalists – Write a second query for the first and second years – Use a UNION to join them together <QUERY FOR FINALISTS> UNION <QUERY FOR OTHERS>
  • 54. Department of Information Technology 54Data base Technologies (ITB4201) We’ll need to Join the Tables • Both of the subqueries need information from all the tables – The student ID, name and year – The marks for each module and the year taken – The number of credits for each module • This is a natural join operation – We could use a NATURAL JOIN statement, and hope that our version of SQL can do it – Safer to just use a WHERE clause
  • 55. Department of Information Technology 55Data base Technologies (ITB4201) The Query So Far SELECT <some information> FROM Student, Module, Grade WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code AND <student is in third year> UNION SELECT <some information> FROM Student, Module, Grade WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code AND <student is in first or second year>
  • 56. Department of Information Technology 56Data base Technologies (ITB4201) Information for Finalists •We need to retrieve – Compute average mark, weighted 40-60 across years 2 and 3 – First year marks need to be ignored – The ID, Name, and Year are needed as they are used for ordering • The average is hard – We don’t have any statement to separate years 2 and 3 easily – We can exploit the fact that 40 = 20*2 and 60 = 20*3, so YearTaken and the weighting have a simple relationship
  • 57. Department of Information Technology 57Data base Technologies (ITB4201) Information for Finalists SELECT Year, Student.ID, Last, First, SUM((20*YearTaken/100)*Mark*Credits)/120 AS AverageMark FROM Student, Module, Grade WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code AND YearTaken IN (2,3) AND Year = 3 GROUP BY Year, Student.ID, First, Last
  • 58. Department of Information Technology 58Data base Technologies (ITB4201) Information for Other Students • Other students are easier than finalists – We just need to average their marks where YearTaken and Year are the same – As before we need the ID, Name, and Year for ordering
  • 59. Department of Information Technology 59Data base Technologies (ITB4201) Information for Other Students SELECT Year, Student.ID, Last, First, SUM(Mark*Credits)/120 AS AverageMark FROM Student, Module, Grade WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code AND YearTaken = Year AND Year IN (1,2) GROUP BY Year, Student.ID, First, Last
  • 60. Department of Information Technology 60Data base Technologies (ITB4201) The Final Query SELECT Year, Student.ID, Last, First, SUM((20*YearTaken/100)*Mark*Credits)/120 AS AverageMark FROM Student, Module, Grade WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code AND YearTaken IN (2,3) AND Year = 3 GROUP BY Year, Student.ID, First, Last UNION SELECT Year, Student.ID, Last, First, SUM(Mark*Credits)/120 AS AverageMark FROM Student, Module, Grade WHERE Student.ID = Grade.ID AND Module.Code = Grade.Code AND YearTaken = Year AND Year IN (1,2) GROUP BY Year, Student.ID, First, Last ORDER BY Year desc, AverageMark desc, First, Last, ID
  • 61. Department of Information Technology 61Data base Technologies (ITB4201) Tutorial https://www.techonthenet.com/sql/select.php