SlideShare a Scribd company logo
1 of 21
DML: SELECT
CIS-182
SELECT Queries
• Used to display data and calculations
• Main tool for making use of the data that‟s
stored in tables
– SELECT can be used as part of other commands
Key Words
• SELECT {field list}: What‟s returned
• FROM {data source}: Which table to use
• WHERE {criteria}: Which rows to include
• GROUP BY {field list}: How to summarize
• HAVING {field list}: Which groups to include
when grouping
• ORDER BY {field list}: How to sort
How Process
1. FROM – get data from original source(s)
2. WHERE – limit rows to work with
3. GROUP BY – create groups
4. HAVING – limit groups
5. SELECT – specify what to return
6. ORDER BY – specify sorting
SELECT
• SELECT starts statement
• Followed by field list
– Fields can refer to table fields or calculations created
as part of query
• SELECT can be used by itself:
SELECT GetDate()
FROM
• Describes where to find the data
• Can refer to a table or view
– View is a pre-defined select query, considered a
“virtual” table
• Basic query typically has SELECT and FROM
SELECT * FROM Titles
Using SELECT
• INTO – write results into table
• DISTINCT – eliminate repeating value(s) or
rows
• AS – name or rename a table or column
• * - include all fields from source
INTO
• Optional clause can write data from one or more
tables into another (new) table
• Typically used for
– Archiving
– To speed processing by creating temporary or
summary tables
– To organize for reporting
SELECT pub_state
INTO PublisherStates
FROM Publishers
DISTINCT
• Distinct eliminates repeating rows or values
– Used in SELECT clause
SELECT DISTINCT Title FROM Titles
Ensures that a title only is returned once, regardless of how
may times a title is found
SELECT DISTINCT pubid FROM Titles
Lists each publisher in the titles table just once, regardless of
number of books published
AS
• AS is used to create a field name for a calculation
or to rename an existing field
– Also referred to as an alias
– Use is optional
Rename fields in authors:
SELECT au_lname AS LastName FROM Authors
SELECT au_fname FirstName FROM Authors
*
• * represents all fields in data source
– Results may differ from what‟s expected if fields are
added, deleted or order changed
SELECT * FROM Publishers
Where
• WHERE limits which rows are included in the
result
• Criteria evaluate to True/False
– True means row will be used for result, false means
row will be excluded
– Sometimes „Predicates‟ is used in place of criteria (a
predicate is a characteristic that‟s true about a row)
Comparison Operators
• Relational (=, >, <,<>,>=,<=)
• Like – compares text patterns
– Wildcards
• One Character: _ (underscore)
• Any combination: %
• Between – compares to range
• Is – compares true/false/null
• In – value is in a list
• Exists – whether there‟s a value
Sample WHERE Clauses
SELECT *
FROM Titles
WHERE Price > 20
SELECT au_Lname
FROM Authors
WHERE State <> „wa‟
Logical Operators
• If have more than one test use AND/OR to tie
tests together
– AND: All parts must evaluate to True for a row to be
included
– OR: Any part evaluating to True means a row is
included
– Precedence: NOT then AND then OR
• NOT returns inverse
– Not False returns True
Logical Operator Examples
SELECT *
FROM Titles
WHERE Price > 20
AND Title LIKE „%SQL%‟
SELECT *
FROM Titles
WHERE Not Contract
Group By
• Allows data from tables to be summarized
– Find rows that share a common value
• Can discover information about the group using
aggregate functions
– Count
– Average
– Max
Sample Grouping
• Count number of books by publisher:
SELECT Count(*) BookCount, pub_id
FROM titles
GROUP BY pub_id
• Count books by price
SELECT Price, Count(*) AS BookCount
FROM Titles
GROUP BY Price
Having
• Determines which groups to include
• Use Criteria similar to Where clause
– Test characteristics of group using HAVING
– Use WHERE to determine which rows to include
Sample Having
• Display publisher ID‟s of those publishers
having more than 5 books published:
SELECT pub_id
FROM Titles
GROUP BY pub_id
HAVING Count(*) > 5
Order By
• Provides means to sort results by a column
(actual or calculated)
• Default sort order is Ascending
ORDER BY pub_date
ORDER BY au_lname DESC

More Related Content

What's hot (20)

Access 03
Access 03Access 03
Access 03
 
Tech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingTech Jam 01 - Database Querying
Tech Jam 01 - Database Querying
 
Data structures list
Data structures listData structures list
Data structures list
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
Advance excel
Advance excelAdvance excel
Advance excel
 
DIG1108C Lesson 5 Fall 2014
DIG1108C Lesson 5 Fall 2014DIG1108C Lesson 5 Fall 2014
DIG1108C Lesson 5 Fall 2014
 
Lists in Python
Lists in PythonLists in Python
Lists in Python
 
Array in c
Array in cArray in c
Array in c
 
Data Structure
Data StructureData Structure
Data Structure
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
SQL(database)
SQL(database)SQL(database)
SQL(database)
 
13 arrays
13 arrays13 arrays
13 arrays
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 
Array
ArrayArray
Array
 
Database index
Database indexDatabase index
Database index
 
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1 "Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
 
C++ arrays part1
C++ arrays part1C++ arrays part1
C++ arrays part1
 
Queries
QueriesQueries
Queries
 
Introduction to array and string
Introduction to array and stringIntroduction to array and string
Introduction to array and string
 

Similar to Select Queries (20)

CIS245 sql
CIS245 sqlCIS245 sql
CIS245 sql
 
Joins
JoinsJoins
Joins
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
OracleSQLraining.pptx
OracleSQLraining.pptxOracleSQLraining.pptx
OracleSQLraining.pptx
 
Sql performance tuning
Sql performance tuningSql performance tuning
Sql performance tuning
 
Sql server 2016 queries
Sql server 2016 queriesSql server 2016 queries
Sql server 2016 queries
 
Intro to t sql – 3rd session
Intro to t sql – 3rd sessionIntro to t sql – 3rd session
Intro to t sql – 3rd session
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Module03
Module03Module03
Module03
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Optimizing MySQL queries
Optimizing MySQL queriesOptimizing MySQL queries
Optimizing MySQL queries
 
Sql2
Sql2Sql2
Sql2
 
MariaDB 10.3 Optimizer - where does it stand
MariaDB 10.3 Optimizer - where does it standMariaDB 10.3 Optimizer - where does it stand
MariaDB 10.3 Optimizer - where does it stand
 
Subqueries
SubqueriesSubqueries
Subqueries
 
ExcelTipsAndTricks.pptx
ExcelTipsAndTricks.pptxExcelTipsAndTricks.pptx
ExcelTipsAndTricks.pptx
 
MS SQL Server.ppt
MS SQL Server.pptMS SQL Server.ppt
MS SQL Server.ppt
 
SQL_Part1
SQL_Part1SQL_Part1
SQL_Part1
 
Introduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]sIntroduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]s
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL Queries
 
Sql server introduction to sql server
Sql server introduction to sql server Sql server introduction to sql server
Sql server introduction to sql server
 

More from Randy Riness @ South Puget Sound Community College

More from Randy Riness @ South Puget Sound Community College (20)

Stored procedures
Stored proceduresStored procedures
Stored procedures
 
3 sql overview
3 sql overview3 sql overview
3 sql overview
 
Normalization
NormalizationNormalization
Normalization
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
CIS 245 Final Review
CIS 245 Final ReviewCIS 245 Final Review
CIS 245 Final Review
 
CIS145 Final Review
CIS145 Final ReviewCIS145 Final Review
CIS145 Final Review
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Cis245 Midterm Review
Cis245 Midterm ReviewCis245 Midterm Review
Cis245 Midterm Review
 
CSS
CSSCSS
CSS
 
XPath
XPathXPath
XPath
 
XSLT Overview
XSLT OverviewXSLT Overview
XSLT Overview
 
Views
ViewsViews
Views
 
CIS282 Midterm review
CIS282 Midterm reviewCIS282 Midterm review
CIS282 Midterm review
 
Schemas 2 - Restricting Values
Schemas 2 - Restricting ValuesSchemas 2 - Restricting Values
Schemas 2 - Restricting Values
 
CIS 145 test 1 review
CIS 145 test 1 reviewCIS 145 test 1 review
CIS 145 test 1 review
 
XML schemas
XML schemasXML schemas
XML schemas
 
Document type definitions part 2
Document type definitions part 2Document type definitions part 2
Document type definitions part 2
 
Document type definitions part 1
Document type definitions part 1Document type definitions part 1
Document type definitions part 1
 

Recently uploaded

Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
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
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 

Recently uploaded (20)

YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
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
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 

Select Queries

  • 2. SELECT Queries • Used to display data and calculations • Main tool for making use of the data that‟s stored in tables – SELECT can be used as part of other commands
  • 3. Key Words • SELECT {field list}: What‟s returned • FROM {data source}: Which table to use • WHERE {criteria}: Which rows to include • GROUP BY {field list}: How to summarize • HAVING {field list}: Which groups to include when grouping • ORDER BY {field list}: How to sort
  • 4. How Process 1. FROM – get data from original source(s) 2. WHERE – limit rows to work with 3. GROUP BY – create groups 4. HAVING – limit groups 5. SELECT – specify what to return 6. ORDER BY – specify sorting
  • 5. SELECT • SELECT starts statement • Followed by field list – Fields can refer to table fields or calculations created as part of query • SELECT can be used by itself: SELECT GetDate()
  • 6. FROM • Describes where to find the data • Can refer to a table or view – View is a pre-defined select query, considered a “virtual” table • Basic query typically has SELECT and FROM SELECT * FROM Titles
  • 7. Using SELECT • INTO – write results into table • DISTINCT – eliminate repeating value(s) or rows • AS – name or rename a table or column • * - include all fields from source
  • 8. INTO • Optional clause can write data from one or more tables into another (new) table • Typically used for – Archiving – To speed processing by creating temporary or summary tables – To organize for reporting SELECT pub_state INTO PublisherStates FROM Publishers
  • 9. DISTINCT • Distinct eliminates repeating rows or values – Used in SELECT clause SELECT DISTINCT Title FROM Titles Ensures that a title only is returned once, regardless of how may times a title is found SELECT DISTINCT pubid FROM Titles Lists each publisher in the titles table just once, regardless of number of books published
  • 10. AS • AS is used to create a field name for a calculation or to rename an existing field – Also referred to as an alias – Use is optional Rename fields in authors: SELECT au_lname AS LastName FROM Authors SELECT au_fname FirstName FROM Authors
  • 11. * • * represents all fields in data source – Results may differ from what‟s expected if fields are added, deleted or order changed SELECT * FROM Publishers
  • 12. Where • WHERE limits which rows are included in the result • Criteria evaluate to True/False – True means row will be used for result, false means row will be excluded – Sometimes „Predicates‟ is used in place of criteria (a predicate is a characteristic that‟s true about a row)
  • 13. Comparison Operators • Relational (=, >, <,<>,>=,<=) • Like – compares text patterns – Wildcards • One Character: _ (underscore) • Any combination: % • Between – compares to range • Is – compares true/false/null • In – value is in a list • Exists – whether there‟s a value
  • 14. Sample WHERE Clauses SELECT * FROM Titles WHERE Price > 20 SELECT au_Lname FROM Authors WHERE State <> „wa‟
  • 15. Logical Operators • If have more than one test use AND/OR to tie tests together – AND: All parts must evaluate to True for a row to be included – OR: Any part evaluating to True means a row is included – Precedence: NOT then AND then OR • NOT returns inverse – Not False returns True
  • 16. Logical Operator Examples SELECT * FROM Titles WHERE Price > 20 AND Title LIKE „%SQL%‟ SELECT * FROM Titles WHERE Not Contract
  • 17. Group By • Allows data from tables to be summarized – Find rows that share a common value • Can discover information about the group using aggregate functions – Count – Average – Max
  • 18. Sample Grouping • Count number of books by publisher: SELECT Count(*) BookCount, pub_id FROM titles GROUP BY pub_id • Count books by price SELECT Price, Count(*) AS BookCount FROM Titles GROUP BY Price
  • 19. Having • Determines which groups to include • Use Criteria similar to Where clause – Test characteristics of group using HAVING – Use WHERE to determine which rows to include
  • 20. Sample Having • Display publisher ID‟s of those publishers having more than 5 books published: SELECT pub_id FROM Titles GROUP BY pub_id HAVING Count(*) > 5
  • 21. Order By • Provides means to sort results by a column (actual or calculated) • Default sort order is Ascending ORDER BY pub_date ORDER BY au_lname DESC