Professional Documents
Culture Documents
-
Data Query with Select Statement
Author: TrungDVQ (Fsoft-Academy)
Fsoft-Academy - 2020
2
Lesson Objectives
3
SELECT
STATEMENT
SELECT syntax
SELECT
[ALL/DISTINCT/TOP [ WITH TIES ] ] SQL function/Operator
<Column name1>,
<Column name2>,..
List of columns in tables source.
FROM
<Table name1>,
<Table name2> List tables source.
…..
6/18/2021 12
SELECT
-- Select all column in Customers table
SELECT * FROM sales.customers
--
Select rows from a Table or View 'c
ustomers' in schema 'sales'
SELECT first_name, last_name, phone
FROM sales.customers
GO
SELECT and WHERE
SELECT
product_id,
product_name,
category_id,
I want information about model_year,
model_year from 2017 to 2019 list_price
and list_price more than 5500 FROM
production.products
WHERE
list_price >5500
AND
model_year BETWEEN 2017 and 2018
ALIAS
SQL Alias syntax:
For table
SELECT column_name(s)
FROM table_name AS alias_name
For Column(s)
SELECT column_name AS alias_name
FROM table_name
Ex:
USE BikeStores
GO
SELECT (c.first_name + ‘ ‘ + c.last_name ) AS ‘Họ và Tên’
c.first_name AS ‘Họ’,
c.last_name AS ‘Tên’,
c.phone AS ‘Số Điện Thoại’
FROM Sales.Customer AS c
SELECT TOP
SQL TOP syntax:
SELECT TOP (expression) [PERCENT]
[WITH TIES]
FROM table_name
ORDER BY column_name;
Ex:
USE BikeStores
GO
SELECT TOP 10
product_name, SELECT TOP 10 PERCENT
list_price product_name,
FROM list_price
FROM
production.products
production.products
ORDER BY ORDER BY
list_price DESC; list_price DESC;
SELECT TOP
SQL TOP syntax:
SELECT TOP (expression) [PERCENT]
[WITH TIES]
FROM table_name
ORDER BY column_name;
Ex:
USE BikeStores
GO
SELECT TOP 10 SELECT TOP 10 PERCENT
product_name, product_name,
list_price list_price
FROM FROM
production.products production.products
ORDER BY ORDER BY
list_price DESC; list_price DESC;
SELECT TOP
The WITH TIES allows you to return more rows with values that match the last row in the limited result set.
SELECT INTO
The SELECT INTO statement selects data from one table and inserts it into a different table.
Syntax:
SELECT * SELECT column_name(s)
INTO new_table_name INTO new_table_name
FROM old_tablename FROM table1;
Tip:
The SELECT INTO statement can also be used to create a new, empty table using the schema of
another. Just add a WHERE clause that causes the query to return no data:
SELECT *
INTO newtable
FROM table1
WHERE 1=0;
SELECT INTO
USE BikeStores
GO
SELECT (c.first_name + ' ' + c.last_name ) AS 'Họ và Tên' ,
c.first_name AS 'Họ',
c.last_name AS 'Tên',
c.phone AS 'Số Điện Thoại'
INTO CustomerList
FROM Sales.Customers AS c
SELECT *
FROM CustomerList
SQL Clause
21
What is Clause in SQL Server?
Basically, we use SQL Clause to apply filters for queries and thus get a filtered result.
5 Mand PR2 35
6 Jane IAI 54
Can DISTINCT on multiple columns ?
23
DISTINCT clause
24
DISTINCT Do it your self
List City exist in customer tables List all City and state exist in customer tables
25
Grouping by clause
Sometimes we want to apply aggregate functions to groups of rows.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
5 Mand PR2 35
Grades
6 Jane IAI 54
List City, state, zip_code exist in customer tables List all City and state exist in customer tables
27
DISTINCT is used to filter unique records out of the records that satisfy the
query criteria.
GROUP BY vs DISTINCT
The "GROUP BY" clause is used when you need to group the data and it
should be used to apply aggregate operators to each group.
28
Having clause
HAVING is like a WHERE clause, except that it applies to the results of a GROUP BY
query.
1 John DBS 76
6 Jane IAI 54
Use AVG()
function
30
6/18/2021
HAVING refers to the groups of rows, can use aggregate functions and cannot use
columns which are not in the GROUP BY
Ex:
Id Name SubjectID Mark
1 John DBS 76
SELECT Name,
AVG(Mark) AS Average
Group 2 John IAI 72
FROM Grades Name Average
3 Mary DBS 60 GROUP BY Name John 74
4 Mand PR1 63 ORDER BY Average DESC Mary 60
34
SQL Functions
An aggregate function performs a calculation on a set of values, and returns a single value.
Use aggregate functions as expressions only in the following situations:
The select list of a SELECT statement (either a subquery or an outer query).
A HAVING clause.
37
Aggregate Functions
Each function eliminates NULL values and operates on Non-NULL values
Aggregate functions are often used with the GROUP BY clause of the
SELECT statement.
Function Description
AVG () Return the average value in a column
SELECT
product_name,
MAX(list_price) max_list_price
FROM [production].[products]
GROUP BY product_name
HAVING MAX(list_price) > 1000
ORDER BY product_name,max_list_price DESC
39
Aggregate Functions - Do it your self with
Use MAX
and MIN
function
40
Having - Do it your self with
Find the customers who placed at least two orders per year
Use Count()
function
42
Section2
SCALAR FUNCTIONS
https://docs.microsoft.com/en-us/sql/t-sql/functions/functions?view=sql-server-ver15
Function Description
49
UNION Operator
The SQL UNION operator combines the result of two or more SELECT statements.
Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use
the ALL keyword with UNION.
SELECT Column1, Column2 FROM Table1 SELECT Column1, Column2 FROM Table1
UNION UNION ALL
SELECT Column1, Column2 FROM SELECT Column1, Column2 FROM
Table2; Table2;
50
6/18/2021
UNION Operator
ID SupplierName ContactName Address City
The Cast() function is used to convert a data type variable or data from one data
type to another data type.
The Cast() function provides a data type to a dynamic parameter (?) or a NULL
value.
56
Section4
DATE AND TIME FUNCTIONS
The GETDATE() function returns the current date and time from the SQL Server.
The DATEPART() function is used to return a single part of a date/time, such as
year, month, day, hour, minute, etc.
Syntax:
GETDATE()
DATEPART(datepart, date)
Ex : SELECT GETDATE()
SELECT DATEPART(YYYY, GETDATE())
60
DATEADD Function
The DATEADD() function adds or subtracts a specified time interval from a
date.
Syntax:
DATEADD(datepart,number,date)
Ex:
DECLARE @date1 DATETIME
DECLARE @date2 DATETIME
SET @date1= '2012-04-07 20:12:22.013'
SET @date2= '2014-02-27 22:14:10.013'
SELECT DATEDIFF(month, @date1, @date2) AS 'Month'
Result:
Syntax:
LTRIM (str)
RTRIM (str)
Syntax: LEN(str)
CHARINDEX ( expression1 ,expression2 [ , start_location ] )
PATINDEX ( '%pattern%' , expression )
Ex : SELECT CHARINDEX('bicycle',
Result: