Practice Topics
- Basic SELECT statements
- Sorting with ORDER BY
- Alias Names
- Filtering using the WHERE statement
- Common Types of Filters
- OR vs. AND
- Using AND and OR Together with Parentheses
Basic SELECT Statements
Overview
The SELECT
statement is used to identify the fields that you wish to view in the query output. Let’s say that one table has 50 fields. If you want to view 10 of the 50 fields, you list them in this portion of the query. As you will find out later in this book, you will also perform mathematical and other functions in this section of the query. If you want to see every field in your output, use SELECT *
.
The FROM
statement is used to identify the tables that the query output will be selected from. This could include one or more tables. Tables are connected by joining on common fields. This topic will be discussed later.
Each table used will be listed below the word FROM
and will contain three components: the database name
, the schema name
, and the table name
. A database
may be made up of a couple of tables or hundreds of tables. A schema
sits within a database
and is used to organize similar groups of tables. A table
is used to store rows and columns (similar to a table in an Excel file).
The syntax is as follows: FROM [Database Name].[Schema Name].[Table Name]
Example: Display a person’s Title
, FirstName
, MiddleName
and LastName
from the AdventureWorks2019.Person.Person
table.
SELECT Title, FirstName, MiddleName, LastName FROM AdventureWorks2019.Person.Person;
Self Practice
- Write a query to select all columns from the
AdventureWorks2019.Person.Person
table. - Write a query to select only the
FirstName
,LastName
, andBusinessEntityID
from theAdventureWorks2019.Person.Person
table.
SELECT * FROM AdventureWorks2019.Person.Person;
SELECT FirstName, LastName, BusinessEntityID FROM AdventureWorks2019.Person.Person;
Sorting with ORDER BY
Overview
The ORDER BY
clause allows us to sort a dataset by any number of columns in ascending
or descending
order.
At the very end of a query, you can accomplish this by adding ORDER BY column1, column2
, etc. Ascending
order is the default. If you want a column to be sorted in descending
order, you can add DESC
after the column name. For example, ORDER BY column1, column2 DESC
. In this case, column1
will come in ascending
order and column column2
will come in descending
order.
Example: Display a person’s Title
, FirstName
, MiddleName
and LastName
from the AdventureWorks2019.Person.Person
table then sort by LastName descending
then FirstName ascending
.
SELECT Title, FirstName, MiddleName, LastName FROM AdventureWorks2019.Person.Person ORDER BY LastName DESC, FirstName;
Self Practice
- Write a query to select all columns from the
AdventureWorks2019.Sales.Customer
table, ordered byCustomerID
in descending order. - Write a query to select
ProductID
,Name
, andListPrice
from theAdventureWorks2019.Production.Product
table, ordered byListPrice
in ascending order.
SELECT * FROM AdventureWorks2019.Sales.Customer ORDER BY CustomerID DESC;
SELECT ProductID, Name, ListPrice FROM AdventureWorks2019.Production.Product ORDER BY ListPrice ASC;
Alias Names
Overview
Alias names
are just like when a person has an alias name
. It means that we can call a column
or table
something else.
Why would we want to call a column
or table
something else?
-
Each
column
shown in theSELECT
statement lives in adatabase table
. Therefore, we need thedatabase table
name listed before eachcolumn
in ourSELECT
statement. Without it, the query won’t know whichtable
to pull eachcolumn
from. When we reference atable
in ourSELECT
statement, writingA
before eachcolumn
from theA
table is a hell of a lot easier than writingDatabaseName.SchemaName.TableName
before eachcolumn
. -
We sometimes need to
rename columns
because database naming conventions aren’t always clean. -
When we create formulas on
columns
(in theSELECT
statement), we need to specify acolumn name
in our output.
It is very important to note that while you can reference a table alias name
anywhere in a query, you are only able to reference a column alias name
in the ORDER BY
.
The syntax for a table alias
is: DatabaseName.SchemaName.TableName TableAliasName
.
The syntax for a column alias
is: TableAliasName.ColumnName as ColumnAliasName
.
Example: Alias name
the AdventureWorks2019.Person.Person
table as A
and in the SELECT
statement, alias name
the FirstName
as FName
, MiddleName
as MName
, and LastName
as LName
.
SELECT A.FirstName as FName, A.MiddleName as MName, A.LastName as LName FROM AdventureWorks2019.Person.Person A;
Self Practice
- Write a query to select
FirstName
andLastName
from theAdventureWorks2019.Person.Person
table with column aliasesFN
andLN
, respectively. - Write a query to select
Name
andListPrice
from theAdventureWorks2019.Production.Product
table with column aliasesProductName
andPrice
, respectively. - Write a query to select
Name
andListPrice
from theAdventureWorks2019.Production.Product
table with column aliasesProductName
andPrice
, respectively. In addition, give theAdventureWorks2019.Production.Product
table an alias name ofa
. Be sure to attach the table’s alias name to theName
andListPrice
fields.
SELECT FirstName AS FN, LastName AS LN FROM AdventureWorks2019.Person.Person;
SELECT Name AS ProductName, ListPrice AS Price FROM AdventureWorks2019.Production.Product;
SELECT a.Name AS ProductName, a.ListPrice AS Price FROM AdventureWorks2019.Production.Product a;
Filtering Using the WHERE Statement
Overview
Filtering
is one of the most important aspects of a SQL query. Filtering
is as simple as it sounds. It’s just a way to eliminate unwanted records
from your query results. When you are in the learning stages of writing SQL queries, I highly recommend that you write on a separate sheet of paper each of the tables
that you plan to use in your query then think through every single filter
and list them for each table
. If you miss even one filter, you can possibly return millions of unwanted records.
Filters
use standard operators
such as =
, <>
, >
, <
, in
, like
, between
.
You can include as many filters
as you need, just separate them by AND
or OR
. If you use OR
, please consider order of operations and use () at the beginning and end of the OR statement(s).
Common uses of filters
in WHERE
clause:
- Eliminate unwanted records (ex. old records, irrelevant records, etc.).
- Limit to specific date ranges.
- Limit to specific status codes.
Example: Filter
our AdventureWorks2019.Person.Person
table to anyone with a PersonType
equal to EM
(aka. ‘Employee’), a FirstName
of Michael
, and a ModifiedDate
in 2009
.
SELECT A.FirstName as FName, A.MiddleName as MName, A.LastName as LName FROM AdventureWorks2019.Person.Person A WHERE A.PersonType = 'EM' AND A.FirstName = 'Michael' AND A.ModifiedDate between '2009-01-01' and '2009-12-31';
Self Practice
- Write a query to select all products from the
AdventureWorks2019.Production.Product
table where theColor
is ‘Black’. - Write a query to select all employees from the
AdventureWorks2019.HumanResources.Employee
table who were hired after January 1, 2005.
SELECT * FROM AdventureWorks2019.Production.Product WHERE Color = 'Black';
SELECT * FROM AdventureWorks2019.HumanResources.Employee WHERE HireDate > '2005-01-01';
Common Types of Filters
Overview
As mentioned in the previous section, filtering
is extremely important. This section highlights some of the most common operators
to be used in filters
. Note – this list is not comprehensive as there could be other types of operators
.
In a filter
, you can compare fields against other fields, fields against fixed/hard-coded values, and fields against calculations (ex. date look backs). Note – Ensure that you are using the same data types
; otherwise, you will get a data type conversion error. For example, you can’t filter a string field by a number/date value.
Example: The below query shows filtering
of the AdventureWorks2019.Sales.SalesOrderDetail
table using operators
such as equal to
, greater than
, less than
and not equal to
. This is just for reference, try running the query with one filter at a time so you can see each filter’s behavior.
SELECT A.SalesOrderID, A.SalesOrderDetailID, A.CarrierTrackingNumber, A.OrderQty, A.ProductID, A.SpecialOfferID, A.UnitPrice, A.UnitPriceDiscount, A.LineTotal, A.rowguid, A.ModifiedDate FROM AdventureWorks2019.Sales.SalesOrderDetail A WHERE A.OrderQty = 5 -- Equal to OR A.OrderQty > 5 -- Greater than OR A.OrderQty >= 5 -- Greater than or equal to OR A.OrderQty < 5 -- Less than OR A.OrderQty <= 5 -- Less than or equal to OR A.OrderQty <> 5 -- Not equal to;
Example: The below query shows filtering
using operators
such as:
IN
: Return records where astring
ornumber
exists within aspecified list of possible values
.LIKE
: Return records where astring
has apartial match on a specified set of characters
: ex. %before
a specified string means any character(s) may existbefore the specified string
. %after
a specified string means any character(s) may existafter the specified string
. %before
andafter
a specified string means any character(s) may exist beforeOR
after the specified string.BETWEEN
: Return records where adate
,string
, ornumber
fallswithin a specified range
: ex. return all records where a date value fallsbetween a range of dates
.
SELECT A.PersonType as [Person Type], -- Use brackets when you want to include a space in your alias name, A.Title as Title, A.FirstName as [First Name], A.MiddleName as [Middle Name], A.LastName as [Last Name], A.ModifiedDate FROM AdventureWorks2019.Person.Person A WHERE A.FirstName IN ('Thomas','Michael','Mary') -- FirstName is either Thomas, Michael or Mary OR A.ModifiedDate BETWEEN '2009-01-01' AND '2009-12-31' -- ModifiedDate falls anywhere between Jan 1, 2009 and Dec 31, 2009 OR A.LastName LIKE '%ra%' -- Lastname contains 'ra' with any characters falling before OR after 'ra';
Self Practice
- Write a query to select all products from the
AdventureWorks2019.Production.Product
table where theListPrice
is greater than 1000. - Write a query to select all employees from the
AdventureWorks2019.HumanResources.Employee
table where theJobTitle
is ‘Production Technician – WC60’.
SELECT * FROM AdventureWorks2019.Production.Product WHERE ListPrice > 1000;
SELECT * FROM AdventureWorks2019.HumanResources.Employee WHERE JobTitle = 'Production Technician - WC60';
OR vs. AND
Overview
A very important (sometimes overlooked) aspect of filtering
is understanding the syntax associated with OR
and AND
. Just like a calculator in math class, SQL might not always process things in the order that you desire so your syntax needs to be specific. It’s very simple, just use parentheses.
Example: Show anyone from the AdventureWorks2019.Person.Person
table with a LastName
that contains
the string MI
or
TH
. Please only include employees by returning PersonType
values equal to EM
. Don’t use parentheses for order of operations yet. You will do this in the next example to see the difference.
SELECT A.PersonType as [Person Type], A.Title as Title, A.FirstName as [First Name], A.MiddleName as [Middle Name], A.LastName as [Last Name], A.ModifiedDate as [Modified Date] FROM AdventureWorks2019.Person.Person A WHERE A.lastName LIKE '%mi%' OR A.lastName LIKE '%th%' AND A.PersonType = 'EM';
Example: Show anyone from the AdventureWorks2019.Person.Person
table with a LastName
that contains
the string MI
or
TH
. Please only include employees by returning PersonType
values equal to EM
. Now, use parentheses around the two LastName
filters for order of operations. Everything else about the query remains the same as the prior example. You will see different results with the parentheses applied.
SELECT A.PersonType as [Person Type], A.Title as Title, A.FirstName as [First Name], A.MiddleName as [Middle Name], A.LastName as [Last Name], A.ModifiedDate as [Modified Date] FROM AdventureWorks2019.Person.Person A WHERE ( A.lastName LIKE '%mi%' OR A.lastName LIKE '%th%' ) AND A.PersonType = 'EM';
Self Practice
- Write a query to select all products from the
AdventureWorks2019.Production.Product
table where theColor
is ‘Black’ OR theListPrice
is greater than 1000. - Write a query to select all products from the
AdventureWorks2019.Production.Product
table where theColor
is ‘Black’ AND theListPrice
is greater than 1000.
SELECT * FROM AdventureWorks2019.Production.Product WHERE Color = 'Black' OR ListPrice > 1000;
SELECT * FROM AdventureWorks2019.Production.Product WHERE Color = 'Black' AND ListPrice > 1000;
Using AND and OR Together with Parentheses
- Write a query to select all products from the
Production.Product
table where theColor
is ‘Black’ AND theListPrice
is greater than 1000 OR theProductLine
is ‘T’ (indicating Touring products). Ensure proper use of parentheses to correctly group the conditions.
SELECT * FROM AdventureWorks2019.Production.Product WHERE ( Color = 'Black' AND ListPrice > 1000 ) OR ProductLine = 'T';
Conclusion
As we wrap up this week’s SQL homework assignments, we’ve delved into the foundational aspects of SQL, including basic SELECT
statements, filtering with WHERE
clauses, ordering results with ORDER BY
, using aliases, and understanding the nuances of AND
versus OR
conditions. These exercises are designed to build your confidence and proficiency in SQL, equipping you with the skills necessary for more advanced queries in the future.
Remember, consistent practice is key to mastering SQL. If you find yourself needing extra help or wanting to deepen your understanding, don’t hesitate to sign up for our private or group training sessions. These sessions offer personalized guidance and a collaborative learning environment to further enhance your SQL skills. Stay tuned for next week’s assignments, and keep pushing your boundaries as you continue on your journey to becoming an SQL expert!