0% found this document useful (0 votes)
25 views19 pages

Bcis5420 - Lecture Note - ch2 - Single Table Queries

The document discusses SQL SELECT queries for single table queries including selecting columns, aggregate functions, grouping and ordering results, and filtering with conditions. Key concepts covered are the SELECT statement, FROM and WHERE clauses, aggregate functions like COUNT and SUM, using GROUP BY with ORDER BY, and the HAVING clause for adding conditions to groups.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views19 pages

Bcis5420 - Lecture Note - ch2 - Single Table Queries

The document discusses SQL SELECT queries for single table queries including selecting columns, aggregate functions, grouping and ordering results, and filtering with conditions. Key concepts covered are the SELECT statement, FROM and WHERE clauses, aggregate functions like COUNT and SUM, using GROUP BY with ORDER BY, and the HAVING clause for adding conditions to groups.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Ch.2.

Single Table Queries

Chapter 2

Single Table Queries


Ch.2. Single Table Queries

Section. 1

SELECT
Ch.2. Single Table Queries

Single Table Queries

• Queries to handle data from a single data table


• SELECT: Essential to perform single table queries, selecting column(s)
• Fundamental framework of SQL SELECT query;

▪ SELECT [column name(s)]


▪ FROM [table name(s)]
▪ WHERE [condition(s)]
Ch.2. Single Table Queries

Single Table Queries_ SELECT


SELECT CustomerID FROM CUSTOMER
CUSTOMER

CustomerID AccountNumber CustomerID

CT_1 AN_1 CT_1


CT_2 AN_2 CT_2
CT_3 AN_3 CT_3
CT_4 AN_4 CT_4
CT_5 AN_5 CT_5

SELECT * FROM CUSTOMER


CUSTOMER

CustomerID AccountNumber CustomerID AccountNumber

CT_1 AN_1 CT_1 AN_1


CT_2 AN_2 CT_2 AN_2
CT_3 AN_3 CT_3 AN_3
CT_4 AN_4 CT_4 AN_4
CT_5 AN_5 CT_5 AN_5
Ch.2. Single Table Queries

Miscellaneous Tips for Queries_1

• SQL reads data table first and then, columns


SELECT * FROM ADVENTUREWORKS.PERSON.PERSON
Read table first!

• Table names are structured in a hierarchical system


SELECT * FROM ADVENTUREWORKS.PERSON.PERSON
Master DB Data Table

• Use semicolon (;) to list multiple queries

SELECT * FROM ADVENTUREWORKS.PERSON.PERSON;


SELECT* FROM ADVENTUREWORKS.SALES.SALESORDERDETAIL;

Query Separator
Ch.2. Single Table Queries

Miscellaneous Tips for Queries_2

• Queries for commands, columns, tables, and conditions are NOT


case sensitive (c.f., different from R or Python) but space sensitive
(c.f., same as R or Python)
• Queries in separate lines and those in one line provide the same result
• Brackets, [ ], can be used to clearly distinguish each word in query
but not making difference
• However, it is more convenient and precise, if separating them in
multiple lines and using the same column and table names in terms of
lower and upper cases (i.e., using auto-completion)
Ch.2. Single Table Queries

Application of SELECT

• Show all columns and rows of a table (from the DB, AdventureWorks)
SELECT * FROM ADVENTUREWORKS.PERSON.PERSON

• Select columns
SELECT BusinessEntityID, LastName FROM ADVENTUREWORKS.PERSON.PERSON

• Select TOP x percent of rows


SELECT TOP 1 PERCENT * FROM ADVENTUREWORKS.PERSON.PERSON
SELECT TOP 1 PERCENT BusinessEntityID FROM ADVENTUREWORKS.PERSON.PERSON

• Select TOP n rows


SELECT TOP 100 * FROM ADVENTUREWORKS. PERSON.PERSON
SELECT TOP 100 BusinessEntityID FROM ADVENTUREWORKS. PERSON.PERSON
Ch.2. Single Table Queries

SELECT with AS
• Showing column headers in different words using AS
SELECT BusinessEntityIDAS TempID, PersonType AS EmployeeFlag,
FirstName AS FName FROM ADVENTUREWORKS.PERSON.PERSON

• Using Brackets in place of column name using AS


SELECT
[SalesOrderID],[SalesOrderDetailID],[CarrierTrackingNumber],[OrderQty],
[ProductID],[SpecialOfferID],[UnitPrice],[UnitPriceDiscount],
[OrderQty]*[UnitPrice] AS [NonDiscountSales],
[LineTotal],[rowguid],[ModifiedDate]
FROM [AdventureWorks].[Sales].[SalesOrderDetail]
Ch.2. Single Table Queries

SELECT with DISTINCT

• Return unique (i.e., distinct) values in a column


• Place in front of the column to apply DISTINCT;

SELECT * FROM Adventureworks.HumanResources.Employee


SELECT JobTitle FROM Adventureworks.HumanResources.Employee

SELECT DISTINCT JobTitle FROM Adventureworks.HumanResources.Employee


Ch.2. Single Table Queries

SELECT with ORDER BY (1 of 2)


• Order the result set
• If ORDER BY is not specified, the order of returned rows is not guaranteed

▪ Single column
SELECT ProductID, Name FROM AdventureWorks.Production.Product ORDER BY ProductID;

▪ Column not defined in SELECT


SELECT ProductID, Name FROM AdventureWorks.Production.Product ORDER BY ListPrice;

▪ Alias as sort column


SELECT ProductID AS IDofProduct, Name FROM AdventureWorks.Production.Product
ORDER BY IDofProduct;

▪ Expression as sort column


SELECT BusinessEntityID, JobTitle, HireDate FROM
AdventureWorks.HumanResources.Employee ORDER BY DATEPART(month, HireDate);
Ch.2. Single Table Queries

SELECT with ORDER BY (2 of 2)

▪ Multiple columns

SELECT LastName, FirstName FROM


AdventureWorks.Person.Person ORDER BY FirstName, LastName

▪ Specifying both Ascending and Descending (default: ascending)

SELECT LastName, FirstName FROM AdventureWorks.Person.Person


ORDER BY FirstName ASC, LastName DESC;
Ch.2. Single Table Queries

SELECT with WHERE


• Indicate the conditions under which a row will be included in the result
• Selection of rows is via the WHERE clause
• Build expressions using comparison operators including:
▪ = Equal to
▪ > Greater than, >= Greater than or equal to
▪ < Less than, <= Less than or equal to
▪ <> OR != Not equal to
▪ E.g., SELECT BusinessEntityID, NationalIDNumber FROM
AdventureWorks.HumanResources.Employee WHERE MaritalStatus = 'M'

• May also include arithmetic operators such as +, *, etc.


• Often used with LIKE to identify conditions for WHERE
▪ SELECT JobTitle FROM AdventureWorks.HumanResources.Employee
WHERE JobTitle LIKE 'Vice President%'
Ch.2. Single Table Queries

Section. 2

Aggregate Functions
Ch.2. Single Table Queries

SELECT with Aggregate Functions


• Used for estimating simple descriptive statistics of data (c.f., Excel Pivot table)

• SQL built-in functions

Function Meaning

COUNT(*) Count the number of rows in the table

COUNT(Column Name) Count the number of rows in the table where a column IS NOT NULL

SUM Estimate the sum of all values (numeric columns only)

AVG Estimate the average of all values (numeric columns only)

MIN Estimate the minimum of all values (numeric columns only)

MAX Estimate the maximum of all values (numeric columns only)


Ch.2. Single Table Queries

SELECT with Aggregate Functions _Examples

• SELECT * FROM AdventureWorks.HumanResources.Employee

• SELECT COUNT(*) FROM AdventureWorks.HumanResources.Employee

• SELECT COUNT (ProductID) AS NumberOfProductID FROM


AdventureWorks.Sales.SalesOrderDetail

• SELECT COUNT (DISTINCT ProductID) AS UniqueProductID FROM


AdventureWorks.Sales.SalesOrderDetail
• SELECT COUNT(*) FROM AdventureWorks.HumanResources.Employee WHERE
JobTitle LIKE 'Vice President%'

• SELECT AVG(VacationHours) AS [Average vacation hours], SUM(SickLeaveHours)


AS [Total sick leave hours], MIN(SickLeaveHours) AS [Minimum sick leave hours],
MAX(SickLeaveHours) AS [Maximum sick leave hours] FROM
AdventureWorks.HumanResources.Employee WHERE JobTitle LIKE 'Vice President%'
Ch.2. Single Table Queries

SELECT with GROUP BY and ORDER BY


• Sort query result into groups of rows (GROUP BY): used with aggregate functions
(e.g., count, max, min, sum, avg)

• Then, order them in alphabetic order (ORDER BY)

• Enable additional aggregation on each group

• SELECT with GROUP BY and ORDER BY examples;

▪ SELECT SalesOrderID, SUM(LineTotal) AS SubTotal FROM


AdventureWorks.Sales.SalesOrderDetail GROUP BY SalesOrderID
ORDER BY SalesOrderID
▪ SELECT ProductID, SpecialOfferID, AVG(UnitPrice) AS [Average Price],
SUM(LineTotal) AS SubTotal FROM AdventureWorks.Sales.SalesOrderDetail
GROUP BY ProductID, SpecialOfferID ORDER BY ProductID DESC
▪ SELECT ProductModelID, AVG(ListPrice) AS 'Average List Price' FROM
AdventureWorks.Production.Product WHERE ListPrice > $1000 GROUP BY
ProductModelID ORDER BY ProductModelID
Ch.2. Single Table Queries

Table Dimensionality

• Will the queries below work? If not, why?

▪ SELECT COUNT (ProductID) AS NumberOfProductID, LineTotal FROM


AdventureWorks.Sales.SalesOrderDetail

▪ SELECT SalesOrderID, SUM(LineTotal) AS SubTotal FROM


AdventureWorks.Sales.SalesOrderDetail ORDER BY SalesOrderID

Impossible to Combine in a Table


LineTotal
2024.994000
NumberOfProductID
6074.982000
121317 2024.994000
2039.994000
2039.994000
Ch.2. Single Table Queries

SELECT with HAVING

• Add condition to a group or aggregate (c.f., WHERE cannot be used with


aggregate functions)

• Similar to WHERE but operated on groups (after GROUP BY), not on


individual rows

• SELECT with HAVING example;

▪ SELECT SalesOrderID, SUM(LineTotal) AS [SubTotal] FROM


AdventureWorks.Sales.SalesOrderDetail GROUP BY SalesOrderID
HAVING SUM(LineTotal) > 100000.00 ORDER BY SalesOrderID

▪ SELECT SalesOrderID, SUM(LineTotal) AS [SubTotal] FROM


AdventureWorks.Sales.SalesOrderDetail GROUP BY SalesOrderID
HAVING SUM(OrderQty) > 10 ORDER BY SubTotal
Ch.2. Single Table Queries

References

• The major contents of this note are reproduced from the textbook of BCIS 5420;
Topi et al. Modern Database Management. 13 th edition. Pearson's, 2019

• Unless having a specific reference source, the photos and icons used in this
material are from the following sources providing copyright free images:
imagesource.com, iconfinder.com, and pexels.com

• The diagrams used are from the textbook publisher’s materials

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy