Queries
This presentation is the property of its rightful owner.
Sponsored Links
1 / 44

Queries PowerPoint PPT Presentation


  • 139 Views
  • Uploaded on
  • Presentation posted in: General

Queries. SELECT [DISTINCT] <columnlist> FROM ( <table-list> {<alias>}| <joined table>),... [WHERE <condition>] [GROUP BY <grouping columns> [HAVING <group selection condition>]] [ORDER BY <column name> [<order>],...]. The Basic Query Block.

Download Presentation

Queries

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Queries

Queries

SELECT [DISTINCT] <columnlist>

FROM ( <table-list> {<alias>}|

<joined table>),...

[WHERE <condition>]

[GROUP BY <grouping columns>

[HAVING <group selection condition>]]

[ORDER BY <column name> [<order>],...]


The basic query block

The Basic Query Block

  • SELECT identifies what columns will be included (or displayed) in the query result

  • FROM identifies whichtable(s) to source rows

SELECT [DISTINCT] {*,column [alias],...}

FROMtable


Selecting all columns all rows

Selecting All Columns, All Rows

  • The simplest SELECT statement contains the following two clauses:

    • SELECT clause

      • Asterisk (*) indicates all columns

    • FROM clause

SELECT *

FROM sales_dept


Selecting specific columns

Selecting Specific Columns

  • List the columns in the SELECT clause.

  • Separate columns by using a comma.

  • Specify columns in the order you want them to appear.

SELECT dept_id, lname, manager_id

FROM sales_emp


Arithmetic expressions

Arithmetic Expressions

  • Create expressions on NUMBER and DATE data types by using operators.

    • Add+

    • Subtract-

    • Multiply*

    • Divide/

      e.g., Display the annual salary of employees:

SELECT lname, salary * 12, commission

FROM sales_emp


Column aliases

Column Aliases

  • A column alias renames a column heading.

  • Especially useful with calculations to provide a meaningful column name.

  • Immediately follows the column name in the SELECT clause.

    • Optional AS keyword between column name and alias.

  • Double quotation marks are required if an alias contains spaces, special characters, or is case-sensitive.


Column aliases1

Column Aliases

  • Optional AS keyword between column name and alias.

  • Double quotation marks are required if an alias contains spaces, special characters, or is case-sensitive.

SELECT lname lastname, salary,

12 * salary + 100

FROM sales_emp

SELECT lname AS lastname, salary,

12 * salary + 100 AS “new salary”

FROM sales_emp


Distinct option

DISTINCT Option

  • The default display of queries is all rows including duplicate rows.

  • Eliminate duplicate rows by using DISTINCT in the SELECT clause.

SELECT name

FROM sales_dept

SELECT DISTINCT name

FROM sales_dept


Distinct option1

DISTINCT Option

  • DISTINCT applies to all columns in the SELECT list.

  • When DISTINCT is applied to multiple columns, the result represents the distinct combination of the columns (that is, no two resulting rows will have the same values for all their columns).

SELECT DISTINCT dept_id, title

FROM sales_emp


Order by clause

ORDER BY Clause

  • Sort resulting rows with the ORDER BY clause.

    • ASC – ascending order, default.

    • DESC – descending order.

  • ORDER BY clause appears last in a SELECT statement.

SELECT lname, dept_id, dstart

FROM sales_emp

ORDER BY lname


Order by clause1

ORDER BY Clause

  • The default sort order is ascending.

  • Use DESC to reverse the sort order.

  • You can sort by expressions or aliases.

SELECT lname EMPLOYEE, dstart

FROM sales_emp

ORDER BY EMPLOYEE DESC

  • Null values are displayed

    • Last for ascending sequences.

    • First for descending sequences.


Order by clause2

ORDER BY Clause

  • You can order by position to save time.

SELECT lname, salary * 12

FROM sales_emp

ORDER BY 2

  • You can sort by multiple columns.

SELECT lname, dept_id, salary

FROM sales_emp

ORDER BY dept_id, salary DESC,

commission ASC

  • The order of ORDER BY list is order of sort.

  • You can sort by a column that is not in the SELECT list.


Where clause

WHERE Clause

  • Restrict the rows returned by the query using the WHERE clause.

  • Follows the FROM clause.

  • Conditions consist of the following:

    • Column name, expression, constant

    • Comparison operator

    • Literal

SELECT lname, dept_id, salary

FROM sales_emp

WHERE dept_id = 42


Where clause1

WHERE Clause

  • Character strings and dates are enclosed within single quotation marks.

  • Character values are case-sensitive.

  • The default date format is 'DD-MMM-YY'.

SELECT fname, lname, title

FROM sales_emp

WHERE lname = 'Magee'


Basic search conditions

R

Basic Search Conditions

  • Comparison. Compare the value of one expression to the value of another expression.

  • Range. Test whether the value of an expression falls within a specified range of values.

  • Set membership. Test whether the value of an expression equals one of a set of values.

  • Pattern match. Test whether a string matches a specified pattern.

  • Null. Test whether a column has a null (unknown) value.


Comparison search condition

R

Comparison Search Condition

  • Logical Comparison Operators

    = > >= < <=

  • SQL Comparison Operators

    • BETWEEN ... AND...

    • IN(list)

    • LIKE

    • IS NULL

  • Logical Operators

    • AND

    • OR

    • NOT


Comparison search condition1

R

Comparison Search Condition

  • Sometimes it is easier to exclude rows you know you do not want.

    • Logical Comparison Operators

      != <> ^=

    • Other SQL Operators

      • NOT BETWEEN

      • NOT IN

      • NOT LIKE

      • IS NOT NULL


Set membership search condition

Set Membership Search Condition

  • Use the [NOT] IN operator to test for values in a list.

SELECT id, name, region_id

FROM sales_dept

WHEREregion_id IN (1,3)


Pattern match search condition

Pattern Match Search Condition

  • Use the LIKE operator to perform wildcard searches of valid search string values.

  • Search conditions can contain either literal characters or numbers.

    • "%" denotes none or many characters.

    • "_" denotes one character.

SELECT lname

FROM sales_emp

WHERE lname LIKE 'M%'


Pattern match search condition1

Pattern Match Search Condition

  • The LIKE operator can be used as a shortcut for some BETWEEN comparisons.

  • Pattern matching characters can be combined.

SELECT lname, dstart

FROM sales_emp

WHERE dstart LIKE '%91'

SELECT lname

FROM sales_emp

WHERE lname LIKE '_a%'


Null search condition

NULL Search Condition

  • Use the IS [NOT] NULL operator to test for null values.

  • Do not use the = operator.

SELECT id, name, credit_rating

FROM aless_customer

WHERE salesrep_id IS NULL


Where clause and or

WHERE Clause: AND / OR

  • Use AND or OR operators to create complex conditions.

  • AND requires both conditions to be TRUE.

SELECT lname, salary, dept_id, title

FROM sales_emp

WHERE dept_id = 41 AND title = 'Clerk'

  • OR requires either condition to be TRUE.

SELECT lname, salary, dept_id, title

FROM sales_emp

WHERE dept_id = 41 OR title = 'Clerk'


Overview of functions in sql

Overview of Functions in SQL

Use functions to --

  • Perform calculations on data.

  • Modify individual data items.

  • Manipulate output for groups of rows.

  • Alter date formats for display.

  • Convert column data types.


Two types of sql functions

Two Types of SQL Functions

  • Single row functions

    • Character

    • Number

    • Date

    • Conversion

  • Multiple row functions

    • Group

FUNCTION

SINGLE

ROW

FUNCTION

MULTI

ROW


Single row functions

R

Single Row Functions

  • Manipulate data items.

  • Accept arguments and return one value.

  • Act on each row returned.

  • Return one result per row.

  • Modify the data type.

  • Can be nested.

function_name (column|expression,

[arg1, arg2,...])


Group multiple row functions

Group (Multiple Row) Functions

  • Also known as aggregate functions.

  • Operate on a single column of a set of rows in a table.

  • Return a single value (or a list of values, with one result for each group).

  • Can be nested.


Group functions

Group Functions

  • AVG (DISTINCT|ALL|n)

  • SUM (DISTINCT|ALL|n)

  • MAX (DISTINCT|ALL|expr)

  • MIN (DISTINCT|ALL|expr)

  • COUNT (DISTINCT|ALL|expr|*)


Group functions avg sum

Group Functions: AVG, SUM

  • Use AVG and SUM functions to return the average and sum, respectively, of values in a column.

  • Accept only numeric data types.

SELECT AVG(salary), SUM(salary)

FROM sales_emp

WHERE UPPER(title) LIKE 'SALES%'


Group functions max min

Group Functions: MAX, MIN

  • Use MAX and MIN functions to return the maximum and minimum, respectively, values for a given column.

  • Accept any data type as argument.

SELECT MIN(lname), MAX(lname)

FROM sales_emp

SELECT MIN(salary), MAX(salary)

FROM sales_emp

SELECT MIN(dstart), MAX(dstart)

FROM sales_emp


Group functions count

Group Functions: COUNT

  • COUNT(*) returns the number of rows, including nulls and duplicates.

SELECTCOUNT(*)

FROM sales_emp

WHEREdept_id = 31


Group functions count1

Group Functions: COUNT

  • COUNT(expression) returns the number of non-null rows.

  • The use of DISTINCT before the column name eliminates duplicates.

SELECTCOUNT(commission)

FROM sales_emp

WHEREdept_id = 31

SELECTCOUNT(DISTINCT commission)

FROM sales_emp

WHERE dept_id = 31


Group functions1

Group Functions

  • If the SELECT clause includes an aggregate function and no GROUP BY clause is used to group data together, then no item in the SELECT list can include any reference to a column unless that column is the argument to an aggregate function.

  • The following is an illegal SQL statement:

SELECTid, COUNT(commission)

FROM sales_emp


Without the group by clause

Without the GROUP BY Clause

SELECTid, lname, dept_id DEPARTMENT

FROM sales_emp

WHERE dept_id = 41

IDLAST_NAMEDEPARTMENT---------------------2Ngao416Urguhart4116Maduro4117Smith41

Department 41 is displayed four times because it appears as the department number of four employees.


With the group by clause

With the GROUP BY Clause

SELECT dept_id, COUNT(*) ”Number” FROM sales_empWHERE dept_id = 41GROUP BY dept_id

DEPT_ID Number ------- ------ 41 4

The GROUP BY clause displays one line of data for each department retrieved in the WHERE clause, and COUNT(*) displays the number of employees in each department (group) displayed.


Group by clause

GROUP BY Clause

  • List the number of customers in each credit rating.

SELECT credit_rating,

COUNT(*) AS "# Customers"

FROM sales_customer

GROUP BY credit_rating


Group by clause1

GROUP BY Clause

  • List all job titles and the total monthly salary for each job title.

SELECT title, SUM(salary) PAYROLL

FROM sales_emp

WHERE title NOT LIKE 'VP%'

GROUP BY title

ORDER BY SUM(salary)


Group by clause2

GROUP BY Clause

  • All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.

  • The GROUP BY column does not have to be in the SELECT clause.

SELECT title, MAX(salary)

FROM sales_emp

GROUP BY title


Group by clause3

GROUP BY Clause

  • Any expression in the SELECT list that is not a group function must be listed in the GROUP BY clause. Otherwise, an error message will be displayed

SELECT region_id, COUNT(name)

FROM sales_dept

ORA-00937: (region_id) not a single-

group group function


Group by clause4

GROUP BY Clause

  • Return summary results for groups and subgroups by listing more than one column in the GROUP BY clause.

  • Determine the default sort order of the results by the order of the columns in the GROUP BY clause.

SELECT dept_id, title, COUNT(*)

FROM sales_emp

GROUP BY dept_id, title


Group functions2

GROUP Functions

  • WHERE clause cannot be used to restrict groups. Use the HAVING clause.

SELECT dept_id, AVG(salary)

FROM sales_emp

WHERE AVG(salary) > 2000

GROUP BY dept_id

ORA-00934: group function is not

allowed here


Recall where clause

Recall: WHERE Clause

  • Used to select rows to be displayed.

SELECT lname, titleFROM sales_empWHERE lname LIKE ’V%’

Restrict Rows

LNAMETITLE--------------------------VelasquezPresident

Display a specific employee as restricted in the WHERE clause


Having clause

HAVING Clause

  • Used to restrict groups.

    • Step 1: Rows (that passed the WHERE condition) are grouped.

    • Step 2: The group function is applied to each of the groups.

    • Step 3: Groups matching the HAVING condition are displayed.

  • Column names used in the HAVING clause must also appear in the GROUP BY clause or be contained in the group functions.


Having clause1

HAVING Clause

SELECT title, TO_CHAR(12 * AVG(salary),

‘$99,999.99’) ”ANNUAL SALARY”,

COUNT(*) ”NUMBER OF EMPLOYEES”FROM sales_empGROUP BY title HAVING COUNT(*) > 2

TITLEANNUAL SALARYNUMBER OF EMPLOYEES-----------------------------------------------------Sales Representative$17,712.005Stock Clerk$11,388.0010Warehouse Manager$14,776.805

Display specific groups of job titles as restricted in the HAVING clause.


Having clause2

HAVING Clause

  • The GROUP BY clause can be used even without using a group function in the SELECT clause.

  • To restrict rows based on the result of a group function, use a GROUP BY clause and a HAVING clause.

SELECT dept_id

FROM sales_emp

GROUP BY dept_id

HAVING SUM(salary) > 4000


  • Login