SlideShare a Scribd company logo
Querying and Reporting  Module 3
Arithmetic operators used in SQL Built in Functions Retrieving data with the select statements Grouping Results sets Joins Sub queries Learning Objectives
At the end of this section, you should be able to work with: Arithmetic operators used in SQL Built in Functions String Functions Date Functions System Functions Aggregate Functions Retrieving data with the select statements Based on Conditions Limit Results Module 3 : Agenda
Module 3 : Agenda Grouping Results sets Group by Compute and Compute By Joins Natural Join Equi Join Self Join Outer Join Sub queries In Exists Correlated sub queries
SELECT Statement Use the SELECT statement to retrieve data from one or more tables: SELECT  <column(s) >  FROM  <table> [ WHERE  <condition>] [ ORDER   BY  <column(s) [ASC|DESC]>] table is the name of the table column is the name of the column in the table to be selected condition identifies the rows to be selected and is composed of  column names, expressions, constraints, sub-queries and  comparison operators column is the name of the column(s) used for sorting (order by)
Querying and Reporting Selection : Querying for selection retrieves a subset of the rows in one or more tables. Example Projection : Querying for projection retrieves a subset of the columns in one or more tables. It is best to put each column chosen in a separate line Example SELECT  *  FROM emp  SELECT  empno, ename, deptno  FROM emp
Rearranging order of columns:  Example Using Column aliases Example Querying and Reporting (Continued) SELECT ename as [Employee Name], empno, deptno FROM emp  SELECT  empname, eno, deptno  FROM emp
Arithmetic Operators Modulo % Division / Addition + Multiplication * Subtraction - Operation Operator
Built in Functions Built in Functions are a T-SQL extension to SQL String Functions Date Functions System Functions Aggregate Functions
Built In Functions : String Functions Returns part of a string.  Start s pecifies the character position at which the substring begins.  length  specifies the number of characters in the substring. substring ( expression ,  start ,  length ) Returns the reverse of the character or binary expression reverse ( expression ) Returns an integer representing the number of characters in a character expression or text value. char_length ( char_expr ) Returns the ASCII code for the first character in the expression. ascii ( char_expr ) Descriptions Functions
Built In Functions : Date Functions Returns date produced by adding datepart to given date. dateadd ( datepart , number,  date ) Returns the time between the first and second date. You can specify the datepart as months, years, hours, etc. datediff (datepart, date, date) Returns part of date as an integer. datepart ( datepart, date ) Returns Current system date and time. getdate () Descriptions Functions
Built In Functions : System Functions Returns the length of the column datalength ( expression ) Returns the computer name Host_name () Returns the process id of the process.  host_id ( ) Descriptions Functions
Use of Aggregate Functions Aggregate functions are used to summarize the data retrieved in a query. Total of the (distinct) values in the expression Sum ([all | distinct]  expression ) Lowest value in the expression Min ( expression ) Highest value in the expression Max ( expression ) Number of selected rows – including null values count(*) Number of (distinct) non-null values in the expression Count ([all | distinct]  expression ) Average of the (distinct) values in the expression Avg ([all | distinct]  expression ) Description Aggregate Function
Selecting Rows – Search Based The method of restriction is the basis of the WHERE clause in SQL Character strings and dates in the WHERE clause must be enclosed in single quotation marks (‘)
Rows may be limited by: EQUALS CONDITION Display rows based on an exact match of values SELECT   LastName,    Salary   FROM   Employee   WHERE   Salary   = 30000 SELECT   EmployeeId,     LastName FROM  Employee  WHERE  ManagerName = ‘RAYMOND’
Rows may be limited by: (Continued) >, <, <=, >= or <> CONDITION SELECT   LastName FROM   Employee   WHERE   Salary > 30000 SELECT   EmployeeId,   LastName FROM   Employee   WHERE   Salary   <= 30000 SELECT   EmployeeId FROM   Employee   WHERE   Status <> ‘ACTIVE’
Rows may be limited by: (Continued) BETWEEN  CONDITION Display rows based on a range of values SELECT   LastName FROM   Employee   WHERE   Salary   BETWEEN   30000   AND   50000   IN  CONDITION Display rows based on a list of values SELECT   EmployeeId FROM  Employee   WHERE  ManagerId  IN  (100, 200, 300)
Rows may be limited by: (Continued) LIKE  CONDITION Performs wildcard searches of valid search string values Can contain either literal characters or numbers % denotes zero or many characters _ denotes one character Use ESCAPE identifier to search for the actual % and _symbols SELECT   LastName  FROM   Employee   WHERE   LastName   LIKE   ‘%ram’ SELECT   LastName  FROM   Employee   WHERE   LastName   LIKE   ‘_at’
Rows may be limited by: (Continued) LOGICAL CONDITION AND, OR, NOT SELECT   LastName ,  JobId   FROM   Employee   WHERE   Salary  <= 15000  AND  JobId = ‘SE’ SELECT   LastName ,  JobId   FROM   Employee   WHERE   Salary  <=  15000  OR  JobId = ‘SE’
Rows may be limited by: (Continued) LOGICAL CONDITION AND, OR, NOT SELECT   LastName ,  JobId   FROM   Employee   WHERE   Salary  <= 15000  AND  NOT  JobId = ‘SE’
Rows may be limited by: (Continued) Distinct Top  Percent SELECT     distinct au_id ,  FROM    titleauthor SELECT     Top(4) *  FROM    titleauthor SELECT     Top 20 percent * FROM    titleauthor
Sorting Rows ORDER BY clause ASC  specifies an ascending order DESC  specifies a descending order SELECT     LastName,     Salary ,    JobId   FROM     Employee   ORDER   BY   Salary   DESC,   JobId  ASC   Display the result in descending order by the attribute salary If two records have the same attribute value, the salary sorting criteria is in ascending order according to the attribute values of JobId
Group By – A group by expression can contain column names not present in the select list. Grouping Result Sets SELECT     type,   avg(price),   sum(ytd_sales)  FROM    title s Group by pub_id, type
Compute clause provides a detail and summary rows with one select statement. You can calculate more than one row aggregate. Grouping Result Sets SELECT     type,   price,   advance  FROM    title s Order by type Compute sum(price), sum(advance) SELECT     type,   price,   advance  FROM    title s Order by type Compute sum(price), sum(advance) By type
Joins Joins compare two or more tables or views by specifying compare column. It checks values in these columns row wise and links the rows with the matching values.  Joins can be applied to the tables of the own database or other databases (with select permissions)
start of select, update, insert, delete, or subquery from { table_list  |  view_list } where [not] [ table_name . |  view_name .] column_name join_operator [ table_name . |  view_name .] column_name [{and | or} [not] [ table_name .| view_name .] column_name join_operator [ table_nam e.| view_name .] column_name ]... End of select, update, insert, delete, or subquery Joins - Syntax
Joins – Cross Join When a join is applied without the WHERE clause it produces the Cartesian product of the tables involved in that join.  USE AdventureWorks   GO SELECT  p.SalesPersonID,  t.Name AS Territory FROM  Sales.SalesPerson p CROSS JOIN  Sales.SalesTerritory t ORDER BY p.SalesPersonID;
Joins – Equi Join and Natural Join Joins based on equality are called as Equi Joins When an Equi-join returns all the columns of both the tables it is known as Natural Join SELECT  au_fname, pub_name FROM  Authors, Publishers Where Authors.city=Publishers.city SELECT  * FROM  Authors, Publishers Where Authors.city=Publishers.city
Joins – Self Join When a join compares values within the same column of one table are called as self joins. USE pubs;   GO select au1.au_fname,  au2.au_fname,  from  authors au1,  authors au2 where au1.city = &quot;Oakland&quot; and au2.city = &quot;Oakland&quot; and  au1.state = &quot;CA&quot; and au2.state = &quot;CA&quot; and  au1.postalcode = au2.postalcode
Joins – Outer Join Outer joins include all the rows regardless of whether there are  matching rows.  Outer Joins are of 3 types Left Outer Right Outer Full Outer SELECT  * FROM  titles LEFT JOIN titileauthor  ON titiles.title_id = titleauthor.title_id
Joins – Outer Join SELECT  * FROM  titles RIGHT JOIN titileauthor  ON titiles.title_id = titleauthor.title_id SELECT  * FROM  titles FULL OUTER JOIN titileauthor  ON titiles.title_id = titleauthor.title_id
Sub Queries A subquery is nested select statement in another select/insert/update/delete statement as a condition. A subquery can be used as an expression. When subquery can be evaluated as if it were an independent query it is called a Non correlated subquery.  When a subquery can not be evaluated as an independent query, but can reference columns in a table listed in the from list of the outer query, it is called a correlated subquery.  There are two types of subqueries Expression subqueries Quantified predicate subqueries
Sub Queries (Continued) Expression subqueries:  The value retuned is always single value which is further used for comparison. SELECT  title, price FROM  titles WHERE price = ( SELECT  price FROM  titles WHERE  title = 'Straight Talk About Computers')
Sub Queries (Continued) Quantified predicate subqueries:  The value returned can range from 0..n. This query operates on lists introduced with IN or with a comparison operator. Further it can be used as an existence test with the EXISTS introduced with exists. Subqueries with IN SELECT  pub_name FROM  publishers  WHERE  pub_id  IN (SELECT  pub_id  FROM  titles  WHERE type = ‘business’)
Subqueries with Exists Sub Queries (Continued) SELECT  pub_name FROM  publishers  WHERE  EXISTS (SELECT  *  FROM  titles  WHERE pub_id = publishers.pub_id   AND  type = ‘business’)
Correlated Subqueries Sub Queries (Continued) SELECT  table1.type FROM  titles table1  WHERE  table1.type  IN  (SELECT table2.type  FROM  titles table2 WHERE table1. pub_id  ! =  table2. pub_id  )
You may find useful content on T-SQL joins on the following url: Web sites: http://www.sqlteam.com/article/writing-outer-joins-in-t-sql http://www.sqlmag.com/Article/ArticleID/5342/sql_server_5342.html http://pietschsoft.com/post/2005/12/T-SQL-Join-Tables-by-a-Field-that-contains-a-delimited-string.aspx ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/c4f98374-e8a7-4f73-8d0e-309bd94ad1ae.htm Resources
Key Points SQL is an industry standard language for updating to, and getting information from, a database. The basic and most common SQL statements are: SELECT, INSERT, UPDATE, DELETE.
Questions & Comments

More Related Content

PPT
Sql server select queries ppt 18
PPT
Sql operators & functions 3
PPTX
Where conditions and Operators in SQL
PPT
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
PPTX
1. dml select statement reterive data
PPT
Les09 (using ddl statements to create and manage tables)
DOC
Sql functions
PPT
Sql server select queries ppt 18
Sql operators & functions 3
Where conditions and Operators in SQL
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
1. dml select statement reterive data
Les09 (using ddl statements to create and manage tables)
Sql functions

What's hot (19)

PPT
PPT
Retrieving data using the sql select statement
PPT
Les02 (restricting and sorting data)
PPT
Les01 (retrieving data using the sql select statement)
PPT
SQL select statement and functions
PDF
Introduction to oracle functions
PPT
Sql select
PPT
ALL ABOUT SQL AND RDBMS
PPT
SQL- Introduction to MySQL
PPT
SQL Introduction to displaying data from multiple tables
PPT
Advanced Sql Training
PPTX
MULTIPLE TABLES
PPSX
Analytic & Windowing functions in oracle
PPT
Using single row functions to customize output
PDF
SQL Functions and Operators
PPT
Aggregate Functions,Final
PPTX
SQL Tutorial for Beginners
PPTX
Oracle: Functions
PDF
Introduction To Oracle Sql
Retrieving data using the sql select statement
Les02 (restricting and sorting data)
Les01 (retrieving data using the sql select statement)
SQL select statement and functions
Introduction to oracle functions
Sql select
ALL ABOUT SQL AND RDBMS
SQL- Introduction to MySQL
SQL Introduction to displaying data from multiple tables
Advanced Sql Training
MULTIPLE TABLES
Analytic & Windowing functions in oracle
Using single row functions to customize output
SQL Functions and Operators
Aggregate Functions,Final
SQL Tutorial for Beginners
Oracle: Functions
Introduction To Oracle Sql
Ad

Viewers also liked (20)

PDF
Transact sql data definition language - ddl- reference
PPT
Module02
PDF
5 tsssisu sql_server_2012
PDF
X query language reference
PPT
Module01
PPT
Module06
PPT
Module08
PPTX
SQL Server 2008 Spatial Data - Getting Started
PPTX
Sql Server Data Tools - Codenamed JUNEAU
PPT
Module04
PPT
Module05
PPTX
Alasql.js - SQL сервер на JavaScript
DOC
Css introduction
PPTX
Sql server ___________session3-normailzation
PPT
SQL Server 2008 for .NET Developers
PDF
High Performance Front-End Development
PPTX
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
PDF
Multidimensional model programming
PDF
Spatialware_2_Sql08
PPT
Module07
Transact sql data definition language - ddl- reference
Module02
5 tsssisu sql_server_2012
X query language reference
Module01
Module06
Module08
SQL Server 2008 Spatial Data - Getting Started
Sql Server Data Tools - Codenamed JUNEAU
Module04
Module05
Alasql.js - SQL сервер на JavaScript
Css introduction
Sql server ___________session3-normailzation
SQL Server 2008 for .NET Developers
High Performance Front-End Development
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Multidimensional model programming
Spatialware_2_Sql08
Module07
Ad

Similar to Module03 (20)

PDF
0716330552518_DBMS_LAB_THEORY_SQL_OPERATOR (1).pdf
PPT
Chinabankppt
PDF
0808.pdf
PDF
0808.pdf
PPTX
SQL Data Manipulation language and DQL commands
PPT
PDF
Structured query language(sql)
PPTX
Data Manipulation Language.pptx
PPTX
ADV Powepoint 3 Lec.pptx
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
PPT
Sql query [select, sub] 4
PPTX
SQLSERVERQUERIES.pptx
PPT
PPT
PPTX
PPT
PPTX
12. Basic SQL Queries (2).pptx
PPTX
2 puc cs.pptx bsbshsjshsbbsjsjshdbdbbdbdd
PDF
MySQL-commands.pdf
0716330552518_DBMS_LAB_THEORY_SQL_OPERATOR (1).pdf
Chinabankppt
0808.pdf
0808.pdf
SQL Data Manipulation language and DQL commands
Structured query language(sql)
Data Manipulation Language.pptx
ADV Powepoint 3 Lec.pptx
Database Systems - SQL - DDL Statements (Chapter 3/3)
Sql query [select, sub] 4
SQLSERVERQUERIES.pptx
12. Basic SQL Queries (2).pptx
2 puc cs.pptx bsbshsjshsbbsjsjshdbdbbdbdd
MySQL-commands.pdf

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharma ospi slides which help in ospi learning
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Insiders guide to clinical Medicine.pdf
PDF
Classroom Observation Tools for Teachers
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Cell Types and Its function , kingdom of life
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Pre independence Education in Inndia.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
Final Presentation General Medicine 03-08-2024.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharma ospi slides which help in ospi learning
human mycosis Human fungal infections are called human mycosis..pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
VCE English Exam - Section C Student Revision Booklet
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Insiders guide to clinical Medicine.pdf
Classroom Observation Tools for Teachers
O7-L3 Supply Chain Operations - ICLT Program
Cell Types and Its function , kingdom of life
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Pre independence Education in Inndia.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
TR - Agricultural Crops Production NC III.pdf

Module03

  • 2. Arithmetic operators used in SQL Built in Functions Retrieving data with the select statements Grouping Results sets Joins Sub queries Learning Objectives
  • 3. At the end of this section, you should be able to work with: Arithmetic operators used in SQL Built in Functions String Functions Date Functions System Functions Aggregate Functions Retrieving data with the select statements Based on Conditions Limit Results Module 3 : Agenda
  • 4. Module 3 : Agenda Grouping Results sets Group by Compute and Compute By Joins Natural Join Equi Join Self Join Outer Join Sub queries In Exists Correlated sub queries
  • 5. SELECT Statement Use the SELECT statement to retrieve data from one or more tables: SELECT <column(s) > FROM <table> [ WHERE <condition>] [ ORDER BY <column(s) [ASC|DESC]>] table is the name of the table column is the name of the column in the table to be selected condition identifies the rows to be selected and is composed of column names, expressions, constraints, sub-queries and comparison operators column is the name of the column(s) used for sorting (order by)
  • 6. Querying and Reporting Selection : Querying for selection retrieves a subset of the rows in one or more tables. Example Projection : Querying for projection retrieves a subset of the columns in one or more tables. It is best to put each column chosen in a separate line Example SELECT * FROM emp SELECT empno, ename, deptno FROM emp
  • 7. Rearranging order of columns: Example Using Column aliases Example Querying and Reporting (Continued) SELECT ename as [Employee Name], empno, deptno FROM emp SELECT empname, eno, deptno FROM emp
  • 8. Arithmetic Operators Modulo % Division / Addition + Multiplication * Subtraction - Operation Operator
  • 9. Built in Functions Built in Functions are a T-SQL extension to SQL String Functions Date Functions System Functions Aggregate Functions
  • 10. Built In Functions : String Functions Returns part of a string. Start s pecifies the character position at which the substring begins. length specifies the number of characters in the substring. substring ( expression , start , length ) Returns the reverse of the character or binary expression reverse ( expression ) Returns an integer representing the number of characters in a character expression or text value. char_length ( char_expr ) Returns the ASCII code for the first character in the expression. ascii ( char_expr ) Descriptions Functions
  • 11. Built In Functions : Date Functions Returns date produced by adding datepart to given date. dateadd ( datepart , number, date ) Returns the time between the first and second date. You can specify the datepart as months, years, hours, etc. datediff (datepart, date, date) Returns part of date as an integer. datepart ( datepart, date ) Returns Current system date and time. getdate () Descriptions Functions
  • 12. Built In Functions : System Functions Returns the length of the column datalength ( expression ) Returns the computer name Host_name () Returns the process id of the process. host_id ( ) Descriptions Functions
  • 13. Use of Aggregate Functions Aggregate functions are used to summarize the data retrieved in a query. Total of the (distinct) values in the expression Sum ([all | distinct] expression ) Lowest value in the expression Min ( expression ) Highest value in the expression Max ( expression ) Number of selected rows – including null values count(*) Number of (distinct) non-null values in the expression Count ([all | distinct] expression ) Average of the (distinct) values in the expression Avg ([all | distinct] expression ) Description Aggregate Function
  • 14. Selecting Rows – Search Based The method of restriction is the basis of the WHERE clause in SQL Character strings and dates in the WHERE clause must be enclosed in single quotation marks (‘)
  • 15. Rows may be limited by: EQUALS CONDITION Display rows based on an exact match of values SELECT LastName, Salary FROM Employee WHERE Salary = 30000 SELECT EmployeeId, LastName FROM Employee WHERE ManagerName = ‘RAYMOND’
  • 16. Rows may be limited by: (Continued) >, <, <=, >= or <> CONDITION SELECT LastName FROM Employee WHERE Salary > 30000 SELECT EmployeeId, LastName FROM Employee WHERE Salary <= 30000 SELECT EmployeeId FROM Employee WHERE Status <> ‘ACTIVE’
  • 17. Rows may be limited by: (Continued) BETWEEN CONDITION Display rows based on a range of values SELECT LastName FROM Employee WHERE Salary BETWEEN 30000 AND 50000 IN CONDITION Display rows based on a list of values SELECT EmployeeId FROM Employee WHERE ManagerId IN (100, 200, 300)
  • 18. Rows may be limited by: (Continued) LIKE CONDITION Performs wildcard searches of valid search string values Can contain either literal characters or numbers % denotes zero or many characters _ denotes one character Use ESCAPE identifier to search for the actual % and _symbols SELECT LastName FROM Employee WHERE LastName LIKE ‘%ram’ SELECT LastName FROM Employee WHERE LastName LIKE ‘_at’
  • 19. Rows may be limited by: (Continued) LOGICAL CONDITION AND, OR, NOT SELECT LastName , JobId FROM Employee WHERE Salary <= 15000 AND JobId = ‘SE’ SELECT LastName , JobId FROM Employee WHERE Salary <= 15000 OR JobId = ‘SE’
  • 20. Rows may be limited by: (Continued) LOGICAL CONDITION AND, OR, NOT SELECT LastName , JobId FROM Employee WHERE Salary <= 15000 AND NOT JobId = ‘SE’
  • 21. Rows may be limited by: (Continued) Distinct Top Percent SELECT distinct au_id , FROM titleauthor SELECT Top(4) * FROM titleauthor SELECT Top 20 percent * FROM titleauthor
  • 22. Sorting Rows ORDER BY clause ASC specifies an ascending order DESC specifies a descending order SELECT LastName, Salary , JobId FROM Employee ORDER BY Salary DESC, JobId ASC Display the result in descending order by the attribute salary If two records have the same attribute value, the salary sorting criteria is in ascending order according to the attribute values of JobId
  • 23. Group By – A group by expression can contain column names not present in the select list. Grouping Result Sets SELECT type, avg(price), sum(ytd_sales) FROM title s Group by pub_id, type
  • 24. Compute clause provides a detail and summary rows with one select statement. You can calculate more than one row aggregate. Grouping Result Sets SELECT type, price, advance FROM title s Order by type Compute sum(price), sum(advance) SELECT type, price, advance FROM title s Order by type Compute sum(price), sum(advance) By type
  • 25. Joins Joins compare two or more tables or views by specifying compare column. It checks values in these columns row wise and links the rows with the matching values. Joins can be applied to the tables of the own database or other databases (with select permissions)
  • 26. start of select, update, insert, delete, or subquery from { table_list | view_list } where [not] [ table_name . | view_name .] column_name join_operator [ table_name . | view_name .] column_name [{and | or} [not] [ table_name .| view_name .] column_name join_operator [ table_nam e.| view_name .] column_name ]... End of select, update, insert, delete, or subquery Joins - Syntax
  • 27. Joins – Cross Join When a join is applied without the WHERE clause it produces the Cartesian product of the tables involved in that join. USE AdventureWorks GO SELECT p.SalesPersonID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t ORDER BY p.SalesPersonID;
  • 28. Joins – Equi Join and Natural Join Joins based on equality are called as Equi Joins When an Equi-join returns all the columns of both the tables it is known as Natural Join SELECT au_fname, pub_name FROM Authors, Publishers Where Authors.city=Publishers.city SELECT * FROM Authors, Publishers Where Authors.city=Publishers.city
  • 29. Joins – Self Join When a join compares values within the same column of one table are called as self joins. USE pubs; GO select au1.au_fname, au2.au_fname, from authors au1, authors au2 where au1.city = &quot;Oakland&quot; and au2.city = &quot;Oakland&quot; and au1.state = &quot;CA&quot; and au2.state = &quot;CA&quot; and au1.postalcode = au2.postalcode
  • 30. Joins – Outer Join Outer joins include all the rows regardless of whether there are matching rows. Outer Joins are of 3 types Left Outer Right Outer Full Outer SELECT * FROM titles LEFT JOIN titileauthor ON titiles.title_id = titleauthor.title_id
  • 31. Joins – Outer Join SELECT * FROM titles RIGHT JOIN titileauthor ON titiles.title_id = titleauthor.title_id SELECT * FROM titles FULL OUTER JOIN titileauthor ON titiles.title_id = titleauthor.title_id
  • 32. Sub Queries A subquery is nested select statement in another select/insert/update/delete statement as a condition. A subquery can be used as an expression. When subquery can be evaluated as if it were an independent query it is called a Non correlated subquery. When a subquery can not be evaluated as an independent query, but can reference columns in a table listed in the from list of the outer query, it is called a correlated subquery. There are two types of subqueries Expression subqueries Quantified predicate subqueries
  • 33. Sub Queries (Continued) Expression subqueries: The value retuned is always single value which is further used for comparison. SELECT title, price FROM titles WHERE price = ( SELECT price FROM titles WHERE title = 'Straight Talk About Computers')
  • 34. Sub Queries (Continued) Quantified predicate subqueries: The value returned can range from 0..n. This query operates on lists introduced with IN or with a comparison operator. Further it can be used as an existence test with the EXISTS introduced with exists. Subqueries with IN SELECT pub_name FROM publishers WHERE pub_id IN (SELECT pub_id FROM titles WHERE type = ‘business’)
  • 35. Subqueries with Exists Sub Queries (Continued) SELECT pub_name FROM publishers WHERE EXISTS (SELECT * FROM titles WHERE pub_id = publishers.pub_id AND type = ‘business’)
  • 36. Correlated Subqueries Sub Queries (Continued) SELECT table1.type FROM titles table1 WHERE table1.type IN (SELECT table2.type FROM titles table2 WHERE table1. pub_id ! = table2. pub_id )
  • 37. You may find useful content on T-SQL joins on the following url: Web sites: http://www.sqlteam.com/article/writing-outer-joins-in-t-sql http://www.sqlmag.com/Article/ArticleID/5342/sql_server_5342.html http://pietschsoft.com/post/2005/12/T-SQL-Join-Tables-by-a-Field-that-contains-a-delimited-string.aspx ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/c4f98374-e8a7-4f73-8d0e-309bd94ad1ae.htm Resources
  • 38. Key Points SQL is an industry standard language for updating to, and getting information from, a database. The basic and most common SQL statements are: SELECT, INSERT, UPDATE, DELETE.

Editor's Notes

  • #6: Faculty Notes: Select - CHOOSE the columns in a table that you want returned by your query Where - FILTER the rows in a table that you want returned by your query Order By - SORT data selected from the table in a specified order
  • #11: Faculty Notes : Char_length function returns the number of character for variable-length data in a table column. However for fixed-length data, it returns the defined length of the column. Reverse(expression) returns reverse of the characters for example if expression is “abcd”, it returns “dcba” Substring(expression, start, length) Returns part of a string where start specifies the character position at which the substring begins. length specifies the number of characters in the substring.
  • #12: Faculty Notes : Datepart notations are given below- Year abbreviated as yy expects values 1753–9999 Quarter abbreviated as qq expected values 1–4 Month abbreviated as mm expected values 1–12 Week abbreviated as wk expected values 1–54 Day abbreviated as dd expected values 1–31 Dayofyear abbreviated as dy expected values 1–366 Weekday abbreviated as dw expected values 1– 7 (Sunday–Saturday) hour abbreviated as hh expected values 0–23 Minute abbreviated as mi expected values 0–59 Second abbreviated as ss expected values 0–59 millisecond abbreviated as ms expected values 0–999
  • #13: Faculty Notes : Examples : select datalength(&apos;aaa&apos;) select host_id() select suser_name()
  • #14: Faculty Notes: The aggregate functions work with any type of column; however there are few exceptions: sum and avg functions work only with the numeric columns of int, smallint, tinyint, decimal, numeric, float, and money. Min and max functions will not work with bit data types Only the count(*) works with text and image data types. Example : Use pubs go select sum(ytd_sales) [Total Sales] from titles select count (*)[Total Records], avg (price*2)[Average Price] from titles --counts null values as well select count (price)[Total Not Null Records], avg (price*2) [Average Price] from titles --doesn&apos;t count null values Select max (ytd_sales)[Max Sales], min (ytd_sales) [Max Sales] from titles
  • #15: Faculty Notes: WHERE Clause Specifies the condition for the rows returned by a query. Syntax WHERE &lt; search_condition &gt; Arguments &lt;search_condition&gt; Defines the condition to be met for the rows to be returned. There is no limit to the number of predicates in &lt;search_condition&gt;.
  • #16: Faculty Notes: Read the above slide. Read both the select statements. Explain the output of each statement as follows: The first statement displays the last name and salary of employees whose salary is equal to 30000 The second statement displays the Employee Id and Last name for employees whose manager name is ‘RAYMOND’
  • #17: Faculty Notes: Read the Select statements. Explain the output of each statement as follows: The first statement displays the last name of employees whose salary is greater than 30000 The second statement displays the Employee Id and Last Name of employees whose salary is less than equal to 30000 The third statement displays the Employee Id whose Status is not ‘ACTIVE’
  • #18: Faculty Notes: Between condition takes into account the lower and the upper limit In the above example the select statement will display last name of employees whose salary is between 30000 and 50000 including 30000 and 50000 IN condition takes into account on the values supplied In the above example the select statement will display employee id of employees whose manager id is 100 or 200 or 300
  • #19: Faculty Notes: % Matches any string of zero or more characters. This wildcard character can be used as either a prefix or a suffix. The above Select statement displays the last name of all employees ending with ‘ram’ from the employee table Example: ‘%ram’ will fetch all those values which end in ‘ram’ ram , program, monogram, gram _ (under score) Matches any single character, and can be used as either a prefix or suffix. The above Select statement displays the last name of all employees ending with ‘at’ from the employee table and whose length is three characters. Example: bat , rat, sat, hat You can search for wildcard characters (% , _) also. There are two methods for specifying a character that would ordinarily be a wildcard: Use the ESCAPE keyword to define an escape character. When the escape character is placed in front of the wildcard in the pattern, the wildcard is interpreted as a character. For example, to search for the string 5% anywhere in a string, use: WHERE ColumnA LIKE &apos;%5/%%&apos; ESCAPE &apos;/&apos; In this LIKE clause, the leading and ending percent signs (%) are interpreted as wildcards, and the percent sign preceded by a slash (/) is interpreted as the % character.
  • #20: Faculty Notes: In the above examples: Select statement will display last name , job id of all employees whose salary is less than equal to 15000 AND job id is ‘SE’ Select statement will display last name , job id of all employees whose salary is less than equal to 15000 OR job id is ‘SE’
  • #21: Faculty Notes: Select statement will display last name , job id of all employees whose salary is less than equal to 15000 and NOT job id is ‘SE’
  • #22: Faculty Notes : Distinct returns non repeating values To returns the first n rows mentioned in the function Percent returns the n percent rows from the total rows. This n value can range only between 0-100
  • #23: Faculty Notes: Step through and explain the slide.
  • #26: Faculty Notes: Joins Join conditions can be specified in either the FROM or WHERE clauses; specifying them in the FROM clause is recommended. WHERE and HAVING clauses can also contain search conditions to further filter the rows selected by the join conditions.
  • #28: Faculty Notes : A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The following example shows a Transact-SQL cross join. See ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/c4f98374-e8a7-4f73-8d0e-309bd94ad1ae.htm for more information.
  • #30: Faculty Notes : Joins can be categorized as: Inner joins (the typical join operation, which uses some comparison operator like = or &lt;&gt;). These include equi-joins and natural joins. Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables. The above stored procedure contains a select statement with INNER JOINS In above example, you can use a self-join to find out which authors in Oakland, California, live in the same postal code area. Since this query involves a join of the authors table with itself, the authors table appears in two roles. To distinguish these roles, you can temporarily and arbitrarily give the authors table two different correlation names—such as au1 and au2—in the from clause. These correlation names qualify the column names in the rest of the query.
  • #31: Faculty Notes : Outer joins : Outer joins can be a left, a right, or full outer join. Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables. Cross joins. Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.
  • #32: Faculty Notes : RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables. Cross joins. Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.
  • #39: Faculty Notes: Review the key points on the slide. The key points should be used to summarize the content covered throughout this presentation.