SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]

Slides:



Advertisements
Similar presentations
Sometimes you need to use data from more than one table. In example1, the report displays data from two separate tables. Employee IDs exist in the EMPLOYEES.
Advertisements

Displaying Data from Multiple Tables. Objectives After completing this lesson, you should Be able to do the following: Write SELECT statements to accessWrite.
Copyright  Oracle Corporation, All rights reserved. 3 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: Write SELECT statements to access.
Chapter 4 JOINING TABLES & FUNCTION Lecture by Ty Rasmey
12-1 Copyright  Oracle Corporation, All rights reserved. What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Restricting and sorting data 16 May May May Created By Pantharee Sawasdimongkol.
Subqueries 11. Objectives After completing this lesson, you should be able to do the following: Describe the types of problems that subqueries can solve.
1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Copyright  Oracle Corporation, All rights reserved. 6 Subqueries.
After completing this lesson, you should be able to do the following: Limit the rows retrieved by a query Sort the rows retrieved by a query.
Writing Basic SQL statement 2 July July July Create By Pantharee Sawasdimongkol.
Session 3: SQL (B): Parts 3 & 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
Chapter 1 Writing Basic SQL Statements Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Logical Operators Operator AND OR NOT Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns.
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
Copyright  Oracle Corporation, All rights reserved. 1 Writing Basic SQL Statements.
4-1 Copyright  Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Dr. Philip Cannata 1 Programming Languages Prolog Part 3 SQL & Prolog.
Displaying Data from Multiple Tables (Join). EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS.
After completing this lesson, you should be able to do the following: List the capabilities of MySQL SELECT statements Execute a basic SELECT statement.
Subqueries.
Subqueries.
2 Writing Basic SELECT Statements. 1-2 Copyright  Oracle Corporation, All rights reserved. Capabilities of SQL SELECT Statements Selection Projection.
Copyright  Oracle Corporation, All rights reserved. Writing Basic SQL Statements.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
SELECT Statements Lecture Notes Sree Nilakanta Fall 2010 (rev)
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
RELATSIOONILISED ANDMEBAASID(alg) SQLi VÕIMALUSED.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
4 Displaying Data from Multiple Tables Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Copyright س Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
1 Writing Basic SQL Statements. 1-2 Objectives At the end of this lesson, you should be able to: List the capabilities of SQL SELECT statements Execute.
I-1 Copyright س Oracle Corporation, All rights reserved. Data Retrieval.
SQL: Part 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
An Introduction To SQL Part 2 (Special thanks to Geoff Leese)
1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Collection Operators These slides are.
2-1 Limiting Rows Using a Selection “…retrieve all employees in department 10” EMP EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER.
6 Subqueries. 6-2 Objectives At the end of this lesson, you should be able to: Describe the types of problems that subqueries can solve Define subqueries.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Collection Operators These slides are.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
1-1 Copyright  Oracle Corporation, All rights reserved. Logging In to SQL*Plus From Windows environment:From Windows environment: From command line:From.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Writing Basic SQL Statements. Objectives After completing this lesson, you should be able to do the following: –List the capabilities of SQL SELECT statements.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
Defining a Column Alias
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
Copyright  Oracle Corporation, All rights reserved. Introduction.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: –Write SELECT statements to access.
4 Displaying Data from Multiple Tables. 4-2 Objectives At the end of this lesson, you should be able to: Write SELECT statements to access data from more.
Copyright س Oracle Corporation, All rights reserved. 1 Writing Basic SQL Statements.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Enhanced Guide to Oracle 10g
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
(SQL) Displaying Data from Multiple Tables
Subqueries Schedule: Timing Topic 25 minutes Lecture
Restricting and Sorting Data
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

SQL- DQL (Oracle Version)

2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list] [HAVING conditional expression] [ORDER BY column_list] ;

3 The SELECT Statement  SELECT - List the columns (and expressions) that should be returned from the query  FROM - Indicate the table(s) or view(s) from which data will be obtained  WHERE - Indicate the conditions under which a row will be included in the result  GROUP BY - Indicate categorization of results  HAVING - Indicate the conditions under which a category (group) will be included  ORDER BY - Sorts the result according to specified criteria

4 SELECTcolumn1, column2, column3,... FROM table; SELECTcolumn1, column2, column3,... FROM table; The Basic SELECT Statement  SELECT identifies what columns  FROM identifies which table

5 DEPTNO LOC NEW YORK 20 DALLAS 30 CHICAGO 40 BOSTON SQL> SELECT deptno, loc 2 FROM dept; Example SELECT Statement

6 DEPTNO DNAME LOC ––––––––––––- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON SQL> SELECT * 2 FROM dept; Selecting All Columns

7 LOCATION NEW YORK DALLAS CHICAGO BOSTON SQL> SELECT loc AS location 2 FROM dept; Specifying Output Headings Note Upper-Case Heading

8 Location NEW YORK DALLAS CHICAGO BOSTON SQL> SELECT loc AS “Location” 2 FROM dept; Specifying Output Headings Note Mixed-Case HeadingDouble quotes

9 JOB PRESIDENT MANAGER SALESMAN... SQL> SELECT job 2 FROM emp; Duplicate Output A total of 14 records display

10 JOB ANALYST CLERK MANAGER PRESIDENT SALESMAN SQL> SELECT DISTINCT job 2 FROM emp; Suppressing Duplicate Output Each unique job is listed only once DISTINCT precedes the list of fields

11 ENAME JOB SAL JAMES CLERK 950 SMITH CLERK 800 ADAMS CLERK 1100 MILLER CLERK 1300 SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE job = ‘CLERK’; Limiting Rows with WHERE Case sensitive; single quotes

12 SQL> SELECT ename, hiredate 2 FROM emp 3 WHERE hiredate >= ’01-JAN-1982'; SQL> SELECT ename, hiredate 2 FROM emp 3 WHERE hiredate >= ’01-JAN-1982'; WHERE Clause Criteria  Text and dates are enclosed in single quotes  Numbers are not enclosed in quotes  Text values are case sensitive  Date values are format sensitive (Our Oracle default date format is DD-MON-YYYY)

13 SQL Comparison Operators

14 SQL Comparison Operators

15 ENAME SAL MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300 SQL> SELECT ename, sal 2 FROM emp 3 WHERE sal BETWEEN 1000 AND 1500; BETWEEN Operator Example

16 ENAME JOB KING PRESIDENT BLAKE MANAGER CLARK MANAGER JONES MANAGER SQL> SELECT ename, job 2 FROM emp 3 WHERE job IN(‘PRESIDENT’,’MANAGER’); IN Operator Example

17 ENAME JONES JAMES SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE ‘J%’; LIKE Operator Example The % is a wildcard character that stands for zero to many characters. The underscore character (_) can be used to stand for exactly one character. The LIKE comparison operator is used when using wildcards. ( LIKE is not the same as = )

18 ENAME MGR KING SQL> SELECT ename, mgr 2 FROM emp 3 WHERE mgr IS NULL; IS NULL Operator Example

19 Boolean (Logical) Operators

20 ENAME JOB SAL ADAMS CLERK 1100 MILLER CLERK 1300 SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE job = ‘CLERK’ 4 AND sal > 1000; AND Operator Example Both conditions must be true

21 ENAME JONES MARTIN JAMES MILLER SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE ‘J%’ 4 OR ename LIKE ‘M%’; OR Operator Example At least one condition must be true

22 JOB ANALYST MANAGER PRESIDENT SALESMAN SQL> SELECT DISTINCT job 2 FROM emp 3 WHERE job NOT LIKE ‘C%’; NOT Operator Example

23 Arithmetic Operators

24 ENAME SAL ANNUAL JAMES SMITH ADAMS MILLER SQL> SELECT ename, sal, sal*12 AS annual 2 FROM emp 3 WHERE job = ‘CLERK’; Arithmetic Expression Example

25 Aggregate Functions

26 SALARY AVG SQL> SELECT AVG(sal) AS “SALARY AVG” 2 FROM emp 3 WHERE job = ‘SALESMAN’; Aggregate Function Example

27 COUNT(*) SQL> SELECT COUNT(*) 2 FROM emp; Aggregate Function Example Note: COUNT(*) returns the number of rows in a table while COUNT(field) returns the number of rows that are nonnull for the field counted

28 ENAME JOB SAL ADAMS CLERK 1100 ALLEN SALESMAN 1600 BLAKE MANAGER 2850 CLARK MANAGER 2450 FORD ANALYST SQL> SELECT ename, job, sal 2 FROM emp 3 ORDER BY ename; Sorting Rows with ORDER BY

29 ENAME JOB SAL FORD ANALYST 3000 SCOTT ANALYST 3000 ADAMS CLERK 1100 JAMES CLERK 950 MILLER CLERK SQL> SELECT ename, job, sal 2 FROM emp 3 ORDER BY job, ename; Sorting by Multiple Fields The order of the list determines the precedence of the sort order

30 ENAME JOB SAL KING PRESIDENT 5000 FORD ANALYST 3000 SCOTT ANALYST 3000 JONES MANAGER 2975 BLAKE MANAGER SQL> SELECT ename, job, sal 2 FROM emp 3 ORDER BY sal DESC; Sorting in Descending Order

31 JOB AVG(SAL) ANALYST 3000 CLERK MANAGER PRESIDENT 5000 SALESMAN 1400 SQL> SELECT job, AVG(sal) 2 FROM emp 3 GROUP BY job; Categorizing with GROUP BY IMPORTANT NOTE: Any field or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause

32 DEPTNO COUNT(*) SQL> SELECT deptno, COUNT(*) 2 FROM emp 3 GROUP BY deptno; Categorizing with GROUP BY

33 DEPTNO COUNT(*) SQL> SELECT deptno, COUNT(*) 2 FROM emp 3 GROUP BY deptno 4 HAVING COUNT(*) >= 5; Limiting GROUP BY with HAVING HAVING acts similarly to a WHERE clause, but operates on groups, not on individual records

34 Processing Multiple Tables  When relationships exist between tables, the tables can be linked together in queries  Relationships between tables are established by setting up primary key to foreign key relationships between columns that are common to both tables  We link related tables together in SQL queries by using joins

35 Joins  A join is defined as: “A relational operation that causes two tables with a common domain to be combined into a single table”  A join is specified in SQL by using a WHERE clause to match values for the common field between the two tables (if you were joining three tables, you would need two joining WHERE clauses)  Each row in the resultant output table contains data from rows in the input tables where values for the common field match

36 EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO EMP EMPNOENAME...DEPTNO KING BLAKE CLARK JONES DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON Data from Multiple Tables DEPTNO is the common field joining the EMP and DEPT tables

37 SELECTtable1.field, table2.field,... FROMtable1, table2 WHEREtable1.fieldX = table2.fieldX; SELECTtable1.field, table2.field,... FROMtable1, table2 WHEREtable1.fieldX = table2.fieldX; Creating a Join in SQL  Write the join condition in the WHERE clause  Prefix the column name with the table name when the same column name appears in more than one table (to avoid ambiguity) SELECTempno, emp.deptno, loc FROMemp, dept WHEREemp.deptno = dept.deptno; SELECTempno, emp.deptno, loc FROMemp, dept WHEREemp.deptno = dept.deptno; This is the query that is shown on the previous slide

38 ORDERDATE QTY DESCRIP JAN-87 1 ACE TENNIS NET 11-JAN-87 1 ACE TENNIS RACKET II 15-JAN ACE TENNIS RACKET I 01-MAY-86 1 SB ENERGY BAR-6 PACK 05-JUN ACE TENNIS BALLS-3 PACK 15-JUN-86 3 ACE TENNIS NET SQL> SELECT ord.orderdate, item.qty, product.descrip 2 FROM ord, item, product 3 WHERE ord.ordid = item.ordid 4 AND item.prodid = product.prodid; 3 Table Join Example Note: Table name prefixes are used here for all fields for clarity

39 Avoiding Cartesian Products  A Cartesian product is formed when a query on multiple tables is attempted and the join condition is omitted or is invalid  The result is that all rows in the first table are joined to all rows in the second table (e.g., if there were 10 rows in each table, the query would return 100 rows in the result)  To avoid a Cartesian product, always include a valid join condition in the WHERE clause of your SELECT statement

40 Join Types  Equi-join: “A join in which the joining condition is based on equality between values in the common columns. Common columns appear (redundantly) in the result table.”  Natural join: “Same as equi-join except one of the duplicate columns is eliminated in the result table.”  Outer join: “A join in which rows that do not have matching values in common columns are nevertheless included in the result table.”  Self join: A join that represents a recursive unary relationship of a table with itself.

41 ENAME DEPTNO DEPTNO DNAME KING ACCOUNTING BLAKE SALES CLARK ACCOUNTING JONES RESEARCH MARTIN SALES ALLEN SALES SQL> SELECT ename, emp.deptno, dept.deptno, dname 2 FROM emp, dept 3 WHERE emp.deptno = dept.deptno; Equi-join Example Note duplicate columns Note joining WHERE clause Note table name prefixes used to specify names for common fields

42 ENAME DEPTNO DNAME KING 10 ACCOUNTING BLAKE 30 SALES CLARK 10 ACCOUNTING JONES 20 RESEARCH MARTIN 30 SALES ALLEN 30 SALES SQL> SELECT ename, emp.deptno, dname 2 FROM emp, dept 3 WHERE emp.deptno = dept.deptno; Natural Join Example Note elimination of duplicate column Note elimination of duplicate field

43 ENAME DEPTNO DNAME KING 10 ACCOUNTING BLAKE 30 SALES CLARK 10 ACCOUNTING MILLER 10 ACCOUNTING SQL> SELECT ename, emp.deptno, dname 2 FROM emp, dept 3 WHERE emp.deptno = dept.deptno; Outer Join Example A total of 14 rows are returned First, let’s run this as a natural join

44 ENAME DEPTNO DNAME KING 10 ACCOUNTING BLAKE 30 SALES CLARK 10 ACCOUNTING MILLER 10 ACCOUNTING OPERATIONS SQL> SELECT ename, emp.deptno, dname 2 FROM emp, dept 3 WHERE emp.deptno (+) = dept.deptno; Outer Join Example A total of 15 rows are returned Now, we’ll use an outer join, with Oracle notation (+) Included is this department that has no employees

45 Using Outer Joins  The outer join operator (+) can appear on only one side of the equal sign in the WHERE clause; it is placed on the side that is deficient in information  A condition involving an outer join cannot be linked to another condition by the OR operator or use the IN operator  ANSI standard syntax is different than Oracle’s (e.g., LEFT OUTER JOIN)

46 Self Joins  Used to join a table to itself  Useful to query a table involved in a recursive unary relationship with itself  Aliases are used in order to be able to distinguish the side of the relationship the table being referenced is on e.g., we could reference the emp table on the employee side of a “manages” unary relationship as “e” and the same table on the manager side of the relationship as “m”

47 EMPNO ENAME MGR KING 7698 BLAKE CLARK JONES MARTIN ALLEN SQL> SELECT empno, ename, mgr 2 FROM emp; Preparation for Self Join Identify the common fields

48 ENAME MANAGER KING BLAKE KING CLARK KING JONES KING MARTIN BLAKE... SQL> SELECT e.ename, m.ename AS manager 2 FROM emp e, emp m 3 WHERE e.mgr = m.empno (+); Self Join Example Aliases Note: Aliases can be useful in other situations besides self joins. Any time you wish to abbreviate a table name you can use them

49 Subqueries  Subqueries are useful when a query is based on unknown values (e.g., “Who has a salary greater than Blake?” when Blake’s salary is unknown)  Subqueries involve placing an inner query (SELECT…FROM…WHERE...etc.) within a WHERE or HAVING clause of an outer query  The inner query is a complete query that could stand on its own and serves to provide values for the search condition of the outer query

50 ENAME KING JONES FORD SCOTT SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno = 7698); Subquery Example The inner query is enclosed in parentheses; indenting is optional The inner query determines the salary of Blake (empno = 7698) and returns it to the outer query

51 ENAME JOB SAL SMITH CLERK 800 SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp); Another Subquery Example The inner query determines the minimum salary of all employees and returns it to the outer query