Relational Database Design Structured Query Language (SQL)
A Database Structure
Database Building Blocks
Structure of a Relational Database
Training Database Schema
Course Outline Executing a Simple Query Performing a Conditional Search Working with Functions Organizing Data Retrieving Data from Tables Presenting Query Results
Executing a Simple Query Connect to the SQL Database Query a Database Save a Query Modify a Query Execute a Saved Query
SSMS Shortcuts
Same category of information Tables Header row Row Same category of information Column Related information
Information retrieved Databases Database Table 1 Table 2 Table 3 Table 4 Information searched Database objects Information retrieved
Databases (Cont.)
Databases (Cont.) Default databases Customized databases
Servers Higher performance No user Manage resource Provide services Network Client 1 Client 2 Client 3 Server
Clients Client 1 Client 2 Client 3 Server Connected to the same network as the server Displays result Requests the service of the server
Syntax Clauses in precise order Placeholders
SQL Statements Appropriate syntax Optional clause Essential clauses Column names Essential clauses
Queries Table name Column names Condition Database Output
SQL Logical Query Processing Steps Clause Order Logical Processing Steps SELECT FROM JOIN____ON____ WHERE GROUP BY HAVING ORDER BY FROM ON OUTER WHERE GROUP BY CUBE | ROLLUP HAVING SELECT DISTINCT ORDER BY TOP
The SELECT Statement FROM clause SELECT clause Table name Column names
The SELECT Statement (Cont.) Returns all columns from titles table Titles
characters are allowed Data Types Alphanumeric values Only numeric values are allowed Data types characters are allowed Numeric values
Datatypes
Comments Characters to enclose comment SQL statement as multiple lines of comment Characters to enclose comment
Comments (Cont.) Explains the code
Comments (Cont.) Comment not meant to execute
Performing a Conditional Search Search Using a Simple Condition Compare Column Values Search Using Multiple Conditions Search for a Range of Values and Null Values Retrieve Data Based on Patterns
Search criteria used to search selected values in a table Conditions Value Search criteria used to search selected values in a table Column name
Conditions (Cont.) Calculation performed on numeric values Using multiple search conditions Calculation performed on numeric values
The Process of a Conditional Search
Operators Operator Column name Value Condition Word
Operators (Cont.) Condition Value WHERE clause Column name Operator
Operator used in condition The WHERE Clause Value Column name Operator used in condition
The WHERE Clause (Cont.) Condition 1 Condition 2
Comparison Operators Comparison operator Column name Value Condition
Arithmetic Operators Arithmetic operator Date column Numeric value Calculation performed on date column Numeric value Date column Arithmetic operator Calculation performed on numeric values
Compound Assignment Operators Column Variable Column Value
Column Aliasing Calculation performed on column name Alphanumeric character Column alias displayed as column name
AND operator returns TRUE when both the boolean conditions are true Logical Operators AND operator returns TRUE when both the boolean conditions are true Boolean condition 2 Boolean condition 1
Logical Operators (Cont.) AND operator is evaluated before OR operator Condition returns TRUE or FALSE
Logical Operators (Cont.) Condition 1 Logical operator Condition 3 Condition 2
The AND , OR, and NOT Operators Boolean condition 1 Boolean condition 2 OR operator returns TRUE when either of the boolean conditions is true
The AND , OR, and NOT Operators (Cont.) NOT operator negates the result of the condition
The AND , OR, and NOT Operators (Cont.) NOT operator used with AND operator
The BETWEEN .. AND Operator Conditional statement End value Start value Range of values Specifies values outside of range
IN operator returns the rows that match the list of values The In Operator IN operator returns the rows that match the list of values List of values within parentheses Column name
The NULL Value
Displays only null value Rows that contain null values The IS NULL Clause Condition 1 Condition 2 Displays only null value Rows that contain null values
The Is Null Clause (Cont.) Search condition Checks whether the values are not null Logical operator
Wildcards Wildcard with a character Column name
Wildcards (Cont.) Wildcard for single character unlimited number of characters
Pattern Matching Pattern Wildcard used to search characters Output
Working with Functions Perform Date Calculations Calculate Data Using Aggregate Functions Manipulate String Values
Functions Parameters Function name Column name Function without
Date Functions Date function Date column Date parameter Numeric values Date and time values
Date and Time Data Types Datetimeoffset value Datetimeoffset data type Date data type Time data type Date value Time value Datetime2 value Datetime2 data type
Aggregate Functions Function name Reference to values Summary values Single row output
Keywords Displayed in color Word reserved for retrieving data entering table name
Keyword used outside its predetermined context Keywords (Cont.) Keyword used outside its predetermined context
The DISTINCT Keyword No duplicate values Column names DISTINCT keyword
arithmetic calculation String enclosed in single quotes Strings Case is ignored during compilation Cannot be used in arithmetic calculation String enclosed in single quotes Special characters
String Functions String function String input Numeric values
Case Conversion Functions Converts lower case characters to upper case Converts upper case characters to lower case Column name Output of the UPPER function Output of the LOWER function
Leading and Trailing Spaces Maximum number of characters that can be stored in a column Leading space Trailing space Characters stored in the column
The Trim Function Removes blank spaces before a column value after a column value String values No space in front of values No space after values
Character Extraction
The SUBSTRING Function Extracted substrings Integer that specifies number of characters to be extracted Column name Integer specifies where the substring begins String value
Trailing spaces present Concatenation Concatenated strings Same data type Trailing spaces present in the name column Expression 1 Expression 2 String concatenation operator
Organizing Data Sort Data Rank Data Group Data Filter Grouped Data Summarize Grouped Data Use PIVOT and UNPIVOT Operators
Arranged in ascending order of slprice Sorting Lowest value Highest value Arranged in ascending order of slprice
Arranged in descending order of slprice Sorting (Cont.) Highest value Lowest value Arranged in descending order of slprice
The ORDER BY Clause Entered at the end of the SELECT statement Values in the descending order Values in the ascending order Sorts the output in ascending order Sorts the output in descending order Column name Entered at the end of the SELECT statement Column name
The Ranking Functions Ranking functions Column alias name Lists the values of quantity in the descending order Ranking values with gaps in between them Partitions the rows of repid column Ranking functions Column alias name
The RANK Function Ranking values with gaps in between them Lists the values of quantity in the descending order Column alias name Partitions the rows of repid column
The DENSE_RANK Function Consecutive rank values Lists the values of quantity in the descending order Column alias name Partitions the rows of repid column
The ROW_NUMBER Function Sequential numbering of each row Lists the values of quantity in the descending order Column alias name Partitions the rows of repid column
The NTILE Function Ranks after grouping and partition Lists the values of quantity in the descending order Column alias name Partitions the rows of repid column
Groups Input Table Records of each group Collection of records are listed here Collection of records based on one or more columns Input Table Output Table
The GROUP BY Clause Column alias cannot be used in the GROUP BY clause Aggregate function returns summary values for groups Grouped based on two columns
The GROUP BY Clause (Cont.) Entire list included in the GROUP BY clause Non-aggregate list in the SELECT clause
CUBE and ROLLUP Subclauses Column values Hierarchy of grouping sets
CUBE and ROLLUP Subclauses (Cont.) Column values Hierarchy of grouping sets
Column values in grouping sets
The HAVING Clause Aggregate function Search condition applied for the groups Aggregate function HAVING clause used with the GROUP BY clause
The HAVING Clause (Cont.) SELECT Statement without the GROUP BY clause HAVING clause behaves like the WHERE clause
The CUBE and ROLLUP Operators Operator entered at the end of the GROUP BY clause Summary column values displayed as null Summary rows for each group Output of the GROUP BY clause Group based on two columns
The CUBE and ROLLUP Operators (Cont.) Operator entered at the end of the GROUP BY clause Group based on two columns Output of the GROUP BY clause Summary column values displayed as null Summary rows for each group Summary value for all groups 86
The PIVOT and UNPIVOT Operators Pivoted columns Alias name for the pivot table Aggregate functions Non pivoted columns Column value converted into header Summary values
Retrieving Data from Tables Combine Results of Two Queries Compare Results of Two Queries Retrieve Data by Joining Tables Check for Unmatched Records Retrieve Information from a Single Table Using Joins
The UNION Operator Number of columns in each statement is identical SELECT statement 2 SELECT statement 1 Keyword entered between two SELECT statements Number of columns in each statement is identical Data type of both columns is compatible Operator used to display duplicate rows
Column common to both tables Joins Column common to both tables Table 2 Table 1 Output
Keyword entered between two table names The Cross Join slspers titles Output containing every row of slspers table paired with every row of titles table Keyword entered between two table names Tables to be joined
The Inner Join Tables to be joined Keyword entered between two table names Condition containing the comparison operator Tables to be joined Records that have matching values
The Outer Join Column used to join tables Keyword entered between two table names ON clause containing the condition Column used to join tables Matching rows from both tables Rows from one table Output after joining two tables
Table alias names used instead of original names The Table Alias Name Full name of the tables Table alias names used instead of original names Table alias names
The Self-Join Table alias used in condition Keyword entered between table names Table alias used in condition ON clause containing the comparison operator Two table alias names assigned to a single table Potential Customers Relating data in a table to itself
Presenting Query Results Save the Query Result Generate an XML Report
Reports Retrieved from titles table sales table
The FOR Clause Column name Table name Returns results in a Column value Table name Returns results in a nested XML tree Returns results as XML type Returns columns as sub elements
Course Outline Using Subqueries to Perform Advanced Querying Manipulating Table Data Manipulating the Table Structure Working with Views Indexing Data Managing Transactions
Using Subqueries to Perform Advanced Querying Search Based on Unknown Values Compare a Value with Unknown Values Search Based on the Existence of Records Generate Output Using Correlated Subqueries Filter Grouped Data Within Subqueries Perform Multiple-Level Subqueries
Outer Queries Depends on the values returned by this query Outer query
returned to outer query Subqueries The unknown value is returned to outer query Subquery Outer query Opening parenthesis Can return a computed value Closing parenthesis Sales
Search value specified The IN Operator Search value specified before the IN operator Can be column name or constant value Search for list of values returned Used in search condition Customers Sales
Modified Comparison Operators Function of comparison operator changed by using ANY Value specified before operator Minimum value in this list compared Logical operator Always used with comparison operator Sales Slspers Output of the outer query
The EXISTS Operator Used in condition Values not specified Only checks for existence of records Asterisk instead of column name Condition tested Used in condition of outer query Titles Sales Qty > 200 EXISTS=TRUE
Correlated Subqueries Always a constant value Depends on input from outer query Located in the WHERE clause Outer query Correlated subquery Executed simultaneously for each record targeted for display
Correlated Subqueries (Cont.) Customers Slspers Sales Output of the outer query
Process of Correlating Queries
to all rows of an outer table The APPLY Operator The APPLY operator The WHERE condition Enables you to apply a table expression to all rows of an outer table
Nested Subqueries Inner query level 1 Nested subquery Output of the outer query Nested subquery Inner query level 1 Inner query level 2 Outer query depends on values returned by inner queries Number of closing parentheses matches number of inner queries Titles Customers Sales
Manipulating Table Data Insert Data Modify and Delete Data
into the target columns The INSERT Statement Target table Target columns Values to be inserted into the target columns
Values to be inserted in corresponding columns The OUTPUT Clause Values to be inserted in corresponding columns Used with the INSERT statement The OUTPUT keyword
Table Value Constructors Used with the INSERT INTO statement Values to be inserted in corresponding columns Graphic has to be inserted.
The UPDATE Statement The UPDATE keyword Columns to be updated New values Condition The SET keyword
The DELETE Statement The DELETE keyword Condition
The TRUNCATE TABLE Statement The TRUNCATE keyword Targeted table
The MERGE Statement Used with the MERGE INTO statement The DELETE keyword The INSERT keyword The UPDATE keyword Graphic has to be inserted.
CAST Graphic has to be inserted.
CASE Graphic has to be inserted.
Manipulating the Table Structure Create a Table Create a Table with Constraints Add and Drop Table Columns Add and Drop Constraints Modify the Column Definition Back Up Tables Delete a Table
The CREATE TABLE Statement Table name Restricts storage of null value Size enclosed within parentheses Datatype and size specified Column names and definitions
Table Design Columns Rows Column header
Data Integrity All values are valid and can be used further qty<225 Column contains valid data Linked columns have matching values Each record is unique
Constraints Qty>0 Column-level constraint Defines rules to test column value Domain integrity implemented
Primary Keys Primary key Uniquely identifies each column Cannot store null or duplicate values
PRIMARY KEY Constraints Constraint name Prevents record duplication Creates primary key on this column Table-level constraint Column name chosen as primary key
UNIQUE Constraints Can accept null values Column-level Implements uniqueness in values stored Can accept null values
Foreign Keys Foreign key Can store Primary key of duplicate values Stores matching values Links records Primary key of referenced table Referenced table
FOREIGN KEY Constraints Defined when creating a table Referenced table name Column-level constraint Referenced column Cannot be modified once created without being deleted Foreign key name Creates the foreign key Table-level constraint
column-level constraint DEFAULT Constraints Specified when creating a table Specified only as a column-level constraint Specifies a default value for a column Value must correspond to the datatype of the column
value based on condition CHECK Constraints Validates column value based on condition Executed in the order specified Multiple expressions linked Column-level CHECK constraint Table-level Logical expression
The ALTER TABLE Statement Modifies table structure Adds a column Modifies column definitions Adds a constraint Drops a column Drops a constraint
Sparse Columns Table name Sparse attribute for the ‘deptno’ column Column definition Code to be inserted here .
The SELECT INTO Statement New table Creates a backup of a table’s structure and data
The DROP TABLE Statement Table to be dropped Table referencing this table must be dropped first Column definitions and constraints also dropped
Working with Views Create a View Manipulate Data in Views Create Aliases Modify and Drop Views
Views Source table Retrieves and displays records from Does not store records Retrieves and displays records from a large source table Virtual table
The CREATE VIEW Statement keyword Name of the view to be created Optional column names can be specified
Schema Binding Written after the CREATE VIEW statement The SCHEMABINDING keyword
The TOP Keyword Number of records The TOP keyword to be retrieved Condition
Aliases Table alias Column name Column alias The AS keyword Table name
The ALTER VIEW Statement Target view name Column names Table name
The DROP VIEW Statement Name of the view
Indexing Data Create Indices Drop Indices
Indices Can be created on Helps in speedy data retrieval Columns frequently used for search to be indexed Cannot delete the column without deleting the index Helps in speedy data retrieval Can be created on multiple columns Query uses pointer to identify and retrieve record Pointers assigned to each value of indexed column
Constraint vs. Index
The CREATE INDEX Statement Creates an index Name of the index Multiple columns can be indexed Columns targeted for indexing Name of the targeted table Creates a unique non-clustered index
The DROP INDEX Statement Deletes an index Targeted table Not created by a clustered primary key Index name
Managing Transactions Create Transactions Commit Transactions
Transactions Name of the transaction The BEGIN TRAN statement The SAVE TRAN Savepoint name Transaction Statements that belong to the transaction and executed as a single unit
The ROLLBACK TRAN Statement Cancels changes done by the transaction up until the save point
The COMMIT TRAN Statement Saves changes done in a transaction