• No results found

SQL Server: T-SQL Fundamentals. Long Hoang June 2020

N/A
N/A
Protected

Academic year: 2021

Share "SQL Server: T-SQL Fundamentals. Long Hoang June 2020"

Copied!
60
0
0

Loading.... (view fulltext now)

Full text

(1)

SQL Server:

T-SQL

Fundamentals

June 2020 Long Hoang

(2)

SQL Server: T-SQL Fundamentals

Lesson 2

(3)

Lesson Agenda

Restricting and Sorting Data

Using Single-Row Functions to Customize Output

Q&A

(4)

Restricting and Sorting Data

(5)

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.

(6)

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

(7)

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.

(8)

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

(9)

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.

(10)

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' ;

(11)

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.

(12)

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.

(13)

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';

(14)

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

(15)

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';

(16)

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%' ;

(17)

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;

(18)

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.

(19)

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:

(20)

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:

(21)

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

(22)

SELECT last_name, job_id, salary FROM employees

WHERE salary BETWEEN 10000 AND 15000

(23)

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

(24)

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.

(25)

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.”

(26)

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

(27)

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 ;

(28)

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.

(29)

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.

(30)

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.

(31)

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.

(32)

Lesson Agenda

Restricting and Sorting Data

Using Single-Row Functions to Customize Output

Q&A

(33)

Using Single-Row Functions to

Customize Output

(34)

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.

(35)

Agenda

• Single-row SQL functions

• Character functions

• Number functions

• Working with dates

• Date functions

(36)

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.

(37)

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”).

(38)

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

(39)

function. This can be represented by a column name or expression.

(40)

Single-Row Functions

Conversion

Character

Number

Date

General Single-row

functions

(41)

Agenda

• Single-row SQL functions

• Character functions

• Number functions

• Working with dates

• Date functions

(42)

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

(43)

Case-Conversion Functions

• These functions convert the case for character strings:

sql course LOWER('SQL Course')

SQL COURSE UPPER('SQL Course')

Result Function

(44)

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';

(45)

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’

(46)

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

(47)

Agenda

• Single-row SQL functions

• Character functions

• Number functions

• Working with dates

• Date functions

(48)

Sample

• ROUND: Rounds value to a specified decimal

• %: Returns remainder of division

1600%300 100

45.93 ROUND(45.926, 2)

Result Function

(49)

Using the ROUND Function

SELECT ROUND(45.923,2), ROUND(45.923,0),

ROUND(45.923,-1) 3

3

1 2

1 2

(50)

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.

(51)

Agenda

• Single-row SQL functions

• Character functions

• Number functions

• Working with dates

• Date functions

(52)

Using the GETDATE()Function

GETDATE

is a function that returns:

– Date – Time

SELECT GETDATE() AS SYSDATE

Using the GETDATE() Function

(53)

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:

(54)

From employees e

(55)

Agenda

• Single-row SQL functions

• Character functions

• Number functions

• Working with dates

• Date functions

(56)

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

(57)

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

(58)

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

(59)

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

Practice 3: Overview

This practice provides a variety of exercises using different functions that are

available for character, number, and date data types.

(60)

End of lesson 2

Q&A

References

Related documents

This research aims to identify the different theoretical approaches about the evaluation of the relationship between HRM and OP and the definition of a “bundle”

See select rows are skipped, sql server to skip header or query query wizard appears, google account and selecting the selection can neither be.. SQL select departmentid

Hazrat Zarar bin Auzar (radi Allahu anhu), another companion of the Holy Prophet (sallal laahu alaihi wasallam) says that he used to recite this Durood Shareef and fight with

No degree programs or more than four certificate programs (Commission policy does permit the institution to offer up to four certificate programs as well as a limited number

In rows inserted into statement on tables returns a different schemas you specify for example if needed by from sql select schema table a table with you create a procedural api...

COUNT(*) returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the

Collisions between railway vehicles and vehicles subject to insurance (road vehicles) shall be regulated by the road vehicle's insurance provider in the first instance.

Databases can insert a if in select statement sql select individual columns selected rows for case statement in simple update from the column value may differ from a specified