SQL Server:
T-SQL
Fundamentals
June 2020 Long Hoang
SQL Server: T-SQL Fundamentals
Lesson 2
Lesson Agenda
▪
Restricting and Sorting Data
▪
Using Single-Row Functions to Customize Output
▪
Q&A
Restricting and Sorting Data
Objectives
•
After completing unit 2 of this lesson, you should be able to do the 2
following:
–
Limit the rows that are retrieved by a query
–Sort the rows that are retrieved by a query
Objectives
When retrieving data from the database, you may need to do the following:
Restrict the rows of data that are displayed Specify the order in which the rows are displayed
This unit explains the SQL statements that you use to perform the actions
listed above.
Agenda
• Limiting rows with:
–
The WHERE clause
–
The comparison conditions using =, <=, BETWEEN, IN, LIKE, and NULL conditions
–
Logical conditions using AND, OR, and NOT operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
Limiting Rows Using a Selection
“retrieve all employees in department 90”
EMPLOYEES
…
Limiting Rows Using a Selection
In the example in the slide, assume that you want to display all the employees
in department 90. The rows with a value of 90 in the DEPARTMENT_ID
column are the only ones that are returned. This method of restriction is the
basis of the WHERE clause in SQL.
Limiting the Rows that Are Selected
• Restrict the rows that are returned by using the WHERE clause:
• The WHERE clause follows the FROM clause.
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table [WHERE condition(s)];
Limiting the Rows that Are Selected
You can restrict the rows that are returned from the query by using the WHERE clause. A WHERE clause contains a condition that must be met and it directly follows the FROM clause. If the condition is true, the row meeting the condition is returned.
In the syntax:
WHERE restricts the query to rows that meet a condition
condition is composed of column names, expressions, constants, and a comparison operator. A condition specifies a
combination of one or more expressions and logical (Boolean) operators, and returns a value of TRUE, FALSE, or UNKNOWN.
The WHERE clause can compare values in columns, literal, arithmetic expressions, or
Using the WHERE Clause
SELECT employee_id, last_name, job_id, department_id FROM employees
WHERE department_id = 90 ;
Using the WHERE Clause
In the example, the SELECT statement retrieves the employee ID, last name, job ID, and department number of all employees who are in department 90.
Note: You cannot use column alias in the WHERE clause.
Character Strings and Dates
SELECT last_name, job_id, department_id FROM employees
WHERE last_name = 'Whalen' ;
• Character strings and date values are enclosed with single quotation marks.
• Character values are case-sensitive and date values are format-sensitive.
SELECT last_name FROM employees
WHERE hire_date = '2000-01-24' ;
Comparison Operators
Not equal to
<>
Between two values (inclusive) BETWEEN
...AND...
Match any of a list of values IN(set)
Match a character pattern LIKE
Is a null value IS NULL
Less than
<
Less than or equal to
<=
Greater than or equal to
>=
Greater than
>
Equal to
=
Meaning Operator
Comparison Operators
Comparison operators are used in conditions that compare one expression to another value or expression. They are used in the WHERE clause in the following format:
Syntax
... WHERE expr operator value
Example
... WHERE hire_date = '01-JAN-95' ... WHERE salary >= 6000
... WHERE last_name = 'Smith'
An alias cannot be used in the WHERE clause.
Note: The symbols != and ^= can also represent the not equal to condition.
Using Comparison Operators
SELECT last_name, salary FROM employees WHERE salary <= 3000 ;
Using Comparison Operators
In the example, the SELECT statement retrieves the last name and salary
from the EMPLOYEES table for any employee whose salary is less than or
equal to $3,000. Note that there is an explicit value supplied to the WHERE
clause. The explicit value of 3000 is compared to the salary value in the
SALARY column of the EMPLOYEES table.
Range Conditions Using the BETWEEN Operator
SELECT last_name, salary FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;
• Use the BETWEEN operator to display rows based on a range of values:
Lower limit Upper limit
Range Conditions Using the BETWEEN Operator
You can display rows based on a range of values using the BETWEEN operator.
The range that you specify contains a lower limit and an upper limit.
The SELECT statement in the slide returns rows from the EMPLOYEES table for any employee whose salary is between $2,500 and $3,500.
Values that are specified with the BETWEEN operator are inclusive. However, you must specify the lower limit first.
You can also use the BETWEEN operator on character values:
SELECT last_name FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith';
Membership Condition Using the IN Operator
SELECT employee_id, last_name, salary, manager_id FROM employees
WHERE manager_id IN (100, 101, 201) ;
• Use the IN operator to test for values in a list:
Membership Condition Using the IN Operator
To test for values in a specified set of values, use the IN operator. The condition defined using the IN operator is also known as the membership condition.
The slide example displays employee numbers, last names, salaries, and managers’ employee numbers for all the employees whose manager’s employee number is 100, 101, or 201.
The IN operator can be used with any data type. The following example returns a row from the EMPLOYEES table, for any employee whose last name is included in the list of names in the WHERE clause:
SELECT employee_id, manager_id, department_id
FROM employees
Pattern Matching Using the LIKE Operator
SELECT first_name FROM employees
WHERE first_name LIKE 'S%' ;
• Use the LIKE operator to perform wildcard searches of valid search string values.
• Search conditions can contain either literal characters or numbers:
–
% denotes zero or many characters.
–
_ denotes one character.
Pattern Matching Using the LIKE Operator
You may not always know the exact value to search for. You can select rows that match a character pattern by using the LIKE operator. The character pattern–matching operation is referred to as a wildcard search. Two symbols can be used to construct the search string.
The SELECT statement in the slide returns the first name from the
EMPLOYEES table for any employee whose first name begins with the letter
“S.” Note the uppercase “S.” Consequently, names beginning with a lowercase
“s” are not returned.
The LIKE operator can be used as a shortcut for some BETWEEN
comparisons. The following example displays the last names and hire dates of all employees who joined between January, 1995 and December, 1995:
SELECT last_name, hire_date FROM employees
WHERE hire_date LIKE '%95';
Combining Wildcard Characters
• You can combine the two wildcard characters (%, _) with literal characters for pattern matching:
SELECT last_name FROM employees
WHERE last_name LIKE '_o%' ;
Using the NULL Conditions
SELECT last_name, manager_id FROM employees
WHERE manager_id IS NULL ;
• Test for nulls with the IS NULL operator.
Using the NULL Conditions
The NULL conditions include the IS NULL condition and the IS NOT NULL condition.
The IS NULL condition tests for nulls. A null value means that the value is unavailable, unassigned, unknown, or inapplicable. Therefore, you cannot test with =, because a null cannot be equal or unequal to any value. The slide example retrieves the last names and managers of all employees who do not have a manager.
Here is another example: To display the last name, job ID, and commission for all employees who are not entitled to receive a commission, use the following SQL statement:
SELECT last_name, job_id, commission_pct FROM employees
WHERE commission_pct IS NULL;
Defining Conditions Using the Logical Operators
Returns TRUE if the condition is false NOT
Returns TRUE if either component condition is true
OR
Returns TRUE if both component conditions are true
AND
Meaning Operator
Defining Conditions Using the Logical Operators
A logical condition combines the result of two component conditions to produce a single result based on those conditions or it inverts the result of a single condition. A row is returned only if the overall result of the condition is true.
Three logical operators are available in SQL:
•
AND
•
OR
•
NOT
All the examples so far have specified only one condition in the WHERE
clause. You can use several conditions in a single WHERE clause using the AND
and OR operators.
Using the AND Operator
SELECT employee_id, last_name, job_id, salary FROM employees
WHERE salary >= 10000 AND job_id LIKE '%MAN%' ;
• AND requires both the component conditions to be true:
Using the AND Operator
In the example, both the component conditions must be true for any record to be selected. Therefore, only those employees who have a job title that
contains the string ‘MAN’ and earn $10,000 or more are selected.
All character searches are case-sensitive, that is no rows are returned if ‘MAN’
is not uppercase. Further, character strings must be enclosed with quotation marks.
AND Truth Table
The following table shows the results of combining two expressions with AND:
Using the OR Operator
• OR requires either component conditions to be true:
SELECT employee_id, last_name, job_id, salary FROM employees
WHERE salary >= 10000 OR job_id LIKE '%MAN%' ;
Using the OR Operator
In the example, either component condition can be true for any record to be selected. Therefore, any employee who has a job ID that contains the string
‘MAN’ or earns $10,000 or more is selected.
OR Truth Table
The following table shows the results of combining two expressions with OR:
Using the NOT Operator
SELECT last_name, job_id FROM employees WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
Using the NOT Operator
The slide example displays the last name and job ID of all employees whose job ID is not IT_PROG, ST_CLERK, or SA_REP.
NOT Truth Table
The following table shows the result of applying the NOT operator to a condition:
Note: The NOT operator can also be used with other SQL operators, such as BETWEEN, LIKE, and NULL.
... WHERE job_id NOT IN ('AC_ACCOUNT', 'AD_VP') ... WHERE salary NOT BETWEEN 10000 AND 15000 ... WHERE last_name NOT LIKE '%A%'
... WHERE commission_pct IS NOT NULL Example:
SELECT last_name, job_id, salary
FROM employees
SELECT last_name, job_id, salary FROM employees
WHERE salary BETWEEN 10000 AND 15000
Agenda
• Limiting rows with:
- The WHERE clause
- The comparison conditions using =, <=, BETWEEN, IN, LIKE, and NULL conditions
- Logical conditions using AND, OR, and NOT operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
Rules of Precedence
You can use parentheses to override rules of precedence.
Not equal to 6
NOT logical condition 7
AND logical condition 8
OR logical condition 9
IS [NOT] NULL, LIKE, [NOT] IN 4
[NOT] BETWEEN 5
Comparison conditions 3
Concatenation operator 2
Arithmetic operators 1
Meaning Operator
Rules of Precedence
The rules of precedence determine the order in which expressions are
evaluated and calculated. The table in the slide lists the default order of
precedence. However, you can override the default order by using
parentheses around the expressions that you want to calculate first.
Rules of Precedence
SELECT last_name, job_id, salary FROM employees
WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000;
SELECT last_name, job_id, salary FROM employees
WHERE (job_id = 'SA_REP' OR job_id = 'AD_PRES') AND salary > 15000;
1
2
Rules of Precedence (continued)
1. Precedence of the AND Operator: Example In this example, there are two conditions:
The first condition is that the job ID is AD_PRES and the salary is greater than
$15,000.
The second condition is that the job ID is SA_REP.
Therefore, the SELECT statement reads as follows:
“Select the row if an employee is a president and earns more than $15,000, or if the employee is a sales representative.”
2. Using Parentheses: Example
In this example, there are two conditions:
The first condition is that the job ID is AD_PRES or SA_REP.
The second condition is that the salary is greater than $15,000.
Therefore, the SELECT statement reads as follows:
“Select the row if an employee is a president or a sales representative, and if the
employee earns more than $15,000.”
Agenda
• Limiting rows with:
- The WHERE clause
- The comparison conditions using =, <=, BETWEEN, IN, LIKE, and NULL conditions
- Logical conditions using AND, OR, and NOT operators
• Rules of precedence for operators in an expression
• Sorting rows using the ORDER BY clause
Using the ORDER BY Clause
• Sort retrieved rows with the ORDER BY clause:
–
ASC: Ascending order, default
–DESC: Descending order
• The ORDER BY clause comes last in the SELECT statement:
SELECT last_name, job_id, department_id, hire_date FROM employees
ORDER BY hire_date ;
…
Sorting
• Sorting in descending order:
• Sorting by column alias:
SELECT last_name, job_id, department_id, hire_date FROM employees
ORDER BY hire_date DESC ;
1
SELECT employee_id, last_name, salary*12 annsal FROM employees
ORDER BY annsal ;
2
Sorting (continued) Examples:
3. You can sort query results by specifying the numeric position of the column in the SELECT clause. The slide example sorts the result by the
department_id as this column is at the third position in the SELECT clause.
4. You can sort query results by more than one column. The sort limit is the
number of columns in the given table. In the ORDER BY clause, specify the
columns and separate the column names using commas. If you want to
reverse the order of a column, specify DESC after its name.
Sorting
• Sorting by using the column’s numeric position:
• Sorting by multiple columns:
SELECT last_name, job_id, department_id, hire_date FROM employees
ORDER BY 3;
3
SELECT last_name, department_id, salary FROM employees
ORDER BY department_id, salary DESC;
4
Sorting (continued) Examples:
3. You can sort query results by specifying the numeric position of the column in the SELECT clause. The slide example sorts the result by the
department_id as this column is at the third position in the SELECT clause.
4. You can sort query results by more than one column. The sort limit is the
number of columns in the given table. In the ORDER BY clause, specify the
columns and separate the column names using commas. If you want to
reverse the order of a column, specify DESC after its name.
Summary
• In unit 2 of this lesson, you should have learned how to:
–
Use the WHERE clause to restrict rows of output:
• Use the comparison conditions
• Use the BETWEEN, IN, LIKE, and NULL operators
• Apply the logical AND, OR, and NOT operators
–
Use the ORDER BY clause to sort rows of output:
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table [WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]] ;
Summary
In unit 2 of this lesson, you should have learned about restricting and sorting rows that are returned by the SELECT statement. You should also have learned how to implement various operators and conditions.
By using the substitution variables, you can add flexibility to your SQL
statements. This enables the queries to prompt for the filter condition for the
rows during run time.
Practice 2: Overview
• This practice covers the following topics:
–
Selecting data and changing the order of the rows that are displayed
–Restricting rows by using the WHERE clause
–
Sorting rows by using the ORDER BY clause
Practice 2: Overview
In this practice, you build more reports, including statements that use the
WHERE clause and the ORDER BY clause. You make the SQL statements more
reusable and generic by including the ampersand substitution.
Lesson Agenda
▪
Restricting and Sorting Data
▪
Using Single-Row Functions to Customize Output
▪
Q&A
Using Single-Row Functions to
Customize Output
Objectives
• After completing unit 3 of this lesson, you should be able to do the 3
following:
–
Describe various types of functions available in SQL
–
Use character, number, and date functions in SELECT statements
Objectives
Functions make the basic query block more powerful, and they are used to
manipulate data values. This is the first unit that explore functions. It focuses
on single-row character, number, and date functions.
Agenda
• Single-row SQL functions
• Character functions
• Number functions
• Working with dates
• Date functions
SQL Functions
Function Input
arg 1 arg 2
arg n
Function performs action
Output
Result value
SQL Functions
Functions are a very powerful feature of SQL. They can be used to do the following:
Perform calculations on data Modify individual data items
Manipulate output for groups of rows Format dates and numbers for display Convert column data types
SQL functions sometimes take arguments and always return a value.
Two Types of SQL Functions
Single-row functions
Multiple-row functions Return one result
per row
Return one result per set of rows Functions
Two Types of SQL Functions
There are two types of functions:
Single-row functions Multiple-row functions Single-Row Functions
These functions operate on single rows only and return one result per row.
There are different types of single-row functions. This unit covers the following ones:
Character Number Date Conversion General
Multiple-Row Functions
Functions can manipulate groups of rows to give one result per group of rows.
These functions are also known as group functions (covered in the unit of
lesson 3 titled “Reporting Aggregated Data Using the Group Functions”).
Single-Row Functions
• Single-row functions:
–
Manipulate data items
–
Accept arguments and return one value
–Act on each row that is returned
–
Return one result per row
–May modify the data type
–Can be nested
–
Accept arguments that can be a column or an expression
function_name [(arg1, arg2,...)]
Single-Row Functions
Single-row functions are used to manipulate data items. They accept one or more arguments and return one value for each row that is returned by the query. An argument can be one of the following:
User-supplied constant Variable value
Column name Expression
Features of single-row functions include:
Acting on each row that is returned in the query Returning one result per row
Possibly returning a data value of a different type than the one that is
function. This can be represented by a column name or expression.
Single-Row Functions
Conversion
Character
Number
Date
General Single-row
functions
Agenda
• Single-row SQL functions
• Character functions
• Number functions
• Working with dates
• Date functions
Character Functions
Character functions
LOWER UPPER CAST CONVERT
CONCAT SUBSTRING LEN CHARINDEX LTRIM/RTRIM REPLACE Case-conversion
functions
Character-manipulation functions
Character Functions
Single-row character functions accept character data as input and can return both character and numeric values. Character functions can be divided into the following:
Case-conversion functions
Character-manipulation functions
Case-Conversion Functions
• These functions convert the case for character strings:
sql course LOWER('SQL Course')
SQL COURSE UPPER('SQL Course')
Result Function
Using Case-Conversion Functions
SELECT employee_id, last_name, department_id FROM employees
WHERE LOWER(last_name) = 'higgins';
• Display the employee number, name, and department number for employee Higgins:
SELECT employee_id, last_name, department_id FROM employees
WHERE last_name = 'higgins';
Character-Manipulation Functions
• These functions manipulate character strings:
BLACK and BLUE REPLACE
('JACK and JUE','J','BL')
10 LEN('HelloWorld')
6 CHARINDEX(‘W’,'HelloWorld')
HelloWorld CONCAT('Hello', 'World')
Hello SUBSTRING('HelloWorld',1,5)
Result Function
- CONCAT(string1, string 2…string n) -> SELECT CONCAT('Toan', ' ', 'Ly', ' ', 'Hoa'); ->
Return: Toan Ly Hoa‘
- SUBSTRING(string, start, length) -> SELECT SUBSTRING('HomNayTroiDep', 1, 4); ->
Return: ‘HomN’
- SELECT REPLACE('SQL Sutorial', 'Su', 'Tu'); -> Return: ‘SQL Tutorial’
Using the Character-Manipulation Functions
SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LEN(last_name),
CHARINDEX(‘a’,last_name) "Contains 'a'?"
FROM employees
WHERE SUBSTRING(job_id, 4,LEN(job_id)) = 'REP';
2
3
1 2
1
3
Agenda
• Single-row SQL functions
• Character functions
• Number functions
• Working with dates
• Date functions
Sample
• ROUND: Rounds value to a specified decimal
• %: Returns remainder of division
1600%300 100
45.93 ROUND(45.926, 2)
Result Function
Using the ROUND Function
SELECT ROUND(45.923,2), ROUND(45.923,0),
ROUND(45.923,-1) 3
3
1 2
1 2
Using the ROUND Function
SELECT last_name, salary, salary%5000 FROM employees
WHERE job_id = 'SA_REP';
• For all employees with the job title of Sales Representative, calculate the remainder of the salary after it is divided by 5,000.
Using the MOD Function
The MOD function finds the remainder of the first argument divided by the second argument. The slide example calculates the remainder of the salary after dividing it by 5,000 for all employees whose job ID is SA_REP.
Note: The MOD function is often used to determine whether a value is odd or
even.
Agenda
• Single-row SQL functions
• Character functions
• Number functions
• Working with dates
• Date functions
Using the GETDATE()Function
• GETDATE
is a function that returns:– Date – Time
SELECT GETDATE() AS SYSDATE
Using the GETDATE() Function
Arithmetic with Dates
• Add or subtract a number to or from a date for a resultant date value.
• Subtract two dates to find the number of days between those dates.
• Add hours to a date by dividing the number of hours by 24.
Note:
- Arithmetic operations using the + and - operators are supported with Date/Time types but the general recommendation is to use the DATE_ADD and
DATE_SUB functions to get the same results.
- -> SELECT GETDATE()-1, GETDATE()+1, GETDATE()-7;
- The DATEADD function simply allows you to add or subtract the specified number of units of time to a specified date/time value.
- Arithmetic with Dates -> query is wrong with SQL 2016
Because the database stores dates as numbers, you can perform calculations using arithmetic operators such as addition and subtraction. You can add and subtract number constants as well as dates.
You can perform the following operations:
Example:
From employees e
Agenda
• Single-row SQL functions
• Character functions
• Number functions
• Working with dates
• Date functions
Date-Manipulation Functions
Returns the number of date or time datepart boundaries that are crossed between two specified dates.
DATEDIFF( datepart , startdate , enddate )
Return a new datetime value by adding an interval to the specified datepart of the specified date
DATEADD(datepart , number , date )
Result Function
DAY(date) MONTH(date)
YEAR(date) Return year part of a specified date.
Return day part of a specified date.
Return year part of a specified date.
datepart: dd or mm or yy or ww
Using Date Functions
----Last Day of Previous Month
SELECT DATEADD(dd,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE()),0)) ----Last Day of Current Month
SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) ----Last Day of Next Month
SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
Check sql command for Date Functions
Select DATEDIFF(mm,0,GETDATE()) – compare and get the current month select DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0) – get the current month with initial day of current month
SELECT DATEADD(dd,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))
0 -> representative for default start date in SQL Server 1-1-1900
Summary
• In unit 3 of this lesson, you should have learned how to:
–
Perform calculations on data using functions
–Modify individual data items using functions
Practice 3: Overview
• This practice covers the following topics:
– Writing a query that displays the current date
– Creating queries that require the use of numeric, character, and date functions
– Performing calculations of years and months of service for an employee