Vous êtes sur la page 1sur 12

PG 8-10

SQL server
1. Single logical entity backed by multiple physical files
2. Support 2 type of databases
o System
o User
E.g. TSQL (use to write queries)
3. Client server system
o Contain both client software (mgmt. & visual studio) & database
engine
o Client software send request to database engine via T-SQL statements,
then SQL server process request to database engine (client not directly
access to database file)
4. Queries
o Set-based language- pull data from server one table/subset table at a
time
5. T-SQL scripts
o Each script ordered into batches, then marked with GO
6. Required items to connect server
o Instance name
o Database name
o authentication
7. Object Explorer
o graphical tool for managing SQL server instances and databases
8. SSMS (SQL Server Management Studio)
o for configuring, managing, and administering all components within
Microsoft SQL Server
o Allow create and save T-SQL code in text files
o Allow open edit and execute code in script file directly

T-SQL
1. Format
o Declarative language to describe the desired data to display, not how
to retrieve data
2. Statement Categories
o Data Manipulation Language (DML)
Purpose: Data manipulation - querying and modify data (SELECT,
UPDATE, DELETE)
o Data Definition Language (DDL)
Purpose: define data - create, modify, and remove database
objects such as tables, indexes, and users (CREATE, ALTER,
DROP)
o Data Control Language (DCL)
Data control/security-manage security permission for users and
objects (GRANT, REVOKE, DENY)
PG 8-10

3. Language Elements
o Predicate & Operator
Comparison (BETWEEN), mathematical (+/-), validate condition
(AND, OR, NOT) etc
Property/express thats either true or false
referred as Boolean expression
o Functions
Date, Aggregate, math, string functions
o Variables
o Expressions
o Batch Separators
this single line will be ignored:
*/this paragraph will be ignored*/
o Control of Flow
o Comments

Set

Mathematical basis for relational database


A set collection of distinct objects considered as a whole
Rule apply to queries
o At on whole set at once
query whole table at once
o Declarative, set based processing
Tell engine what to retrieve
o Addressing elements via unique identifier (e.g. keys)
o Provide sorting instruction

Statements & Characteristics

Logical Orders in writing


o Select, from, where, group by, having, order by
Logical order Server processing
o From, where, group by, having, select, order by
1. From Command
a. IBM has 4 names
b. E.g. sever name, database name, schema (=directory)name, table
name
2. Where command
a. Column=option 1
b. Column IS NULL
c. Column IN (option1, option 2)
3. Distinct
a. Remove duplicate data
b. Function wont work if has multiple columns to look up
c. Function: SELECT DISTINCT column name
PG 8-10

4. Aliases
a. Relabel columns
b. Improve readability and save redundancy
c. Function: SELECT column1, column 2 AS desire displayed name
d. Or function 2: SELECT column1 desired display name (only allow one
word in display name in this function)
5. Case
a. Return a single value
b. Simple CASE vs. Search CASE
i. Simple compare value to a list of possible values
ii. Searched evaluates a set of predicates/logical expressions
iii. Function: SELECT column, case column 2, then desired name,
else unknown
6. Top
a. Function: SELECT TOP 10 column list
b. Can be combine with TIE option will see more rows same as the last
result based on order by subject
7. Null
a. Function: WHERE XX IS NULL
PG 8-10

Method to Connect Tables (in query, view, select)


A. Set joins used tables from different computers/locations
1) Union
i. Combine all data
2) Intercept
i. Find common data (e.g. find out which item every store is
selling)
3) Except/minus
i. Find differences
B. Equi-joins used tables from SAME computer
1) Inner (default)
i. Find matches
ii. System default
iii. ANSI 89 Old method writing JOIN statement
1. Use , to separate tables in FROM statement, WHERE
iv. ANSI 92 New method writing JOIN statement
1. Use JOIN in the FROM statement ,ON =

2) Outer
i. Find missing data (e.g. Find out which customer hasnt use their
account in years)
1. Left look at the left side of table
2. Right look at right side of table
3. Full look at all tables
ii. Same as above ANSI-92, add left outer join or right outer join in
from statement
3) Cross / Cartesian combine data from unrelated tables (e.g. colors and
cars)
i. Function: FROM table name el CROSS JOIN second table name
4) Self compare values of 2 rows from the same table (e.g. manager vs.
workers)
i. At least one alias is required
ii. Function : FROM one table AS alias JOIN second table AS alias
ON alias1 id= alias2 id

C. Nested joins/Subqueries
1) Correlated (super slow)
2) Non-correlated
SQL Part of Select to Show Data

Function Meaning Example


Select xx,xx Pick Columns select.* from customer#
(.*=all records)
From xx, xx Pick Tables from customers
Where xx, xx Pick records (Specific where city=Calgary
Record)
Group by xx, xx Identify (which) columns group by item#
show totals
PG 8-10

Having xx Pick total having sum(quantity)


>10,000
Order by xx, xx Sort data by column order by street
data types may be converted when querying SQL Serve when:
When data is moved, compared, or combined with other data
During variable assignment
When using any operator that involves two operands of different types
When T-SQL code explicitly converts one type to another, using a CAST or
CONVERT function

Collation
Supported languages
Sort order
Case sensitivity
Accent sensitivity

Concatenate
join together, two strings
FORMAT()
SUBSTRING()
LEFT() and RIGHT() for returning the leftmost or rightmost characters
LEN() and DATALENGTH() for providing metadata about the number of characters or number of
bytes stored in a string.
CHARINDEX() for returning a number representing the position of a string within another string
REPLACE() for substituting one set of characters with another set within a string
UPPER() and LOWER() for performing case conversions
The LIKE predicate allows you to check a character string against a pattern
% (Percent) represents a string of any length. For example, LIKE N'Sand%' will match 'Sand',
'Sandwich', 'Sandwiches', etc.
_ (Underscore) represents a single character. For example, LIKE N'_a' will match any string
whose
second character is an 'a'.
[<List of characters>] represents a single character within the supplied list. For example,
LIKE
N'[DEF]%' will find any string that starts with a 'D', an 'E', or an 'F'.
[<Character> - <character>] represents a single character within the specified range. For
example,
LIKE N'[N-Z]%' will match any string that starts with any letter of the alphabet between N and Z,
inclusive.
[^<Character list or range>] represents a single character not in the specified list or range.
For
example, LIKE N'^[A]% will match a string beginning with anything other than an 'A'.
ESCAPE Character allows you to search for a character that is also a wildcard character. For
example,
LIKE N'10% off%' ESCAPE '%' will find any string that starts with 10%, including the literal
character
'%'.
[CAST] covert from one data type to another, use select & whereclauses
PG 8-10

[CONVERT] same as [CAST], not ANSI standard


[ISNUMERIC] validate data type, true=1, otherwise=0
[IIF] test if condition is true, false or unknown
[CHOOSE] return an item from a list as specified
[ISNULL] way to treat null value, covert null value to specify condition (not ASNI)
[COALESCE] way to treat null value, covert null value to specify condition (ASNI)

literals, which are delimited with single quotes

insert select insert set of rows returned by a select query into a destination table
insert exe-c
select into
create and populate new table with select query
cant insert rows in an existing table
insert values
[update] with where clause
[merge into]
[Delete] remove row from specific table
Truncate delete function, data cannot be retrieve once activated
[identity] auto number and increment a field (x,x)
[create sequence] oracle command , same as [identity]

Scalar functions
operate on a single element and result return as single value
organized into conversion, string, logical, math
use select clause
Aggregate functions
group by clause
max, min, avg etc
Window functions (?)
use over clause
perform calculation against user-defined set of rows
Rowset function
return a virtual table that can be used elsewhere in query and take parameters specific to
the rowset function itself
Explicit converstion
use when implicit conversion fail or not permit
override a precedence
use function: CAST or COVERT

Aggregate functions
return a single (scalar) value and can be used in SELECT, HAVING, and ORDER BY clauses
Aggregate functions ignore NULLs, except when using COUNT(*)
Aggregate functions in a SELECT list do not generate a column alias. Use the AS clause to
provide one.
Aggregate functions in a SELECT clause operate on all rows passed to the SELECT phase.
If there is no GROUP BY clause, all rows will be summarized

DISTINCT
removes duplicate values from the input column before display summary result
useful to answer question such as how many customers does employee have

Differenciate WHERE & HAVING BY

A WHERE clause controls which rows are available to the next phase of the query.
A HAVING clause controls which groups are available to the next phase of the query.
PG 8-10

Subqueries
Queries within queries
Return result to outer query
Self-contained / correlated
o Self-contained = not depend on outer query
o Correlated dependant on outer query as it references one or more columns from
outer query
In select statement
Run multiple times in outer query then pass result to inner query
Can support 32 levels of subqueries
Denote a subquery through parentheses (bracket)
If inner query will return a single value, use =, <,> etc in WHERE clause
If inner query return multiple values, use IN

[EXIST]
Subquery + [WHERE] [EXISTS]= existence test (true/false, not unknown)
No passed back to outer query
Row return by subquery if EXIST returns true
No column will be specify in subquery following [EXISTS], use [SELECT] *

Views
Saved query
In [SELECT]
Cant use [ORDER BY], unless in subquery
Does not store data
Views can be considered an application programming interface (API) to a
database for purposes of retrieving data
guard permission to viewer

Inline table-valued function (TVF)


like view = store as persistent object and use [SELECT]
distinction from view: accept inputted parameter
return result is a table=called query
2types
o Inline use [CREATE FUNCTION] + [SELECT]+ [RETURNS TABLE]
o Multi-statement = create and loads a table variable
Derived Tables
Another subquery
Visual relation table thats not stored in database
Like subquery = create[SELECT] from outer query
Difference: write derived tables using a named expression, help breakdown complex
query
No ORDER BY in this table
Must create aliases
o Inline (SELECTAS derived column ALIASE)
o Externally (AS <derived_table_alias>(<col1_alias>, <col2_alias>)
Passing argument
o Use [DELCLARE @]

Common Table Expression (CTE)


break down query problems into smaller, more modular units
require a name for the table expression
support recursion, referenced multiple times in the same query with one definition
use [WITH] + [AS]
PG 8-10
PG 8-10

UNION
Set joins used tables from different computers/locations
1) Union
i. Combine all data
ii. Input set must have same# of columns in SELEC + same data
type
iii. If row appears in either input sets, it will be incl. in result
iv. UNION combine all rows, then filter out duplicate
v. 2 forms:
1. [UNION DISTINCT] eliminate duplicate rows while
combing sets
2. [UNION ALL] combine all rows (incl. duplicates)
2) Intercept
vi. Find common data (e.g. find out which item every store is
selling)
vii. Result returns only same rows found in both sets
3) Except/minus
viii. Find differences /result return only distinct rows that appear in
one set but not another
4) Apply
ix. Table operator use in from clause, similar to join
x. Result in table values rather than single/muti-valued
xi. 2 operators:
1. CROSS APPLY = inner join(but can correlate data between
sources)
2. OUTER APPLY = left outer join (applies right table
expression to each row in the left table)
Window Function

Categories
o Aggregate (SUM, COUNT, MAX etc)
Aggregate setoff rows and return a single value
Use [OVER] clause, not group by
o Analytic (LEAD, FIRST_VALUE, LAST_VALUE, LAG)
Comparison between rows
[LAG] look at previous data set to determine if data value incr.
or decr.
[LEAD] look at future data
o Statistical (CUME_DIS, PERCENT_RANKT) distribution of a value
[ORDER BY] required
Express ratio between 0 & 1
o Ranking (RANK, DENSE_RANK)
Return ranking between rows
[ORDER BY] is required
[DENSE_RANK] return rank incl. ties, no gaps in between
Function:
o Generate row numbers
o Calculation of running total
PG 8-10

o Compare values between rows without joining a table to itself


o Cant add [GROUP BY] within running total
Elements
o Allow specify order to rows without affecting final order of query output
o Partition feature- restrict a function only apply to rows that have same
value as current row
o Framing option specify further row subset within partition by setting
upper and lower boundaries
o [OVER] with [PARTITION BY]
[OVER] w/out partition= result unrestricted (return all rows of
function)
[OVER] + [PARTITION BY] = return rows W/ same values in
partitioned columns (running total by section)
[ROW]/[RANGE] = create window frame by setting starting &
ending of partition, it requires [ORDER BY] subclause in [OVER]
clause (adding totals)
PIVIOT

Definition
o Rotate data from row-based orientation to column based orientation
o Requires min.3 columns to create a pivot table
o distinct values from a single column project across as column headings
o may incl. aggregation
o can only pivot use derived or temp table (not real tables)
o select statement must always have a alias
Elements
o FROM 1 + (SELECT + FROM2 + PIVIOT)
o Grouping columns used in final result in from1 clause, any columns
not pivoted or aggregated will end up as grouping (rows)
o Spreading column heading (separate by commas)
o Aggregation

GROUPING SETS

Alternative to using UNION ALL combine multiple outputs


Pick total you want
use GROUP BY clause
CUBE
o Shortcut to define grouping sets, provide total for every combination of
columns
ROLLUP
o Shortcut to define grouping sets
o Create subtotal and final totals based on specify columns
o Assume input columns represent a hierarchy
GROUPING_ID
o Method to make row with 1 or 0 to identify whether null is a
placeholder from underlying data
PG 8-10

o Pick names for totals

Stored Procedures
o Collection of TSQL statements stored in database and saved for future
use
o Return results, manipulate data and perform admin action on server
o Syntax : EXEC table name @column name=value

TSQL Batches
Collection of one or more TSQL statements sent to SQL server as a unit
for parsing, optimization and execution
Structure
o Terminated by GO
o Boundaries for variable scope
o CREATE] cant be combined with others n same batch
Procedure
1) Submit by SSMS
2) Check for syntax errors
3) Resolve object names
4) Check permissions
5) Optimize code for execution
6) Result

TSQL Variables
o Objects that allow storage of a value for later use in the same
batch
o Must be declare before use
o Defined with [DECLARE]
1. Can be declare and initialize in the same statement
2. Provide a name & data type
3. @ is a variable
o Only other statements in same batch can see declared variable.
It will be auto destroyed wen batches ends
o Ways to DECLARE
1. Initialize a variable using DECLARE statement
2. Assign a single value in the set statement
3. Assign a variable using SELECT statemen, but ensure
statement returns exactly one row
Synonyms
o Alias/link to object store on same SQL server instance or linked
server
o Reference remote objects/provide another name for object
o Use [CREATE] & [DROP] commands

Flow of Execution

Performed in specific orders, or not at all


2 commands
PG 8-10

1. [IF][ELSE]
if predicate true, dedicated code is executed, otherwise, no
action is taken unless specify by [ELSE] command
syntax[IF] condition true [BEGIN] specify actions [END] [ELSE]
[ BEGIN] false action initiates [END]
2. [WHILE]
Loop base on predicate
Syntax same as [IF] except replace with [WHILE], use [BEGIN] +
[END]
TSQL Error Handling

Try/Catch Block Programing


TRY block : codes that might raise an error is placed within
o Syntax: BEGIN TRY + END TRY
CATCH block: if catchable error occurs, execution of those codes will be
moved and done in the CATCH block
o Syntax : BEGIN CATCH + END CATCH
Try to catch errors in statements and catch errors

Transaction

Sequence of SQL statements performed in an all-or-nothing fashion by


SQL server (2 phrases, care about other commands)
2 ways to create transactions:
o Autocommit transactions individual data modification statements
(INSERT, UPDATE, DELETE) submitted separately from other
commands are either auto committed when statement success or
auto rolled back when statement fail

o Explicit transactions: - user initiated transactions that are created


thru use of TCL commands that begin, commit or rollback work
based on user-issued codes (user need to start transaction
manually)

Syntax : Begin TRAN + Commit OR Rollback (Undo)


XACT_STATE test if transaction is active
XACT_ABORT specify auto rollback if current transactions have a runtime
error

Vous aimerez peut-être aussi