Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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
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
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
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
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
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
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
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
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
Transaction