SlideShare a Scribd company logo
1 of 143
SQL Saturday Night


   Using T-SQL


      March 30, 2013
   SQL Saturday Night #19
Η παρουσίαση αυτή θα καταγραφεί ώστε να είναι διαθέσιμη
για όσους θέλουν να την ξαναδούν, ή δεν είχαν την
δυνατότητα να την παρακολουθήσουν σε πραγματικό χρόνο.
Εάν κάποιος από τους παραβρισκόμενους σε αυτή έχει το
οποιοδήποτε πρόβλημα ή αντίρρηση να είναι μέρος της
καταγραφή αυτής, παρακαλείται να αποχωρήσει άμεσα.
Σε διαφορετική περίπτωση η παραμονή σε αυτή εκλαμβάνεται
ως αποδοχή της καταγραφής.
Η παρουσίαση αυτή διατίθεται δωρεάν,
και θα αρχίσει σε 1 λεπτό…
Αυτή την στιγμή ο παρουσιαστής μιλάει και σας ζητάει να
βεβαιώσετε ότι τον ακούτε.
Εάν αυτό δεν είναι δυνατόν παρακαλείστε να αλλάξετε το
χρώμα της κάρτας σας στο αντίστοιχο χρώμα ώστε να
τον ενημερώσετε.
Αυτό μπορεί να γίνει πατώντας την αντίστοιχη επιλογή
που βρίσκεται στο πάνω δεξί μέρος του περιβάλλοντος
του live meeting.
Σας ευχαριστούμε για την συνεργασία.
Using T-SQL



SQL Saturday Night # 19 – March 30, 2013
SP_WHO



Sotiris                       Fivi                          Antonios
Karras                        Panopoulou                    Chatzipavlis
SQL Server Jr. DBA            SQL Server Jr. DBA            SQL Server Evangelist
- Microsoft Student Partner   - Microsoft Student Partner   - MVP on SQL Server
- N.T.U.A Student             - N.T.U.A Student             - MCSE on Data Platform
                                                            - MCSA on SQL Server 2012
                                                            - Microsoft Trainer (MCT)
                                                            - MCT Regional Leader
SOCIAL CONNECTIONS




@antoniosch
@sqlschool    SQL School Greece   www.sqlschool.gr   help@sqlschool.gr
Agenda
Using T-SQL
PRESENTATION TOPICS - 1
• Introduction to Microsoft SQL Server 2012
• SQL Server Management Studio
• Introduction to T-SQL Querying
• SELECT Statements / Queries
• Querying Multiple Tables
• Sorting and Filtering Data
• Grouping and Aggregating Data
PRESENTATION TOPICS - 2
• Using Sub-queries
• Using Views, Table Value Functions and
  Table Expressions
• Using Set Operators
• Using Stored Procedures
• Using Window Functions
• What’s New in SQL Server 2012
Introduction
to Microsoft SQL Server 2012
SQL SERVER ARCHITECTURE
• Services
• Instances
• Tools
SQL SERVER VERSIONS




  Umachandar Jayachandran
  former SQL Server MVP and currently a PM on the SQL Server Perf Team.
SQL SERVER VERSIONS
SQL SERVER VERSIONS
                                        Operating
 Version   Release Year    Code Name                           Company
                                         System

  1.0        1989                        OS2        Aston Tate, Microsoft, Sybase
  1.1        1991                        OS2        Aston Tate, Microsoft, Sybase
  4.2        1992                       Windows              Microsoft
 4.21        1994           SQLNT       Windows              Microsoft
  6.0        1995           SQL95       Windows              Microsoft
  6.5        1996           Hydra       Windows              Microsoft
  7.0        1998           Sphinx      Windows              Microsoft
 2000        2000           Shiloh      Windows              Microsoft
 2005        2005           Yukon       Windows              Microsoft
 2008        2008           Katmai      Windows              Microsoft
2008 R2      2010         Kilimanjaro   Windows              Microsoft
 2012        2012           Denali      Windows              Microsoft
SQL SERVER 2012 EDITIONS

Main Editions           Other Editions
Enterprise              Parallel Data Warehouse
Standard                Web
Business Intelligence   Developer
                        Express
                        Express LocalDB
SQL SERVER DATABASES

Containers       Boundaries
Tables           Security Accounts
Views            Permissions
Procedures       Default Collations
Functions
Users
Roles
Schemas
SQL SERVER SYSTEM DATABASES
master
The system configuration database.

msdb
The configuration database for the SQL Server Agent service and other system services.

model
Τhe template for new user databases.

tempdb
Used by the database engine to store temporary data such as work tables. Dropped and recreated
each time SQL Server restarts

resource
Α hidden system configuration database that provides system objects to other databases.

distribution
The distribution database stores metadata and history data for all types of replication, and
transactions for transactional replication.
SSMS
SQL Server Management Studio
SQL SERVER MANAGEMENT STUDIO
(SSMS)

“SQL Server Management Studio is an integrated
 environment for accessing, configuring, managing,
 administering, and developing all components of
 SQL Server. SQL Server Management Studio
 combines a broad group of graphical tools with a
 number of rich script editors to provide access to
 SQL Server to developers and administrators of all
 skill levels. ”
Using SQL Server Management
Studio
Introduction
to T-SQL Querying
INTRODUCING TRANSACT-SQL (T-SQL)
Is the language in which you will write your
queries for SQL Server.
Structure Query Language (SQL)
Developed by IBM in 1970
Adopted as ANSI and ISO standards
Widely used in industry

SQL is declarative not procedural
CATEGORIES OF T-SQL STATEMENTS
Data Manipulation Language (DML)
Statement for querying and modify data
SELECT, INSERT, UPDATE, DELETE
Data Definition Language (DDL)
Statements for Objects definitions
CREATE, ALTER, DROP
Data Control Language (DCL)
Statements for security permissions
GRANT, DENY, REVOKE
PREDICATES AND OPERATORS
Predicates
IN, BETWEEN, LIKE                 Operators Precedence

                                  1   ( ) Parentheses
Comparison Operators              2   *, /, %
=, >, <, >=, <=, <>, !=, !>, !<   3   +, -

Logical Operators
                                  4   =, <, >, >=, <=, !=, !>, !<
                                  5   NOT
AND, OR, NOT                      6   AND

Arithmetic Operators              7
                                  8
                                      BETWEEN, IN, LIKE, OR
                                      =
+, -, *, /, %

Concatenation
+
FUNCTIONS CATEGORIES
•   Rowset Functions       • Mathematical Functions
•   Aggregate Functions    • Metadata Functions
•   Ranking Functions
                           • Security Functions
•   Configuration
    Functions              • String Functions
•   Conversion Functions   • System Functions
•   Cursor Functions
                           • System Statistical
•   Date and Time Data       Functions
    Types and Functions
•   Logical Functions      • Text and Image
                             Functions
VARIABLES
• Local variables in T-SQL temporarily store a value of specific data
  type
• Name begins with single @ sign
• @@ reserved for system functions
• Assigned a data type
• Must be declared and used within the same batch
• You can declare and initialize in the same statement (from SQL
  Server 2008 and later)

DECLARE @variablename            datatype [=init value]

DECLARE @myVar INT = 20;
EXPRESSIONS
• Combination of identifiers, values and
  operators evaluated to obtain a single result
• Can be used in many situations like
  • SELECT clause
  • WHERE clause
  • SET clause



SELECT YEAR(SalesOrderDate) + 1 …

SELECT Quantity * UnitPrice …
CONTROL FLOW STATEMENTS
• IF…ELSE
• WHILE
• BREAK
• CONTINUE
• BEGIN…END
ERRORS AND ERROR HANDLING
• @@error system function
• RAISERROR
• THROW
• TRY…CATCH
TRANSACTION CONTROL STATEMENTS
• BEGIN TRANSACTION
• COMMIT TRANSACTION
• ROLLBACK TRANSACTION
T-SQL Elements
COMMENTS
Block comments
/*
     SELECT …
     other code…
*/


Inline comments
-- inline comment
DECLARE @myVar INT = 20; -- initial value
BATCHES AND BATCH SEPARATOR
• Batches are sets of commands sent to SQL Server as a unit
• Batches determine variable scope and name resolution
• To separate statements into batches SQL Server uses the
  GO keyword
  •   GO is not a SQL Server command!
  •   We can define our batch separator
  •   GO n time feature added in SQL Server 2005 and later.

DECLARE @CustomerID NCHAR(5) = ‘ANTON’;
SELECT CustomerID, CompanyName FROM Orders
WHERE CustomerID = @CustomerID;
GO
CREATE TABLE T(c1 INT);
GO
CREATE VIEW V AS SELECT * FROM T;
GO
SQL SERVER DATA TYPES
• SQL Server defines a set of system data types
  for
  • storing data in columns,
  • holding values temporarily in variables,
  • for operating on data in expressions,
  • for passing parameters in stored procedures and functions

• Data Types specify the
  • Type
  • Length
  • Precision
  • Scale
SQL SERVER DATA TYPES CATEGORIES
• Exact numeric
• Approximate numeric
• Date & Time
• Character string
• Unicode character strings
• Binary string
• Other data types
EXACT NUMERIC DATA TYPES
Data type    Range                               Storage (bytes)

tinyint      0 to 255                            1
smallint     -32,768 to 32,768                   2
int          2^31 (-2,147,483,648) to            4
             2^31-1 (2,147,483,647)
bigint       -2^63 - 2^63-1                      8
             (+/- 9 quintillion)
bit          1, 0 or NULL                        1
decimal      - 10^38 +1 through 10^38 – 1 when   5-17
             maximum precision is used
numeric      - 10^38 +1 through 10^38 – 1 when   5-17
             maximum precision is used
money        -922,337,203,685,477.5808 to        8
             922,337,203,685,477.5807
smallmoney   - 214,748.3648 to 214,748.3647      4
APPROXIMATE NUMERIC DATA TYPES
Data Type    Range                                        Storage (bytes)

float(n)     - 1.79E+308 to -2.23E-308, 0 and 2.23E-      Depends on value of n, 4
             308 to 1.79E+308                             or 8 bytes
real         - 3.40E + 38 to -1.18E - 38, 0 and 1.18E -
                                                          4
             38 to 3.40E + 38


• float(24) is the ISO synonym for float
   • In float(n), n is the number of bytes used to store the mantissa of the float
     number in scientific notation

• Values of float are truncated when converted
  to integer types
DATE & TIME DATA TYPES
• Older versions of SQL Server supported only
  DATETIME and SMALLDATETIME
• DATE, TIME, DATETIME2, and
  DATETIMEOFFSET introduced in SQL Server
  2008
• SQL Server 2012 adds new functionality for
  working with date and time data types
DATE & TIME DATA TYPES
                 Storage                                       Recommended Entry
Data Type                  Date Range             Accuracy
                 (bytes)                                       Format

DATETIME           8       January 1, 1753 to       3-1/3      'YYMMDD
                           December 31, 9999    milliseconds   hh:mm:ss:nnn'
SMALLDATETIME      4       January 1, 1900 to    1 minute      'YYMMDD
                           June 6, 2079                        hh:mm:ss:nnn'
DATETIME2        6 to 8    January 1, 0001 to       100        'YYMMDD
                           December 31, 9999    nanoseconds    hh:mm:ss.nnnn
                                                               nn'
DATE               3       January 1, 0001 to      1 day       'YYYY-MM-DD'
                           December 31, 9999
TIME             3 to 5                             100        'hh:mm:ss:nnn
                                                nanoseconds    nnnn'
DATETIMEOFFSET   8 to 10 January 1, 0001 to         100        'YY-MM-DD
                         December 31, 9999      nanoseconds    hh:mm:ss:nnnn
                                                               nnn [+|-
                                                               ]hh:mm'
CHARACTER STRING DATA TYPES
• One byte per character
Data Type           Range                 Storage

CHAR(n)             1-8000 characters     n bytes, padded     Fixed Length
VARCHAR(n)          1-8000 characters     n+2 bytes           Variable Length
VARCHAR(MAX)        1-2^31-1 characters   Actual length + 2   Variable Length




• TEXT deprecated
       • Use VARCHAR(MAX) instead
UNICODE CHARACTER STRING DATA TYPES

• Two bytes per character
Data Type           Range                 Storage

NCHAR(n)            1-8000 characters     2*n bytes, padded Fixed Length
NVARCHAR(n)         1-8000 characters     (2*n)+2 bytes       Variable Length
NVARCHAR(MAX)       1-2^31-1 characters   Actual length + 2   Variable Length




• NTEXT deprecated
       • Use NVARCHAR(MAX) instead
BINARY STRING
Data Type        Range                          Storage (bytes)

binary(n)        1-8000 bytes                   n bytes
varbinary(n)     1-8000 bytes                   n bytes + 2
varbinary(MAX)   1-2.1 billion (approx) bytes   actual length + 2



• IMAGE deprecated
   • Use VARBINARY(MAX) instead
OTHER DATA TYPES
Data Type          Range            Storage      Remarks
                                    (bytes)

rowversion         Auto-generated   8            Successor type to
                                                 timestamp
uniqueidentifier   Auto-generated   16           Globally unique identifier
                                                 (GUID)
xml                0-2 GB           0-2 GB       Stores XML in native
                                                 hierarchical structure
cursor             N/A              N/A          Not a storage data type
hierarchyid        N/A              Depends on   Represents position in a
                                    content      hierarchy
sql_variant        0-8000 bytes     Depends on   Can store data of various
                                    content      data types
table              N/A              N/A          Not a storage data type,
                                                 used for query and
                                                 programmatic operations
DATA TYPES PRESENTENCE
• Data type precedence determines which data
  type will be chosen when expressions of different
  types are combined
• Data type with the lower precedence is converted
  to the data type with the higher precedence
• Important for understanding implicit conversions
  •   Conversion to type of lower precedence must be made explicitly (with CAST
      function)

• Example (low to high):
  •   CHAR -> VARCHAR -> NVARCHAR -> TINYINT -> INT -> DECIMAL -> TIME ->
      DATE -> DATETIME2 -> XML
DATA TYPES CONVERSION
• Data type conversion scenarios
  • When data is moved, compared, or combined with other data
  • During variable assignment

• Implicit conversion
  • When comparing data of one type to another
  • Transparent to user
  WHERE <column of smallint type> = <value of int type>

• Explicit conversion
  • Uses CAST or CONVERT functions
  CAST(unitprice AS int)

• Not all conversions allowed by SQL Server
SELECT Statement
The Select Statement and Writing Queries
SELECT STATEMENT – MAIN CLAUSES
• [ WITH <common_table_expression>]
• SELECT select_list [ INTO new_table ]
• [ FROM table_source ] [ WHERE search_condition ]
• [ GROUP BY group_by_expression ]
• [ HAVING search_condition ]
• [ ORDER BY order_expression [ ASC | DESC ] ]
SELECT STATEMENT – LOGICAL PROCESSING
• FROM
• ON
• JOIN
• WHERE
• GROUP BY
• WITH CUBE or WITH ROLLUP
• HAVING
• SELECT
• DISTINCT
• ORDER BY
• TOP
Select statement – Full statement
SELECT DISTINCT
• Specifies that only unique rows can appear in the
  result set
• Removes duplicates based on column list results,
  not source table
• Provides uniqueness across set of selected
  columns
• Removes rows already operated on by WHERE,
  HAVING, and GROUP BY clauses
• Some queries may improve performance by
  filtering out duplicates prior to execution of
  SELECT clause
COLUMN ALIASES
• Column aliases using AS
 SELECT orderid, unitprice, qty AS quantity
 FROM   OrderDetails;

• Column aliases using =
 SELECT orderid, unitprice, quantity = qty
 FROM   OrderDetails;

• Accidental column aliases
 SELECT orderid, unitprice quantity
 FROM   OrderDetails;
TABLE ALIASES
• Create table aliases in the FROM clause
• Table aliases with AS
  SELECT custid, orderdate
  FROM   dbo.Orders AS SO;

• Table aliases without AS
  SELECT custid, orderdate
  FROM   Sales.Orders SO;

• Using table aliases in the SELECT clause
  SELECT SO.custid, SO.orderdate
  FROM   Sales.Orders AS SO;
SELECT STATEMENT – CASE EXPRESSION

Simple Case expression
CASE input_expression
     WHEN when_expression THEN result_expression [ ...n ]
     [ ELSE else_result_expression ]
END

Searched CASE expression
CASE
       WHEN boolean_expression THEN result_expression [ ...n ]
       [ ELSE else_result_expression ]
END
SELECT Statement
Querying Multiple
Tables
Writing Join Queries
JOIN CLAUSE – INTRODUCTION
• By using joins, you can retrieve data from two or more tables
  based on logical relationships between the tables.
• Three types of Joins
  1.     Inner Joins, which use a comparison operator to match rows from two tables
         based on the values in common columns from each table
  2.     Outer Joins, in which all the rows of the specified table(s) are returned, not
         just the ones in which the joined columns match
  3.     Cross Joins, which produce the Cartesian product of the tables involved in the
         join (if there is no WHERE clause present)
  4.     Self Joins which you need to compare and retrieve data stored in the same
         table

• Main Join Clause
       SELECT select_list
       FROM first_table
       join_type second_table [ON (join_condition)]
       [WHERE (search_condition)]
T-SQL JOIN SYNTAX CHOICES
• ANSI SQL-92
 • Tables joined by JOIN operator in FROM Clause
 • Preferred syntax
  SELECT ...
  FROM   Table1 JOIN Table2
         ON <on_predicate>

• ANSI SQL-89
 • Tables joined by commas in FROM Clause
 • Not recommended: accidental Cartesian products!

  SELECT ...
  FROM   Table1, Table2
  WHERE <where_predicate>
Join Multiple Tables
Sorting & Filtering
Sorting and Filtering Data
SORTING/FILTERING – SORTING

• You can sort data retrieved by a SELECT
  statement using the ORDER BY clause

• ORDER BY clause syntax:
ORDER BY order_by_expression
   [ COLLATE collation_name ]
   [ ASC | DESC ]
   [ ,...n ]
[ <offset_fetch> ]
SORTING/FILTERING – COLLATION

• Specifies that the ORDER BY operation
  should be performed according to the
  collation specified in collation_name
• Using collations to sort data, depending
  on encoding or case sensitive/accent
  sensitive options
SORTING/FILTERING – TOP/OFFSET
  <offset_fetch> ::=
  {
      OFFSET { integer_constant | offset_row_count_expression } { ROW |
  ROWS }
      [
        FETCH { FIRST | NEXT } {integer_constant |
  fetch_row_count_expression } { ROW | ROWS } ONLY
      ]
  }


• Specifies the number of rows to return after the OFFSET
  clause has been processed. The value can be an integer
  constant or expression that is greater than or equal to one.
• Both OFFSET and FETCH can use variables as input and thus
  are able to be optimized for specified values of those values
  using the OPTIMIZE FOR hint
SORTING/FILTERING – WORKING WITH NULL VALUES

• NULL has three logical interpretations
  •   Unknown value
  •   Unavailable value
  •   Not supported value

• SET ANSI_NULLS { ON | OFF }
• Setting ANSI_NULLS ON, causes the SELECT
  statements using WHERE column_name = NULL
  to return zero rows even if there are null values
  in column_name ( thus operators =, <> follow the ISO
  standard)
• Option in future versions ANSI_NULLS will by default
  be set to ON
Sorting & Filtering
Grouping &
Aggregating
Grouping and Aggregating Data
AGGREGATE FUNCTIONS

• Aggregate functions perform a calculation
  on a set of values and return a single value.
• Deterministic in nature. They return the
  same value any time that they are called by
  using a specific set of input values.
               List of Aggregate Functions
             AVG                        MIN
         CHECKSUM_AVG                   SUM
            COUNT                      STDEV
           COUNT_BIG                  STDEVP
           GROUPING                     VAR
          GROUPING_ID                  VARP
             MAX
GROUP BY CLAUSE
• Groups sets of rows, using the values of one or
  more columns or expressions.
• Each group is represented by one and only one
  row.
• Usually aggregates are used to provide the
  grouping criterion
• Can filter the groups created using the HAVING
  keyword
• A GROUP BY clause can include GROUPING
  SETS, CUBE AND ROLLUP keywords
DISTINCT & NULL WITH AGGREGATE FUNCTIONS

• Use DISTINCT with aggregate functions to summarize only unique
  values

• DISTINCT aggregates eliminate duplicate values, not rows (unlike
  SELECT DISTINCT)
• Most aggregate functions ignore NULL
  •   COUNT(<column>) ignores NULL
  •   COUNT(*) counts all rows


• NULL may produce incorrect results (such as use of AVG)
• Use ISNULL or COALESCE to replace NULLs before aggregating
GROUPING SETS
• GROUPING SETS subclause builds on T-SQL
  GROUP BY clause
• Allows multiple groupings to be defined in
  same query
 SELECT <column list with aggregate(s)>
 FROM <source>
 GROUP BY
 GROUPING SETS(
       (<column_name>),--one or more columns
       (<column_name>),--one or more columns
       () -- empty parentheses if aggregating all rows
             );
GROUPING_ID
• Multiple grouping sets present a problem in
  identifying the source of each row in the result set
• NULLs could come from the source data or could be
  a placeholder in the grouping set
• The GROUPING_ID function provides a method to
  mark a row with a 1 or 0 to identify which grouping
  set the row is a member of
SELECT GROUPING_ID(Category)AS grpCat,
      GROUPING_ID(CustomerID) AS grpCust,
      Category, CustomerID, SUM(Qty) AS TotalQty
FROM CategorySales
GROUP BY CUBE(Category,CustomerID)
ORDER BY Category, CustomerID;
Grouping & Aggregating
CUBE/ROLLUP
• CUBE provides shortcut for defining grouping sets given a list of
  columns
• All possible combinations of grouping sets created
   SELECT <column list with aggregate(s)>
   FROM <source>
   GROUP BY CUBE (<column_name>, <column_name>, ...);

• ROLLUP provides shortcut for defining grouping sets, creates
  combinations assuming input columns form a hierarchy
   SELECT <column list with aggregate(s)>
   FROM <source>
   GROUP BY CUBE (<column_name>, <column_name>, ...);
PIVOT
• Pivoting data is rotating data from a rows-based orientation
  to a columns-based orientation
• Distinct values from a single column are projected across as
  headings for other columns - may include aggregation
PIVOT SYNTAX
• Pivoting includes three phases:
1. Grouping determines which element gets a row in the
   result set
2. Spreading provides the distinct values to be pivoted across
3. Aggregation performs an aggregation function (such as
   SUM)
                        Grouping

   SELECT Category, [2006],[2007],[2008]
   FROM ( SELECT Category, Qty, Orderyear
          FROM Sales.CategoryQtyYear) AS D
   PIVOT(SUM(QTY) FOR orderyear
               IN([2006],[2007],[2008])           Spreading
               ) AS pvt;

      Aggregation
UNPIVOT
• Unpivoting data is rotating data from a columns-based orientation to a
  rows-based orientation
• Spreads or splits values from one source row into one or more target rows
• Each source row becomes one or
  more rows in result set based on
  number of columns being pivoted
UNPIVOT SYNTAX
• Unpivoting includes three elements:
 • Source columns to be unpivoted
 • Name to be assigned to new values column
 • Name to be assigned to names columns




  SELECT category, qty, orderyear
  FROM CategorySales
  UNPIVOT(qty FOR orderyear
  IN([2006],[2007],[2008])) AS unpvt;
CUBE, ROLLUP PIVOT, UNPIVOT
            ,
Using Sub-queries
What is and How to write Sub-queries
SUBQUERIES
• Nesting queries within queries
  • Outer query : result set returned to caller
  • Inner query : result set returned to outer query



• Types of subqueries based on return value:
  • Single –valued (scalar)
  • Multivalued
  • Table-valued
DEPENDENCY ON OUTER QUERY
• Self-Contained Subqueries
 • Subquery not dependent on outer query
 • Can be evaluated by executing the subquery once and substituting the
   result into the WHERE clause of the outer query
 • Easier to debug

• Correlated Subqueries
 • The subquery depends on the outer query for its values
 • The subquery is executed repeatedly, once for each row that might be
   selected by the outer query
 • Known as repeating subquery
USE

 •   Anywhere an expression is allowed
 •   Not in an ORDER BY clause
 •   Subqueries within subqueries
 •   Commonly used with (NOT) IN and EXISTS
EXISTS PREDICATE
• Tests existence of rows.
• Returns TRUE or FALSE
• Usually * consists the SELECT list of the subquery,
  no reason to list column names
• Enough to determine whether the subquery returns
  at least one row, so engine doesn’t need to process
  all rows
Using Subqueries
Views, TVFs, Table
Expressions
Using Views, Table Value Functions and Table
Expressions
VIEWS
A view is a virtual table whose contents (rows and
columns) are defined by a query.
• The rows and columns of data come from tables
  referenced in the query defining the view and are
  produced dynamically when the view is referenced.
• Updatable view: modifying an underlying base table
  through the view
• Indexed view: The view definition has been
  computed and the resulting data stored just like a
  table.
USE
• To focus, simplify, and customize the perception
  each user has of the database.
• As a security mechanism by allowing users to
  access data through the view, without granting the
  users permissions to directly access the underlying
  base tables.
• To provide a backward compatible interface to
  emulate a table whose schema has changed.
OPTIONS
• CHECK OPTION
  Prevent data modifications through the view that conflict
  with the views filter
• ENCRYPTION
  Encrypt text of the CREATE VIEW statement in
  sys.syscomments
• SCHEMABINDING
  Prevent modification of underlying views that would affect
  the view definition
Using Views
INLINE TABLE-VALUED FUNCTIONS
• Table-valued functions (TVFs) are named table
  expressions with definitions stored in a database
• TVFs return a virtual table to the calling query
• SQL Server provides two types of TVFs
  •   Inline, based on a single SELECT statement
  •   Multi-statement, which creates and loads a table variable

• Unlike views, TVFs support input parameters
• Inline TVFs may be thought of as parameterized
  views
WRITING INLINE TVF
• Table-valued functions are created by administrators and
  developers
• Create and name function and optional parameters with
  CREATE FUNCTION
• Declare return type as TABLE
• Define inline SELECT statement following RETURN
   CREATE FUNCTION Sales.fn_LineTotal (@orderid INT)
   RETURNS TABLE
   AS
   RETURN
       SELECT orderid,
          CAST((qty * unitprice * (1 - discount)) AS
                 DECIMAL(8, 2)) AS line_total
       FROM    OrderDetails
       WHERE   orderid = @orderid ;
Inline Table Value Functions
DERIVED TABLES
• Derived tables are named query expressions created within an
  outer SELECT statement
• Not stored in database – represents a virtual relational table
• When processed, unpacked into query against underlying
  referenced objects
•   Allow you to write more modular queries

    SELECT <column_list>
    FROM (
          <derived_table_definition>
          ) AS <derived_table_alias>;


• Scope of a derived table is the query in which it is defined
Derived Tables
COMMON TABLE EXPRESSIONS
• CTEs are named table expressions defined in
  a query
• CTEs are similar to derived tables in scope
  and naming requirements
• Unlike derived tables, CTEs support multiple
  definitions, multiple references, and recursion
   WITH <CTE_name>
   AS (
      <CTE_definition>
         )
   <outer query referencing CTE>;
WRITING CTE
• Define the table expression in WITH clause
• Assign column aliases (inline or external)
• Pass arguments if desired
• Reference the CTE in the outer query
 WITH CTE_year AS
        (
        SELECT YEAR(orderdate) AS orderyear, customerid
        FROM Orders
        )
 SELECT orderyear,
        COUNT(DISTINCT customerid) AS cust_count
 FROM CTE_year
 GROUP BY orderyear;
Common Table Expressions
Set Operators
Using Set Operators
SET OPERATORS
Set operators combine results from two or more queries into
a single result set.
• The number and the order of the columns must be the same in all
  queries.
• The data types must be compatible
• ORDER BY clause applied to result of operator
• Names of columns in result are specified by the first query
• NULLS are equal                               Input Query 1
                                                set operator
                                                Input Query 2
                                                [ORDER BY … ]
SET OPERATORS
• UNION: returns all rows that belong to at least one
  of the input queries.
  • By default result set has no duplicates. To get result set with
    duplicates specify ALL option.

• INTERSECT: returns any distinct values that are
  returned by both the left query and the right one.
• EXCEPT: returns any distinct values from the left
  query that are not also found on the right query.
APPLY
• Invoke a table-valued function for each row
  returned by an outer table expression of a query.
• CROSS APPLY returns only rows from the outer
  table that produce a result set from the table-
  valued function.
• OUTER APPLY returns both rows that produce a
  result set, and rows that do not, with NULL values in
  the columns produced by the table-valued
  function.
Union, Intersect, Except, Apply
Stored Procedures
Using Stored Procedures
STORED PROCEDURES
A stored procedure in SQL Server is a group of one
or more Transact-SQL statements which can :
  • Accept input parameters and return multiple values in the
    form of output parameters to the calling program.
  • Contain programming statements that perform operations in
    the database. These include calling other procedures.
  • Return a status value to a calling program to indicate success
    or failure (and the reason for failure)
BENEFITS
• Reduced server/client network traffic
• Stronger security
• Reuse of code
• Easier maintenance
• Improved performance
Using Stored Procedures
Window Functions
Using Window Functions
SQL WINDOWING
Window functions are functions applied to sets of rows defined by
a clause called OVER
They are used mainly for analytical purposes allowing you to
calculate running totals, calculate moving averages, identify gaps
and islands in your data, and perform many other computations
These functions are based on the concept of windowing in
standard SQL, which is both an ISO and ANSI standard
The idea behind this concept is to allow you to apply various
calculations to a set, or window, of rows and return a single value
Window functions can help to solve a wide variety of querying
tasks by helping you express set calculations more easily,
intuitively, and efficiently than ever before
THE SYNTAX
function_name(<arguments>)
OVER(
    [ <window partition clause> ]
    [ <window order clause>
        [ <window frame clause> ]
    ]
   )
OVER CLAUSE
OVER defines a window, or set, of rows to be used
by a window function, including any ordering
With a specified window partition clause, the OVER
clause restricts the set of rows to those with the
same values in the partitioning elements
By itself, OVER() is unrestricted and includes all
rows
Multiple OVER clauses can be used in a single
query, each with its own partitioning and ordering,
if needed
WINDOW PARTITION CLAUSE
The partitioning element allows you to restrict
the window to only those rows that have the
same values in the partitioning attributes as
the current row.

SELECT orderid, custid, val,
SUM(val) OVER() AS sumall,
SUM(val) OVER(PARTITION BY custid) AS sumcust
FROM OrderValues AS O1;
WINDOW ORDER CLAUSE
The ordering element defines the ordering for
the calculation, if relevant, within the partition


SELECT custid, orderid, val,
RANK() OVER(ORDER BY val DESC) AS rnk_all,
RANK() OVER(PARTITION BY custid
             ORDER BY val DESC) AS rnk_cust
FROM Orders;
WINDOW FRAME CLAUSE
Framing is another option that enables you to
further restrict the rows in the window
partition.
SELECT empid, ordermonth, qty,
SUM(qty) OVER(PARTITION BY empid
              ORDER BY ordermonth
              ROWS BETWEEN UNBOUNDED PRECEDING
                    AND CURRENT ROW) AS runqty
FROM EmpOrders;
CONCEPTUAL RELATIONSHIP BETWEEN WINDOW ELEMENTS




 Result set
 (OVER)

 Window
 partition
 (PARTITION BY)

 Frame
 (ROWS BETWEEN)
WINDOW AGGREGATE FUNCTIONS
• Similar to grouped aggregate functions
 • SUM, MIN, MAX, etc.

• Applied to windows defined by OVER clause
• Window aggregate functions support
  partitioning, ordering, and framing

  SELECT  custid, ordermonth, qty,
          SUM(qty) OVER(PARTITION BY custid) AS
              totalpercust
  FROM Sales.CustOrders;
WINDOW RANKING FUNCTIONS
• Ranking functions require a window order
  clause
 • Partitioning is optional
 • To display results in sorted order still requires ORDER BY!

  Function                Description

  RANK                    Returns the rank of each row within the partition of a
                          result set. May include ties and gaps.
  DENSE_RANK              Returns the rank of each row within the partition of a
                          result set. May include ties. Will not include gaps.
  ROW_NUMBER              Returns a unique sequential row number within
                          partition based on current order.
  NTILE                   Distributes the rows in an ordered partition into a
                          specified number of groups. Returns the number of
                          the group to which the current row belongs.
WINDOW DISTRIBUTION FUNCTIONS
• Window distribution functions perform
  statistical analysis on data, and require a
  window order clause
• Rank distribution performed with
  PERCENT_RANK and CUME_DIST
• Inverse distribution performed with
  PERCENTILE_CONT and PERCENTILE_DISC
WINDOW OFFSET FUNCTIONS
• Window offset functions allow comparisons between
  rows in a set without the need for a self-join
• Offset functions operate on an position relative to the
  current row, or to the start or end of the window
  frame
Function      Description

LAG           Returns an expression from a previous row that is a defined offset
              from the current row. Returns NULL if no row at specified position.
LEAD          Returns an expression from a later row that is a defined offset from
              the current row. Returns NULL if no row at specified position.
FIRST_VALUE   Returns the first value in the current window frame. Requires window
              ordering to be meaningful.
LAST_VALUE    Returns the last value in the current window frame. Requires window
              ordering to be meaningful.
Window Functions
What’s New in
SQL Server 2012
Improvements of T-SQL in SQL Server 2012
USING SEQUENCES
• Sequence objects added in SQL Server 2012
• Independent objects in database
  •   More flexible than the IDENTITY property
  •   Can be used as default value for a column

• Manage with CREATE/ALTER/DROP statements
• Retrieve value with the NEXT VALUE FOR clause
-- Define a sequence
CREATE SEQUENCE dbo.InvoiceSeq AS INT
                    START WITH 1 INCREMENT BY 1;
-- Retrieve next available value from sequence
SELECT NEXT VALUE FOR dbo.InvoiceSeq;
USING MERGE TO MODIFY DATA
• MERGE modifies data based on a condition
 • When the source matches the target
 • When the source has no match in the target
 • When the target has no match in the source


  MERGE INTO schema_name.table_name AS TargetTbl
      USING (SELECT <select_list>) AS SourceTbl
      ON (TargetTbl.col1 = SourceTbl.col1)
      WHEN MATCHED THEN
          UPDATE SET col2 = SourceTbl.col2
  WHEN NOT MATCHED THEN
      INSERT (<column_list>)
      VALUES (<value_list>);
Conversion
Functions
NEW CONVERSION FUNCTIONS
• PARSE
SELECT PARSE('Monday, 13 December 2010' AS datetime2
             USING 'en-US') AS Result;
Result : 2010-12-13 00:00:00.0000000

• TRY_CONVERT
SELECT CASE WHEN TRY_CONVERT(float, 'test') IS NULL
            THEN 'Cast failed'
            ELSE 'Cast succeeded'
       END AS Result;

• TRY_PARSE
SELECT TRY_PARSE('AAAAA' AS datetime2
              USING 'en-US') AS Result;
Result : NULL
Date & Time
Functions
DATEFROMPARTS
• Returns a date value with the date portion set
  to the specified year, month and day, and the
  time portion set to the default.
• If the arguments are not valid, then an error
  is raised.
• If required arguments are null, then null is
  returned.
SELECT DATEFROMPARTS ( 2010, 12, 31 ) AS Result;

Result 2010-12-31
DATETIME2FROMPARTS
• Returns a fully initialized datetime2 value.
• If the arguments are not valid, an error is
  raised.
• If required arguments are null, then null is
  returned.
• If the precision argument is null, then an error
  is raised.
SELECT DATETIME2FROMPARTS( 2010, 12, 31, 23, 59, 59, 0, 0 );

Result 2010-12-31 23:59:59.0000000
DATETIMEFROMPARTS
• Returns a fully initialized datetime value.
• If the arguments are not valid, then an error
  is raised.
• If required arguments are null, then a null is
  returned.

SELECT DATETIMEFROMPARTS( 2010, 12, 31, 23, 59, 59, 0 );

Result 2010-12-31 23:59:59.000
DATETIMEOFFSETFROMPARTS
• Returns a fully initialized datetimeoffset data type.
• The offset arguments are used to represent the time zone offset.
• If the offset arguments are omitted, then the time zone offset is assumed
  to be 00:00.
• If the offset arguments are specified, then both arguments must be
  present and both must be positive or negative.
• If minute_offset is specified without hour_offset, an error is raised.
• If other arguments are not valid, then an error is raised.
• If required arguments are null, then a null is returned.
• If the precision argument is null, then an error is raised.
SELECT DATETIMEOFFSETFROMPARTS(2010,12,31,14,23,23,0,12,0,7);

Result 2010-12-07 00:00:00.0000000 +00:00
EOMONTH
• Returns the last day of the month that
  contains the specified date, with an optional
  offset.
DECLARE @date DATETIME = '12/1/2011';
SELECT EOMONTH ( @date ) AS Result;
GO

Result 2011-12-31
SMALLDATETIMEFROMPARTS
• Returns a smalldatetime value for the
  specified date and time.

SELECT SMALLDATETIMEFROMPARTS ( 2010, 12, 31, 23, 59 );

Result 2011-01-01 00:00:00
TIMEFROMPARTS
• Returns a fully initialized time value.
• If the arguments are invalid, then an error is
  raised.
• If any of the parameters are null, null is
  returned.
• If the precision argument is null, then an error
  is raised.
SELECT TIMEFROMPARTS ( 23, 59, 59, 0, 0 ) AS Result;

Result 23:59:59.0000000
Logical Functions
CHOOSE
• Returns the data type with the highest
  precedence from the set of types passed to
  the function
• CHOOSE acts like an index into an array,
  where the array is composed of the
  arguments that follow the index argument.
SELECT CHOOSE (3,'Manager','Director','Developer','Tester');

Result Developer
IIF
• Returns the data type with the highest
  precedence from the types in true_value and
  false_value
• IIF is a shorthand way for writing a CASE
  expression.
DECLARE @a int = 45, @b int = 40;
SELECT IIF ( @a > @b, 'TRUE', 'FALSE' ) AS Result;
GO

Result TRUE
String Functions
CONCAT
• Returns a string that is the result of
  concatenating two or more string values.


SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' );

Result Happy Birthday 11/25
FORMAT
• Returns a value formatted with the specified
  format and optional culture.

DECLARE @d DATETIME = '10/01/2011';
SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'
       ,FORMAT ( @d, 'd', 'en-gb' ) AS 'GB English Result'
       ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result';


        US English Result : 10/1/2011
 Result GB English Result : 01/10/2011
        German Result : 01.01.2011
Questions
&
Answers
SUMMARY
• Introduction to Microsoft SQL Server 2012
• SQL Server Management Studio
• Introduction to T-SQL Querying
• SELECT Statements / Queries
• Querying Multiple Tables
• Sorting and Filtering Data
• Grouping and Aggregating Data
SUMMARY
• Using Sub-queries
• Using Views, Table Value Functions and
  Table Expressions
• Using Set Operators
• Using Stored Procedures
• Using Window Functions
• What’s New in SQL Server 2012
Thank you
SELECT KNOWLEDGE FROM SQL SERVER

More Related Content

What's hot

Mobile dbms
Mobile dbmsMobile dbms
Mobile dbms
Tech_MX
 
Lecture 10 distributed database management system
Lecture 10   distributed database management systemLecture 10   distributed database management system
Lecture 10 distributed database management system
emailharmeet
 
Data Warehouse Modeling
Data Warehouse ModelingData Warehouse Modeling
Data Warehouse Modeling
vivekjv
 
Data mining-primitives-languages-and-system-architectures2641
Data mining-primitives-languages-and-system-architectures2641Data mining-primitives-languages-and-system-architectures2641
Data mining-primitives-languages-and-system-architectures2641
Aiswaryadevi Jaganmohan
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbms
Naresh Kumar
 

What's hot (20)

Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
Mobile dbms
Mobile dbmsMobile dbms
Mobile dbms
 
Data Warehousing and Data Mining
Data Warehousing and Data MiningData Warehousing and Data Mining
Data Warehousing and Data Mining
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Lecture 10 distributed database management system
Lecture 10   distributed database management systemLecture 10   distributed database management system
Lecture 10 distributed database management system
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
Data Streaming in Big Data Analysis
Data Streaming in Big Data AnalysisData Streaming in Big Data Analysis
Data Streaming in Big Data Analysis
 
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtapADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
ADVANCE DATABASE MANAGEMENT SYSTEM CONCEPTS & ARCHITECTURE by vikas jagtap
 
Data warehouse
Data warehouseData warehouse
Data warehouse
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Introduction to Data Warehouse
Introduction to Data WarehouseIntroduction to Data Warehouse
Introduction to Data Warehouse
 
Data Warehouse Modeling
Data Warehouse ModelingData Warehouse Modeling
Data Warehouse Modeling
 
Business Intelligence Module 3
Business Intelligence Module 3Business Intelligence Module 3
Business Intelligence Module 3
 
Date and time functions in mysql
Date and time functions in mysqlDate and time functions in mysql
Date and time functions in mysql
 
Data mining-primitives-languages-and-system-architectures2641
Data mining-primitives-languages-and-system-architectures2641Data mining-primitives-languages-and-system-architectures2641
Data mining-primitives-languages-and-system-architectures2641
 
Etl overview training
Etl overview trainingEtl overview training
Etl overview training
 
Database Basics
Database BasicsDatabase Basics
Database Basics
 
Data mining technique (decision tree)
Data mining technique (decision tree)Data mining technique (decision tree)
Data mining technique (decision tree)
 
Data warehouse,data mining & Big Data
Data warehouse,data mining & Big DataData warehouse,data mining & Big Data
Data warehouse,data mining & Big Data
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbms
 

Viewers also liked

Viewers also liked (17)

Intro to T-SQL - 1st session
Intro to T-SQL - 1st sessionIntro to T-SQL - 1st session
Intro to T-SQL - 1st session
 
Intro to T-SQL – 2nd session
Intro to T-SQL – 2nd sessionIntro to T-SQL – 2nd session
Intro to T-SQL – 2nd session
 
Pivot Unpivot
Pivot UnpivotPivot Unpivot
Pivot Unpivot
 
Technical stream presentation
Technical stream presentationTechnical stream presentation
Technical stream presentation
 
Dating Game - T-SQL for High School Girls
Dating Game - T-SQL for High School GirlsDating Game - T-SQL for High School Girls
Dating Game - T-SQL for High School Girls
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
Microsoft SQL Server PowerPivot
Microsoft SQL Server PowerPivotMicrosoft SQL Server PowerPivot
Microsoft SQL Server PowerPivot
 
MS SQL SERVER: Getting Started With Sql Server 2008
MS SQL SERVER: Getting Started With Sql Server 2008MS SQL SERVER: Getting Started With Sql Server 2008
MS SQL SERVER: Getting Started With Sql Server 2008
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, Intersect
 
Introduction to sql database on azure
Introduction to sql database on azureIntroduction to sql database on azure
Introduction to sql database on azure
 
Mcts chapter 2
Mcts chapter 2Mcts chapter 2
Mcts chapter 2
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
70-461 Querying Microsoft SQL Server 2012
70-461 Querying Microsoft SQL Server 201270-461 Querying Microsoft SQL Server 2012
70-461 Querying Microsoft SQL Server 2012
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Writing and optimizing T-SQL
Writing and optimizing T-SQLWriting and optimizing T-SQL
Writing and optimizing T-SQL
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
10 Ways To Abuse T-SQL
10 Ways To Abuse T-SQL10 Ways To Abuse T-SQL
10 Ways To Abuse T-SQL
 

Similar to Using T-SQL

SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
Andrew Brust
 
SQL Server Developer 70-433
SQL Server Developer 70-433SQL Server Developer 70-433
SQL Server Developer 70-433
jasonyousef
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
Axmed Mo.
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
Jonathan Levin
 
World2016_T5_S5_SQLServerFunctionalOverview
World2016_T5_S5_SQLServerFunctionalOverviewWorld2016_T5_S5_SQLServerFunctionalOverview
World2016_T5_S5_SQLServerFunctionalOverview
Farah Omer
 

Similar to Using T-SQL (20)

Ssn0020 ssis 2012 for beginners
Ssn0020   ssis 2012 for beginnersSsn0020   ssis 2012 for beginners
Ssn0020 ssis 2012 for beginners
 
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
 
SQL Server Developer 70-433
SQL Server Developer 70-433SQL Server Developer 70-433
SQL Server Developer 70-433
 
SQL Server 2008 For Developers
SQL Server 2008 For DevelopersSQL Server 2008 For Developers
SQL Server 2008 For Developers
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
SQL server 2016 New Features
SQL server 2016 New FeaturesSQL server 2016 New Features
SQL server 2016 New Features
 
SQL-Server Database.pdf
SQL-Server Database.pdfSQL-Server Database.pdf
SQL-Server Database.pdf
 
SQL Server 2008 certification
SQL Server 2008 certificationSQL Server 2008 certification
SQL Server 2008 certification
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
 
Migrating on premises workload to azure sql database
Migrating on premises workload to azure sql databaseMigrating on premises workload to azure sql database
Migrating on premises workload to azure sql database
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql
 
Querying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuerying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptx
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
World2016_T5_S5_SQLServerFunctionalOverview
World2016_T5_S5_SQLServerFunctionalOverviewWorld2016_T5_S5_SQLServerFunctionalOverview
World2016_T5_S5_SQLServerFunctionalOverview
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
NoSQL and MySQL: News about JSON
NoSQL and MySQL: News about JSONNoSQL and MySQL: News about JSON
NoSQL and MySQL: News about JSON
 
SQL Server 2016 What's New For Developers
SQL Server 2016  What's New For DevelopersSQL Server 2016  What's New For Developers
SQL Server 2016 What's New For Developers
 
An overview of microsoft data mining technology
An overview of microsoft data mining technologyAn overview of microsoft data mining technology
An overview of microsoft data mining technology
 

More from Antonios Chatzipavlis

More from Antonios Chatzipavlis (20)

Data virtualization using polybase
Data virtualization using polybaseData virtualization using polybase
Data virtualization using polybase
 
SQL server Backup Restore Revealed
SQL server Backup Restore RevealedSQL server Backup Restore Revealed
SQL server Backup Restore Revealed
 
Migrate SQL Workloads to Azure
Migrate SQL Workloads to AzureMigrate SQL Workloads to Azure
Migrate SQL Workloads to Azure
 
Machine Learning in SQL Server 2019
Machine Learning in SQL Server 2019Machine Learning in SQL Server 2019
Machine Learning in SQL Server 2019
 
Workload Management in SQL Server 2019
Workload Management in SQL Server 2019Workload Management in SQL Server 2019
Workload Management in SQL Server 2019
 
Loading Data into Azure SQL DW (Synapse Analytics)
Loading Data into Azure SQL DW (Synapse Analytics)Loading Data into Azure SQL DW (Synapse Analytics)
Loading Data into Azure SQL DW (Synapse Analytics)
 
Introduction to DAX Language
Introduction to DAX LanguageIntroduction to DAX Language
Introduction to DAX Language
 
Building diagnostic queries using DMVs and DMFs
Building diagnostic queries using DMVs and DMFs Building diagnostic queries using DMVs and DMFs
Building diagnostic queries using DMVs and DMFs
 
Exploring T-SQL Anti-Patterns
Exploring T-SQL Anti-Patterns Exploring T-SQL Anti-Patterns
Exploring T-SQL Anti-Patterns
 
Designing a modern data warehouse in azure
Designing a modern data warehouse in azure   Designing a modern data warehouse in azure
Designing a modern data warehouse in azure
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019
 
Designing a modern data warehouse in azure
Designing a modern data warehouse in azure   Designing a modern data warehouse in azure
Designing a modern data warehouse in azure
 
SQLServer Database Structures
SQLServer Database Structures SQLServer Database Structures
SQLServer Database Structures
 
Sqlschool 2017 recap - 2018 plans
Sqlschool 2017 recap - 2018 plansSqlschool 2017 recap - 2018 plans
Sqlschool 2017 recap - 2018 plans
 
Azure SQL Database for the SQL Server DBA - Azure Bootcamp Athens 2018
Azure SQL Database for the SQL Server DBA - Azure Bootcamp Athens 2018 Azure SQL Database for the SQL Server DBA - Azure Bootcamp Athens 2018
Azure SQL Database for the SQL Server DBA - Azure Bootcamp Athens 2018
 
Microsoft SQL Family and GDPR
Microsoft SQL Family and GDPRMicrosoft SQL Family and GDPR
Microsoft SQL Family and GDPR
 
Statistics and Indexes Internals
Statistics and Indexes InternalsStatistics and Indexes Internals
Statistics and Indexes Internals
 
Introduction to Azure Data Lake
Introduction to Azure Data LakeIntroduction to Azure Data Lake
Introduction to Azure Data Lake
 
Azure SQL Data Warehouse
Azure SQL Data Warehouse Azure SQL Data Warehouse
Azure SQL Data Warehouse
 
Introduction to azure document db
Introduction to azure document dbIntroduction to azure document db
Introduction to azure document db
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

Using T-SQL

  • 1. SQL Saturday Night Using T-SQL March 30, 2013 SQL Saturday Night #19
  • 2. Η παρουσίαση αυτή θα καταγραφεί ώστε να είναι διαθέσιμη για όσους θέλουν να την ξαναδούν, ή δεν είχαν την δυνατότητα να την παρακολουθήσουν σε πραγματικό χρόνο. Εάν κάποιος από τους παραβρισκόμενους σε αυτή έχει το οποιοδήποτε πρόβλημα ή αντίρρηση να είναι μέρος της καταγραφή αυτής, παρακαλείται να αποχωρήσει άμεσα. Σε διαφορετική περίπτωση η παραμονή σε αυτή εκλαμβάνεται ως αποδοχή της καταγραφής. Η παρουσίαση αυτή διατίθεται δωρεάν, και θα αρχίσει σε 1 λεπτό…
  • 3. Αυτή την στιγμή ο παρουσιαστής μιλάει και σας ζητάει να βεβαιώσετε ότι τον ακούτε. Εάν αυτό δεν είναι δυνατόν παρακαλείστε να αλλάξετε το χρώμα της κάρτας σας στο αντίστοιχο χρώμα ώστε να τον ενημερώσετε. Αυτό μπορεί να γίνει πατώντας την αντίστοιχη επιλογή που βρίσκεται στο πάνω δεξί μέρος του περιβάλλοντος του live meeting. Σας ευχαριστούμε για την συνεργασία.
  • 4. Using T-SQL SQL Saturday Night # 19 – March 30, 2013
  • 5. SP_WHO Sotiris Fivi Antonios Karras Panopoulou Chatzipavlis SQL Server Jr. DBA SQL Server Jr. DBA SQL Server Evangelist - Microsoft Student Partner - Microsoft Student Partner - MVP on SQL Server - N.T.U.A Student - N.T.U.A Student - MCSE on Data Platform - MCSA on SQL Server 2012 - Microsoft Trainer (MCT) - MCT Regional Leader
  • 6. SOCIAL CONNECTIONS @antoniosch @sqlschool SQL School Greece www.sqlschool.gr help@sqlschool.gr
  • 8. PRESENTATION TOPICS - 1 • Introduction to Microsoft SQL Server 2012 • SQL Server Management Studio • Introduction to T-SQL Querying • SELECT Statements / Queries • Querying Multiple Tables • Sorting and Filtering Data • Grouping and Aggregating Data
  • 9. PRESENTATION TOPICS - 2 • Using Sub-queries • Using Views, Table Value Functions and Table Expressions • Using Set Operators • Using Stored Procedures • Using Window Functions • What’s New in SQL Server 2012
  • 11. SQL SERVER ARCHITECTURE • Services • Instances • Tools
  • 12. SQL SERVER VERSIONS Umachandar Jayachandran former SQL Server MVP and currently a PM on the SQL Server Perf Team.
  • 14. SQL SERVER VERSIONS Operating Version Release Year Code Name Company System 1.0 1989 OS2 Aston Tate, Microsoft, Sybase 1.1 1991 OS2 Aston Tate, Microsoft, Sybase 4.2 1992 Windows Microsoft 4.21 1994 SQLNT Windows Microsoft 6.0 1995 SQL95 Windows Microsoft 6.5 1996 Hydra Windows Microsoft 7.0 1998 Sphinx Windows Microsoft 2000 2000 Shiloh Windows Microsoft 2005 2005 Yukon Windows Microsoft 2008 2008 Katmai Windows Microsoft 2008 R2 2010 Kilimanjaro Windows Microsoft 2012 2012 Denali Windows Microsoft
  • 15. SQL SERVER 2012 EDITIONS Main Editions Other Editions Enterprise Parallel Data Warehouse Standard Web Business Intelligence Developer Express Express LocalDB
  • 16. SQL SERVER DATABASES Containers Boundaries Tables Security Accounts Views Permissions Procedures Default Collations Functions Users Roles Schemas
  • 17. SQL SERVER SYSTEM DATABASES master The system configuration database. msdb The configuration database for the SQL Server Agent service and other system services. model Τhe template for new user databases. tempdb Used by the database engine to store temporary data such as work tables. Dropped and recreated each time SQL Server restarts resource Α hidden system configuration database that provides system objects to other databases. distribution The distribution database stores metadata and history data for all types of replication, and transactions for transactional replication.
  • 19.
  • 20. SQL SERVER MANAGEMENT STUDIO (SSMS) “SQL Server Management Studio is an integrated environment for accessing, configuring, managing, administering, and developing all components of SQL Server. SQL Server Management Studio combines a broad group of graphical tools with a number of rich script editors to provide access to SQL Server to developers and administrators of all skill levels. ”
  • 21. Using SQL Server Management Studio
  • 23. INTRODUCING TRANSACT-SQL (T-SQL) Is the language in which you will write your queries for SQL Server. Structure Query Language (SQL) Developed by IBM in 1970 Adopted as ANSI and ISO standards Widely used in industry SQL is declarative not procedural
  • 24. CATEGORIES OF T-SQL STATEMENTS Data Manipulation Language (DML) Statement for querying and modify data SELECT, INSERT, UPDATE, DELETE Data Definition Language (DDL) Statements for Objects definitions CREATE, ALTER, DROP Data Control Language (DCL) Statements for security permissions GRANT, DENY, REVOKE
  • 25. PREDICATES AND OPERATORS Predicates IN, BETWEEN, LIKE Operators Precedence 1 ( ) Parentheses Comparison Operators 2 *, /, % =, >, <, >=, <=, <>, !=, !>, !< 3 +, - Logical Operators 4 =, <, >, >=, <=, !=, !>, !< 5 NOT AND, OR, NOT 6 AND Arithmetic Operators 7 8 BETWEEN, IN, LIKE, OR = +, -, *, /, % Concatenation +
  • 26. FUNCTIONS CATEGORIES • Rowset Functions • Mathematical Functions • Aggregate Functions • Metadata Functions • Ranking Functions • Security Functions • Configuration Functions • String Functions • Conversion Functions • System Functions • Cursor Functions • System Statistical • Date and Time Data Functions Types and Functions • Logical Functions • Text and Image Functions
  • 27. VARIABLES • Local variables in T-SQL temporarily store a value of specific data type • Name begins with single @ sign • @@ reserved for system functions • Assigned a data type • Must be declared and used within the same batch • You can declare and initialize in the same statement (from SQL Server 2008 and later) DECLARE @variablename datatype [=init value] DECLARE @myVar INT = 20;
  • 28. EXPRESSIONS • Combination of identifiers, values and operators evaluated to obtain a single result • Can be used in many situations like • SELECT clause • WHERE clause • SET clause SELECT YEAR(SalesOrderDate) + 1 … SELECT Quantity * UnitPrice …
  • 29. CONTROL FLOW STATEMENTS • IF…ELSE • WHILE • BREAK • CONTINUE • BEGIN…END
  • 30. ERRORS AND ERROR HANDLING • @@error system function • RAISERROR • THROW • TRY…CATCH
  • 31. TRANSACTION CONTROL STATEMENTS • BEGIN TRANSACTION • COMMIT TRANSACTION • ROLLBACK TRANSACTION
  • 33. COMMENTS Block comments /* SELECT … other code… */ Inline comments -- inline comment DECLARE @myVar INT = 20; -- initial value
  • 34. BATCHES AND BATCH SEPARATOR • Batches are sets of commands sent to SQL Server as a unit • Batches determine variable scope and name resolution • To separate statements into batches SQL Server uses the GO keyword • GO is not a SQL Server command! • We can define our batch separator • GO n time feature added in SQL Server 2005 and later. DECLARE @CustomerID NCHAR(5) = ‘ANTON’; SELECT CustomerID, CompanyName FROM Orders WHERE CustomerID = @CustomerID; GO CREATE TABLE T(c1 INT); GO CREATE VIEW V AS SELECT * FROM T; GO
  • 35. SQL SERVER DATA TYPES • SQL Server defines a set of system data types for • storing data in columns, • holding values temporarily in variables, • for operating on data in expressions, • for passing parameters in stored procedures and functions • Data Types specify the • Type • Length • Precision • Scale
  • 36. SQL SERVER DATA TYPES CATEGORIES • Exact numeric • Approximate numeric • Date & Time • Character string • Unicode character strings • Binary string • Other data types
  • 37. EXACT NUMERIC DATA TYPES Data type Range Storage (bytes) tinyint 0 to 255 1 smallint -32,768 to 32,768 2 int 2^31 (-2,147,483,648) to 4 2^31-1 (2,147,483,647) bigint -2^63 - 2^63-1 8 (+/- 9 quintillion) bit 1, 0 or NULL 1 decimal - 10^38 +1 through 10^38 – 1 when 5-17 maximum precision is used numeric - 10^38 +1 through 10^38 – 1 when 5-17 maximum precision is used money -922,337,203,685,477.5808 to 8 922,337,203,685,477.5807 smallmoney - 214,748.3648 to 214,748.3647 4
  • 38. APPROXIMATE NUMERIC DATA TYPES Data Type Range Storage (bytes) float(n) - 1.79E+308 to -2.23E-308, 0 and 2.23E- Depends on value of n, 4 308 to 1.79E+308 or 8 bytes real - 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 4 38 to 3.40E + 38 • float(24) is the ISO synonym for float • In float(n), n is the number of bytes used to store the mantissa of the float number in scientific notation • Values of float are truncated when converted to integer types
  • 39. DATE & TIME DATA TYPES • Older versions of SQL Server supported only DATETIME and SMALLDATETIME • DATE, TIME, DATETIME2, and DATETIMEOFFSET introduced in SQL Server 2008 • SQL Server 2012 adds new functionality for working with date and time data types
  • 40. DATE & TIME DATA TYPES Storage Recommended Entry Data Type Date Range Accuracy (bytes) Format DATETIME 8 January 1, 1753 to 3-1/3 'YYMMDD December 31, 9999 milliseconds hh:mm:ss:nnn' SMALLDATETIME 4 January 1, 1900 to 1 minute 'YYMMDD June 6, 2079 hh:mm:ss:nnn' DATETIME2 6 to 8 January 1, 0001 to 100 'YYMMDD December 31, 9999 nanoseconds hh:mm:ss.nnnn nn' DATE 3 January 1, 0001 to 1 day 'YYYY-MM-DD' December 31, 9999 TIME 3 to 5 100 'hh:mm:ss:nnn nanoseconds nnnn' DATETIMEOFFSET 8 to 10 January 1, 0001 to 100 'YY-MM-DD December 31, 9999 nanoseconds hh:mm:ss:nnnn nnn [+|- ]hh:mm'
  • 41. CHARACTER STRING DATA TYPES • One byte per character Data Type Range Storage CHAR(n) 1-8000 characters n bytes, padded Fixed Length VARCHAR(n) 1-8000 characters n+2 bytes Variable Length VARCHAR(MAX) 1-2^31-1 characters Actual length + 2 Variable Length • TEXT deprecated • Use VARCHAR(MAX) instead
  • 42. UNICODE CHARACTER STRING DATA TYPES • Two bytes per character Data Type Range Storage NCHAR(n) 1-8000 characters 2*n bytes, padded Fixed Length NVARCHAR(n) 1-8000 characters (2*n)+2 bytes Variable Length NVARCHAR(MAX) 1-2^31-1 characters Actual length + 2 Variable Length • NTEXT deprecated • Use NVARCHAR(MAX) instead
  • 43. BINARY STRING Data Type Range Storage (bytes) binary(n) 1-8000 bytes n bytes varbinary(n) 1-8000 bytes n bytes + 2 varbinary(MAX) 1-2.1 billion (approx) bytes actual length + 2 • IMAGE deprecated • Use VARBINARY(MAX) instead
  • 44. OTHER DATA TYPES Data Type Range Storage Remarks (bytes) rowversion Auto-generated 8 Successor type to timestamp uniqueidentifier Auto-generated 16 Globally unique identifier (GUID) xml 0-2 GB 0-2 GB Stores XML in native hierarchical structure cursor N/A N/A Not a storage data type hierarchyid N/A Depends on Represents position in a content hierarchy sql_variant 0-8000 bytes Depends on Can store data of various content data types table N/A N/A Not a storage data type, used for query and programmatic operations
  • 45. DATA TYPES PRESENTENCE • Data type precedence determines which data type will be chosen when expressions of different types are combined • Data type with the lower precedence is converted to the data type with the higher precedence • Important for understanding implicit conversions • Conversion to type of lower precedence must be made explicitly (with CAST function) • Example (low to high): • CHAR -> VARCHAR -> NVARCHAR -> TINYINT -> INT -> DECIMAL -> TIME -> DATE -> DATETIME2 -> XML
  • 46. DATA TYPES CONVERSION • Data type conversion scenarios • When data is moved, compared, or combined with other data • During variable assignment • Implicit conversion • When comparing data of one type to another • Transparent to user WHERE <column of smallint type> = <value of int type> • Explicit conversion • Uses CAST or CONVERT functions CAST(unitprice AS int) • Not all conversions allowed by SQL Server
  • 47. SELECT Statement The Select Statement and Writing Queries
  • 48. SELECT STATEMENT – MAIN CLAUSES • [ WITH <common_table_expression>] • SELECT select_list [ INTO new_table ] • [ FROM table_source ] [ WHERE search_condition ] • [ GROUP BY group_by_expression ] • [ HAVING search_condition ] • [ ORDER BY order_expression [ ASC | DESC ] ]
  • 49. SELECT STATEMENT – LOGICAL PROCESSING • FROM • ON • JOIN • WHERE • GROUP BY • WITH CUBE or WITH ROLLUP • HAVING • SELECT • DISTINCT • ORDER BY • TOP
  • 50. Select statement – Full statement
  • 51. SELECT DISTINCT • Specifies that only unique rows can appear in the result set • Removes duplicates based on column list results, not source table • Provides uniqueness across set of selected columns • Removes rows already operated on by WHERE, HAVING, and GROUP BY clauses • Some queries may improve performance by filtering out duplicates prior to execution of SELECT clause
  • 52. COLUMN ALIASES • Column aliases using AS SELECT orderid, unitprice, qty AS quantity FROM OrderDetails; • Column aliases using = SELECT orderid, unitprice, quantity = qty FROM OrderDetails; • Accidental column aliases SELECT orderid, unitprice quantity FROM OrderDetails;
  • 53. TABLE ALIASES • Create table aliases in the FROM clause • Table aliases with AS SELECT custid, orderdate FROM dbo.Orders AS SO; • Table aliases without AS SELECT custid, orderdate FROM Sales.Orders SO; • Using table aliases in the SELECT clause SELECT SO.custid, SO.orderdate FROM Sales.Orders AS SO;
  • 54. SELECT STATEMENT – CASE EXPRESSION Simple Case expression CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END Searched CASE expression CASE WHEN boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END
  • 57. JOIN CLAUSE – INTRODUCTION • By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. • Three types of Joins 1. Inner Joins, which use a comparison operator to match rows from two tables based on the values in common columns from each table 2. Outer Joins, in which all the rows of the specified table(s) are returned, not just the ones in which the joined columns match 3. Cross Joins, which produce the Cartesian product of the tables involved in the join (if there is no WHERE clause present) 4. Self Joins which you need to compare and retrieve data stored in the same table • Main Join Clause SELECT select_list FROM first_table join_type second_table [ON (join_condition)] [WHERE (search_condition)]
  • 58. T-SQL JOIN SYNTAX CHOICES • ANSI SQL-92 • Tables joined by JOIN operator in FROM Clause • Preferred syntax SELECT ... FROM Table1 JOIN Table2 ON <on_predicate> • ANSI SQL-89 • Tables joined by commas in FROM Clause • Not recommended: accidental Cartesian products! SELECT ... FROM Table1, Table2 WHERE <where_predicate>
  • 60. Sorting & Filtering Sorting and Filtering Data
  • 61. SORTING/FILTERING – SORTING • You can sort data retrieved by a SELECT statement using the ORDER BY clause • ORDER BY clause syntax: ORDER BY order_by_expression [ COLLATE collation_name ] [ ASC | DESC ] [ ,...n ] [ <offset_fetch> ]
  • 62. SORTING/FILTERING – COLLATION • Specifies that the ORDER BY operation should be performed according to the collation specified in collation_name • Using collations to sort data, depending on encoding or case sensitive/accent sensitive options
  • 63. SORTING/FILTERING – TOP/OFFSET <offset_fetch> ::= { OFFSET { integer_constant | offset_row_count_expression } { ROW | ROWS } [ FETCH { FIRST | NEXT } {integer_constant | fetch_row_count_expression } { ROW | ROWS } ONLY ] } • Specifies the number of rows to return after the OFFSET clause has been processed. The value can be an integer constant or expression that is greater than or equal to one. • Both OFFSET and FETCH can use variables as input and thus are able to be optimized for specified values of those values using the OPTIMIZE FOR hint
  • 64. SORTING/FILTERING – WORKING WITH NULL VALUES • NULL has three logical interpretations • Unknown value • Unavailable value • Not supported value • SET ANSI_NULLS { ON | OFF } • Setting ANSI_NULLS ON, causes the SELECT statements using WHERE column_name = NULL to return zero rows even if there are null values in column_name ( thus operators =, <> follow the ISO standard) • Option in future versions ANSI_NULLS will by default be set to ON
  • 67. AGGREGATE FUNCTIONS • Aggregate functions perform a calculation on a set of values and return a single value. • Deterministic in nature. They return the same value any time that they are called by using a specific set of input values. List of Aggregate Functions AVG MIN CHECKSUM_AVG SUM COUNT STDEV COUNT_BIG STDEVP GROUPING VAR GROUPING_ID VARP MAX
  • 68. GROUP BY CLAUSE • Groups sets of rows, using the values of one or more columns or expressions. • Each group is represented by one and only one row. • Usually aggregates are used to provide the grouping criterion • Can filter the groups created using the HAVING keyword • A GROUP BY clause can include GROUPING SETS, CUBE AND ROLLUP keywords
  • 69. DISTINCT & NULL WITH AGGREGATE FUNCTIONS • Use DISTINCT with aggregate functions to summarize only unique values • DISTINCT aggregates eliminate duplicate values, not rows (unlike SELECT DISTINCT) • Most aggregate functions ignore NULL • COUNT(<column>) ignores NULL • COUNT(*) counts all rows • NULL may produce incorrect results (such as use of AVG) • Use ISNULL or COALESCE to replace NULLs before aggregating
  • 70. GROUPING SETS • GROUPING SETS subclause builds on T-SQL GROUP BY clause • Allows multiple groupings to be defined in same query SELECT <column list with aggregate(s)> FROM <source> GROUP BY GROUPING SETS( (<column_name>),--one or more columns (<column_name>),--one or more columns () -- empty parentheses if aggregating all rows );
  • 71. GROUPING_ID • Multiple grouping sets present a problem in identifying the source of each row in the result set • NULLs could come from the source data or could be a placeholder in the grouping set • The GROUPING_ID function provides a method to mark a row with a 1 or 0 to identify which grouping set the row is a member of SELECT GROUPING_ID(Category)AS grpCat, GROUPING_ID(CustomerID) AS grpCust, Category, CustomerID, SUM(Qty) AS TotalQty FROM CategorySales GROUP BY CUBE(Category,CustomerID) ORDER BY Category, CustomerID;
  • 73. CUBE/ROLLUP • CUBE provides shortcut for defining grouping sets given a list of columns • All possible combinations of grouping sets created SELECT <column list with aggregate(s)> FROM <source> GROUP BY CUBE (<column_name>, <column_name>, ...); • ROLLUP provides shortcut for defining grouping sets, creates combinations assuming input columns form a hierarchy SELECT <column list with aggregate(s)> FROM <source> GROUP BY CUBE (<column_name>, <column_name>, ...);
  • 74. PIVOT • Pivoting data is rotating data from a rows-based orientation to a columns-based orientation • Distinct values from a single column are projected across as headings for other columns - may include aggregation
  • 75. PIVOT SYNTAX • Pivoting includes three phases: 1. Grouping determines which element gets a row in the result set 2. Spreading provides the distinct values to be pivoted across 3. Aggregation performs an aggregation function (such as SUM) Grouping SELECT Category, [2006],[2007],[2008] FROM ( SELECT Category, Qty, Orderyear FROM Sales.CategoryQtyYear) AS D PIVOT(SUM(QTY) FOR orderyear IN([2006],[2007],[2008]) Spreading ) AS pvt; Aggregation
  • 76. UNPIVOT • Unpivoting data is rotating data from a columns-based orientation to a rows-based orientation • Spreads or splits values from one source row into one or more target rows • Each source row becomes one or more rows in result set based on number of columns being pivoted
  • 77. UNPIVOT SYNTAX • Unpivoting includes three elements: • Source columns to be unpivoted • Name to be assigned to new values column • Name to be assigned to names columns SELECT category, qty, orderyear FROM CategorySales UNPIVOT(qty FOR orderyear IN([2006],[2007],[2008])) AS unpvt;
  • 78. CUBE, ROLLUP PIVOT, UNPIVOT ,
  • 79. Using Sub-queries What is and How to write Sub-queries
  • 80. SUBQUERIES • Nesting queries within queries • Outer query : result set returned to caller • Inner query : result set returned to outer query • Types of subqueries based on return value: • Single –valued (scalar) • Multivalued • Table-valued
  • 81. DEPENDENCY ON OUTER QUERY • Self-Contained Subqueries • Subquery not dependent on outer query • Can be evaluated by executing the subquery once and substituting the result into the WHERE clause of the outer query • Easier to debug • Correlated Subqueries • The subquery depends on the outer query for its values • The subquery is executed repeatedly, once for each row that might be selected by the outer query • Known as repeating subquery
  • 82. USE • Anywhere an expression is allowed • Not in an ORDER BY clause • Subqueries within subqueries • Commonly used with (NOT) IN and EXISTS
  • 83. EXISTS PREDICATE • Tests existence of rows. • Returns TRUE or FALSE • Usually * consists the SELECT list of the subquery, no reason to list column names • Enough to determine whether the subquery returns at least one row, so engine doesn’t need to process all rows
  • 85. Views, TVFs, Table Expressions Using Views, Table Value Functions and Table Expressions
  • 86. VIEWS A view is a virtual table whose contents (rows and columns) are defined by a query. • The rows and columns of data come from tables referenced in the query defining the view and are produced dynamically when the view is referenced. • Updatable view: modifying an underlying base table through the view • Indexed view: The view definition has been computed and the resulting data stored just like a table.
  • 87. USE • To focus, simplify, and customize the perception each user has of the database. • As a security mechanism by allowing users to access data through the view, without granting the users permissions to directly access the underlying base tables. • To provide a backward compatible interface to emulate a table whose schema has changed.
  • 88. OPTIONS • CHECK OPTION Prevent data modifications through the view that conflict with the views filter • ENCRYPTION Encrypt text of the CREATE VIEW statement in sys.syscomments • SCHEMABINDING Prevent modification of underlying views that would affect the view definition
  • 90. INLINE TABLE-VALUED FUNCTIONS • Table-valued functions (TVFs) are named table expressions with definitions stored in a database • TVFs return a virtual table to the calling query • SQL Server provides two types of TVFs • Inline, based on a single SELECT statement • Multi-statement, which creates and loads a table variable • Unlike views, TVFs support input parameters • Inline TVFs may be thought of as parameterized views
  • 91. WRITING INLINE TVF • Table-valued functions are created by administrators and developers • Create and name function and optional parameters with CREATE FUNCTION • Declare return type as TABLE • Define inline SELECT statement following RETURN CREATE FUNCTION Sales.fn_LineTotal (@orderid INT) RETURNS TABLE AS RETURN SELECT orderid, CAST((qty * unitprice * (1 - discount)) AS DECIMAL(8, 2)) AS line_total FROM OrderDetails WHERE orderid = @orderid ;
  • 92. Inline Table Value Functions
  • 93. DERIVED TABLES • Derived tables are named query expressions created within an outer SELECT statement • Not stored in database – represents a virtual relational table • When processed, unpacked into query against underlying referenced objects • Allow you to write more modular queries SELECT <column_list> FROM ( <derived_table_definition> ) AS <derived_table_alias>; • Scope of a derived table is the query in which it is defined
  • 95. COMMON TABLE EXPRESSIONS • CTEs are named table expressions defined in a query • CTEs are similar to derived tables in scope and naming requirements • Unlike derived tables, CTEs support multiple definitions, multiple references, and recursion WITH <CTE_name> AS ( <CTE_definition> ) <outer query referencing CTE>;
  • 96. WRITING CTE • Define the table expression in WITH clause • Assign column aliases (inline or external) • Pass arguments if desired • Reference the CTE in the outer query WITH CTE_year AS ( SELECT YEAR(orderdate) AS orderyear, customerid FROM Orders ) SELECT orderyear, COUNT(DISTINCT customerid) AS cust_count FROM CTE_year GROUP BY orderyear;
  • 99. SET OPERATORS Set operators combine results from two or more queries into a single result set. • The number and the order of the columns must be the same in all queries. • The data types must be compatible • ORDER BY clause applied to result of operator • Names of columns in result are specified by the first query • NULLS are equal Input Query 1 set operator Input Query 2 [ORDER BY … ]
  • 100. SET OPERATORS • UNION: returns all rows that belong to at least one of the input queries. • By default result set has no duplicates. To get result set with duplicates specify ALL option. • INTERSECT: returns any distinct values that are returned by both the left query and the right one. • EXCEPT: returns any distinct values from the left query that are not also found on the right query.
  • 101. APPLY • Invoke a table-valued function for each row returned by an outer table expression of a query. • CROSS APPLY returns only rows from the outer table that produce a result set from the table- valued function. • OUTER APPLY returns both rows that produce a result set, and rows that do not, with NULL values in the columns produced by the table-valued function.
  • 104. STORED PROCEDURES A stored procedure in SQL Server is a group of one or more Transact-SQL statements which can : • Accept input parameters and return multiple values in the form of output parameters to the calling program. • Contain programming statements that perform operations in the database. These include calling other procedures. • Return a status value to a calling program to indicate success or failure (and the reason for failure)
  • 105. BENEFITS • Reduced server/client network traffic • Stronger security • Reuse of code • Easier maintenance • Improved performance
  • 108. SQL WINDOWING Window functions are functions applied to sets of rows defined by a clause called OVER They are used mainly for analytical purposes allowing you to calculate running totals, calculate moving averages, identify gaps and islands in your data, and perform many other computations These functions are based on the concept of windowing in standard SQL, which is both an ISO and ANSI standard The idea behind this concept is to allow you to apply various calculations to a set, or window, of rows and return a single value Window functions can help to solve a wide variety of querying tasks by helping you express set calculations more easily, intuitively, and efficiently than ever before
  • 109. THE SYNTAX function_name(<arguments>) OVER( [ <window partition clause> ] [ <window order clause> [ <window frame clause> ] ] )
  • 110. OVER CLAUSE OVER defines a window, or set, of rows to be used by a window function, including any ordering With a specified window partition clause, the OVER clause restricts the set of rows to those with the same values in the partitioning elements By itself, OVER() is unrestricted and includes all rows Multiple OVER clauses can be used in a single query, each with its own partitioning and ordering, if needed
  • 111. WINDOW PARTITION CLAUSE The partitioning element allows you to restrict the window to only those rows that have the same values in the partitioning attributes as the current row. SELECT orderid, custid, val, SUM(val) OVER() AS sumall, SUM(val) OVER(PARTITION BY custid) AS sumcust FROM OrderValues AS O1;
  • 112. WINDOW ORDER CLAUSE The ordering element defines the ordering for the calculation, if relevant, within the partition SELECT custid, orderid, val, RANK() OVER(ORDER BY val DESC) AS rnk_all, RANK() OVER(PARTITION BY custid ORDER BY val DESC) AS rnk_cust FROM Orders;
  • 113. WINDOW FRAME CLAUSE Framing is another option that enables you to further restrict the rows in the window partition. SELECT empid, ordermonth, qty, SUM(qty) OVER(PARTITION BY empid ORDER BY ordermonth ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runqty FROM EmpOrders;
  • 114. CONCEPTUAL RELATIONSHIP BETWEEN WINDOW ELEMENTS Result set (OVER) Window partition (PARTITION BY) Frame (ROWS BETWEEN)
  • 115. WINDOW AGGREGATE FUNCTIONS • Similar to grouped aggregate functions • SUM, MIN, MAX, etc. • Applied to windows defined by OVER clause • Window aggregate functions support partitioning, ordering, and framing SELECT custid, ordermonth, qty, SUM(qty) OVER(PARTITION BY custid) AS totalpercust FROM Sales.CustOrders;
  • 116. WINDOW RANKING FUNCTIONS • Ranking functions require a window order clause • Partitioning is optional • To display results in sorted order still requires ORDER BY! Function Description RANK Returns the rank of each row within the partition of a result set. May include ties and gaps. DENSE_RANK Returns the rank of each row within the partition of a result set. May include ties. Will not include gaps. ROW_NUMBER Returns a unique sequential row number within partition based on current order. NTILE Distributes the rows in an ordered partition into a specified number of groups. Returns the number of the group to which the current row belongs.
  • 117. WINDOW DISTRIBUTION FUNCTIONS • Window distribution functions perform statistical analysis on data, and require a window order clause • Rank distribution performed with PERCENT_RANK and CUME_DIST • Inverse distribution performed with PERCENTILE_CONT and PERCENTILE_DISC
  • 118. WINDOW OFFSET FUNCTIONS • Window offset functions allow comparisons between rows in a set without the need for a self-join • Offset functions operate on an position relative to the current row, or to the start or end of the window frame Function Description LAG Returns an expression from a previous row that is a defined offset from the current row. Returns NULL if no row at specified position. LEAD Returns an expression from a later row that is a defined offset from the current row. Returns NULL if no row at specified position. FIRST_VALUE Returns the first value in the current window frame. Requires window ordering to be meaningful. LAST_VALUE Returns the last value in the current window frame. Requires window ordering to be meaningful.
  • 120. What’s New in SQL Server 2012 Improvements of T-SQL in SQL Server 2012
  • 121. USING SEQUENCES • Sequence objects added in SQL Server 2012 • Independent objects in database • More flexible than the IDENTITY property • Can be used as default value for a column • Manage with CREATE/ALTER/DROP statements • Retrieve value with the NEXT VALUE FOR clause -- Define a sequence CREATE SEQUENCE dbo.InvoiceSeq AS INT START WITH 1 INCREMENT BY 1; -- Retrieve next available value from sequence SELECT NEXT VALUE FOR dbo.InvoiceSeq;
  • 122. USING MERGE TO MODIFY DATA • MERGE modifies data based on a condition • When the source matches the target • When the source has no match in the target • When the target has no match in the source MERGE INTO schema_name.table_name AS TargetTbl USING (SELECT <select_list>) AS SourceTbl ON (TargetTbl.col1 = SourceTbl.col1) WHEN MATCHED THEN UPDATE SET col2 = SourceTbl.col2 WHEN NOT MATCHED THEN INSERT (<column_list>) VALUES (<value_list>);
  • 124. NEW CONVERSION FUNCTIONS • PARSE SELECT PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-US') AS Result; Result : 2010-12-13 00:00:00.0000000 • TRY_CONVERT SELECT CASE WHEN TRY_CONVERT(float, 'test') IS NULL THEN 'Cast failed' ELSE 'Cast succeeded' END AS Result; • TRY_PARSE SELECT TRY_PARSE('AAAAA' AS datetime2 USING 'en-US') AS Result; Result : NULL
  • 126. DATEFROMPARTS • Returns a date value with the date portion set to the specified year, month and day, and the time portion set to the default. • If the arguments are not valid, then an error is raised. • If required arguments are null, then null is returned. SELECT DATEFROMPARTS ( 2010, 12, 31 ) AS Result; Result 2010-12-31
  • 127. DATETIME2FROMPARTS • Returns a fully initialized datetime2 value. • If the arguments are not valid, an error is raised. • If required arguments are null, then null is returned. • If the precision argument is null, then an error is raised. SELECT DATETIME2FROMPARTS( 2010, 12, 31, 23, 59, 59, 0, 0 ); Result 2010-12-31 23:59:59.0000000
  • 128. DATETIMEFROMPARTS • Returns a fully initialized datetime value. • If the arguments are not valid, then an error is raised. • If required arguments are null, then a null is returned. SELECT DATETIMEFROMPARTS( 2010, 12, 31, 23, 59, 59, 0 ); Result 2010-12-31 23:59:59.000
  • 129. DATETIMEOFFSETFROMPARTS • Returns a fully initialized datetimeoffset data type. • The offset arguments are used to represent the time zone offset. • If the offset arguments are omitted, then the time zone offset is assumed to be 00:00. • If the offset arguments are specified, then both arguments must be present and both must be positive or negative. • If minute_offset is specified without hour_offset, an error is raised. • If other arguments are not valid, then an error is raised. • If required arguments are null, then a null is returned. • If the precision argument is null, then an error is raised. SELECT DATETIMEOFFSETFROMPARTS(2010,12,31,14,23,23,0,12,0,7); Result 2010-12-07 00:00:00.0000000 +00:00
  • 130. EOMONTH • Returns the last day of the month that contains the specified date, with an optional offset. DECLARE @date DATETIME = '12/1/2011'; SELECT EOMONTH ( @date ) AS Result; GO Result 2011-12-31
  • 131. SMALLDATETIMEFROMPARTS • Returns a smalldatetime value for the specified date and time. SELECT SMALLDATETIMEFROMPARTS ( 2010, 12, 31, 23, 59 ); Result 2011-01-01 00:00:00
  • 132. TIMEFROMPARTS • Returns a fully initialized time value. • If the arguments are invalid, then an error is raised. • If any of the parameters are null, null is returned. • If the precision argument is null, then an error is raised. SELECT TIMEFROMPARTS ( 23, 59, 59, 0, 0 ) AS Result; Result 23:59:59.0000000
  • 134. CHOOSE • Returns the data type with the highest precedence from the set of types passed to the function • CHOOSE acts like an index into an array, where the array is composed of the arguments that follow the index argument. SELECT CHOOSE (3,'Manager','Director','Developer','Tester'); Result Developer
  • 135. IIF • Returns the data type with the highest precedence from the types in true_value and false_value • IIF is a shorthand way for writing a CASE expression. DECLARE @a int = 45, @b int = 40; SELECT IIF ( @a > @b, 'TRUE', 'FALSE' ) AS Result; GO Result TRUE
  • 137. CONCAT • Returns a string that is the result of concatenating two or more string values. SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' ); Result Happy Birthday 11/25
  • 138. FORMAT • Returns a value formatted with the specified format and optional culture. DECLARE @d DATETIME = '10/01/2011'; SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result' ,FORMAT ( @d, 'd', 'en-gb' ) AS 'GB English Result' ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'; US English Result : 10/1/2011 Result GB English Result : 01/10/2011 German Result : 01.01.2011
  • 140. SUMMARY • Introduction to Microsoft SQL Server 2012 • SQL Server Management Studio • Introduction to T-SQL Querying • SELECT Statements / Queries • Querying Multiple Tables • Sorting and Filtering Data • Grouping and Aggregating Data
  • 141. SUMMARY • Using Sub-queries • Using Views, Table Value Functions and Table Expressions • Using Set Operators • Using Stored Procedures • Using Window Functions • What’s New in SQL Server 2012
  • 143. SELECT KNOWLEDGE FROM SQL SERVER