Professional Documents
Culture Documents
cc
Advanced Excel
| 2
Course Outline
1 Introduction to DATABASE
3 Relational Database
| 3
Course Outline
6 Performing Data Manipulation
9 SET Operators
| 4
1
Introduction to Database
Definition, Concepts, Types
| 5
What is a Database?
| 6
Database Management Systems
Types of DBMS
Flat file DBMS
Hierarchical DBMS
Relational DBMS
NoSQL DBMS
| 7
Relational DBMS
Data in relational databases is stored in different access control tables, each having a
key field that mainly identifies each row.
A Relational DBMS is a
database structured to
recognize relations
between stored items of
information
| 8
2
| 9
What is SQL?
| 10
Why SQL?
| 11
Variants of SQL
Although most database systems use SQL, most of them also have their own
additional proprietary extensions that are usually only used on their system.
T-SQL is a dialect of standard SQL adopted by Microsoft as its language for
managing and manipulating data in Microsoft main relational database
management system (RDBMS) SQL Server
All variants of SQL understand the basic commands such as "Select", "Insert",
"Update", "Delete", "Create", and "Drop.
| 12
SQL Vendors
| 13
3
Relational Database
Explanation, Model, Features, Examples
| 14
Relational Database Management Systems
RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
| 15
RDBMS Contd
| 16
Relational Model
When working with relational database, its important to think of the relationships
between pieces of information.
| 17
Relational Model
Do you understand
this DB Schema?
| 18
Relationship Keys
PRIMARY KEY:
Every Entity(table) must have a primary key
Primary key ensures uniqueness of each rows
Unique constraint does not allow for NULL values
FOREIGN KEY:
Constraint which enforces referential integrity
The foreign key references the table containing the primary key.
| 19
Relational Database Model Example
| 20
Another Model Example
| 21
Advantages of Relational Databases
| 22
SQL Server as a RDBMS
| 24
Attributes
Represents a property of an ENTITY
| 25
Rows
Represent an instance of an ENTITY. Also referred to as tuples
| 26
4
| 27
Data Types
There are 3 main SQL data types
Character
Numbers
Dates
| 28
Common SQL Data Types
NUMERIC-A fixed precision and scale numbers
INT: Whole number values between -32,768 and 32,767
VARCHAR and nVARCHAR : Variable length alphanumeric data. i.e. Can
contain letters, numbers and special characters. It can also store up to 255
characters.
CHAR and nCHAR :Fixed length alphanumeric data. i.e. Can contain letters,
numbers and special characters.
DATETIME :Stores date and time combination.
REAL: Stores a small number with a floating decimal point.
| 29
5
| 30
Create Statement
CREATE statement are used to create databases, and tables.
| 31
Create Table Statement
Tables are organized into rows and columns; and each table must have a name
Syntax:
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
....
);
The column name parameters specify the names of the columns of the table.
The data type parameter specifies what type of data the column can hold (e.g.
varchar, integer, decimal, date, etc.).
The size parameter specifies the maximum length of the column of the table.
| 32
SQL Constraints
SQL Constraints are used to specify rules for data in a table. Where there is any
deviation from the set constraint, any data action is aborted.
Constraint are usually specified when a table is being created (Within the CREATE
Statement), but can as well be specified after the table has been created (Using the
ALTER Statement).
| 33
Types of Constraints
NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row of a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column
(or combination of two or more columns) have a unique identity which helps to find
a particular record in a table more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match
values in another table
DEFAULT - Specifies a default value when specified none for this column
| 34
Constraints
PRIMARY KEY
Ensures that a column (or combination of two or more columns) have a unique identity
which helps to find a particular record in a table more easily and quickly
FOREIGN KEY
Ensure the referential integrity of the data in one table to match values in another table
Syntax
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
| 35
Select Statement
| 36
Select Statement Basic
The select statement is used to query the database and retrieve selected data that
match the criteria that you specify.
The table name that follows the keyword FROM specifies the table that will be
queried to retrieve the desired results.
| 37
Try This
Selecting all columns from a table
Using the AdventureWorks Database, retrieve all information from the
HumanResource.Employee table.
Tip: if you want to select all the fields (Columns) in the table, you can use
the syntax below
SELECT *
FROM tablename;
| 38
SQL Joins Clause
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them
It allow you to link data from two or more tables together into a single query
result--from one single SELECT statement.
A "Join" can be recognized in a SQL SELECT statement if it has more than one
table after the FROM keyword.
| 39
SQL Joins Structure
| 40
SQL-Inner Join
The INNER JOIN keyword selects records that have matching values in both
tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
The ON keyword forms the basis upon which the join is established. i.e. the
common key between both tables.
| 41
My Example
I would like to see all the customers who have orders and all the
orders that have corresponding customers. For each customer
show me the customer account number and for each order,
show me the order date
| 42
Your Exercise
| 43
SQL Left Outer Join
The LEFT JOIN keyword returns all records from the left table (table1), and
the matched records from the right table (table2).
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
| 44
My Example
| 45
SQL Right Outer Join
The Right JOIN keyword returns all records from the right table (table2), and
the matched records from the left table (table1).
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
| 46
SQL Full Outer Join
The full outer join returns all the rows from the left and right table, even if
there are no matches in both tables.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
| 47
Multi Table Join
| 48
Keyed in the Order of SELECT Statement
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
| 49
Logical Query Processing
However the database engine does not use the keyed in order to
process your query, it uses the logical query processing order (this is a
conceptual interpretation order), shown below;
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
| 50
WHERE Clause
This allows user to retrieve specific information from a rows by filtering
through the column
SELECT <Column_Name>
FROM <Table_Name>
WHERE<column_name, operator value>
| 51
WHERE Clause
The WHERE clause filter the rows returned by the FROM phrase.
I Would Like All Information On All Employees With Jobtitle Like Research
| 54
AND/OR Operator
Using AND / OR
AND operator displays record if both the first condition and the
second condition is true
| 55
ORDER BY
Order by clause imposes an order on the results of the query
Ascending is default
| 56
Try This
Extract employee Login ID, Job Title, Birth Date, Gender and
Marital Status of all employees that are single or Male arranged
by their job title
| 57
6
Date Manipulation
Date Extraction, Date Difference, Date Formatting
| 58
Date Manipulation
These functions are used for working with Datetime Datatype
Common Date functions Description
YEAR( ) These three functions return an integer date part of
MONTH( ) datetime type value. They allow users to create unique
date format
DAY( )
DATEPART( )/DATENAME( ) Returns an unit of a datetime value.
DATEPART returns an integer while
DATENAME returns a string character
DATEDIFF( ) Returns the difference in integer value between two
dates in the interval units provided
GETDATE( ) Function returns the current date and time as a date type
| 59
Try This
| 60
7
String Manipulation
Uppercase, Lowercase, Text Length, Concatenation
| 61
String Manipulation
String functions are used to manipulate and replace characters values
COMMON STRING FUNCTION
UPPER() Simply converts a character string to all lowercases or all uppercases characters.
LOWER()
LEN() Returns all the length of a string as an integer
LEFT() Both function return the substring specified size.
RIGHT () LEFT function returns character from the left-most part of the string , counting
the characters to the right.
The RIGHT () function starts at the right-most character and counts to the left
returning the specified number of characters
SUBSTRING () it starts at a position and counts to right , returning a substring of a specified
length. It allows you to extract a substring from anywhere within a character
string
CONCAT() Joins together two or more characters together.
| 62
Try This
Return first name and last name of employee, I would also like
to see the first 2 letters of First name in Lowercase and the last
2 Characters of the Last name in Uppercase.
| 63
8
Mathematical Calculation
Simple Operations, Functions, Nested Formula
| 64
Mathematical Functions
Arithmetic operators
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus: %
| 65
Try This
| 66
9
| 67
Aggregate Function
Aggregate function results a single value, calculated from values in a column.
Aggregate Function
| 68
GROUP BY Clause
Group by clause is used in conjunction with aggregate function to
group the result set by one or more columns.
Any other field in the select list that is not aggregated must be
included in the Group By clause
SELECT [Color],
AVG([ListPrice])
FROM [Production].[Product]
GROUP BY [Color]
| 69
Try This
Derive the total value of orders from the Sales Order Detail table
Derive the total number of products, maximum price for each colour and the
sum of list price from the product table
Calculate Total Profit, Average Profit, Max Profit, Min Profit and total
Number of product where List price is less than 10 for all White Products
| 70
HAVING Clause
In SQL, WHERE clause cannot be used to filter aggregate function
as its written before GROUP BY.
| 71
My Example
Please provide the average list price of products, grouped by colour
only where the average price is greater than $1200.
SELECT [Color],
AVG([ListPrice])
FROM [Production].[Product]
GROUP BY [Color]
HAVING AVG([ListPrice]) > 1200
| 72
Try This
Please provide the count of employees, grouped by Gender only
where the marital status is Married
| 73
10
CASE Expressions
Making conditional statements in a simple way
| 74
CASE Expression
This is a conditional statement which returns a value based on the
evaluation of a statement.
| 75
CASE Expression
Simple expression
A simple case expression only returns equivalent values, if theres is no
match, then the else clause is evaluated.
CASE
WHEN [Expression] THEN [result]
WHEN [Expression] THEN [result]
...
ELSE
END
| 76
Try This
Change the Gender from M to Male and F to Female, From the Human
Resource Employee Table
Get the names of our employees, and their ages at the point of hire.
Categorize them into five different age bands. Give me what age band has
the highest number of employees.
| 77
Try This
I would like to increase the List Price of product that are multi, silver,
silver /black, blue by 15% and for other colors by 5%.
Group the List price into 3 categories (i.e. Low, medium and High)
using the criteria of your choice.
| 78
11
Set Operators
Union, Union ALL, Intersection
| 79
UNION
The UNION operator allows user to draw information from two or
more table that have the same structure. This means
Using Sales order detail table : increase price by 15% for all
transaction where more than 3 item were purchased and for
transactions where less than 3 items were purchased give a
discount of 25%
| 82
Set Operation (Intersection)
| 83
Set Operation (Except)
| 84
RANK Function
| 85
12
Subqueries
Segmenting SQL queries
| 86
Subqueries
| 87
How to use subqueries
As an ATTRIBUTE in the select list: We want to see the avg list price
of products and at the same time the list price that are <= avg list price
from the Production.Product Table
| 88
How to use subqueries
As an ATTRIBUTE in the select list: We want to see the avg list price
of products and at the same time the list price that are <= avg list price
from the Production.Product Table
| 89
Subquery with Exist Predicate
| 90
13
Stored Procedure
Gaining time with stored queries
| 91
Stored Procedure
| 92
Advantages of Stored Procedure
Executes faster as the code is already complied and resides in
memory
Reduces Network Traffic as you execute a PROC command
statement rather than batch of SQL queries across the network
Enforces Consistency
Provides Security. Users can be given permission to execute a stored
procedure that modifies data rather than permission directly
modifying the table
| 93
Creating Procedure Statement
To create a stored procedure, you use a Create PROCEDURE command
CREATE PROCEDURE ProcedureName
AS
BEGIN
SQL STATEMENTS
END;
| 94
14
Creating Views
Generating a virtual table for queried dataset
| 95
SQL Views
You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.
Key Point: The database engine recreates the data, using the view's SQL
statement, every time a user queries a view, hence A view always shows
up-to-date data from the database
| 96
Types of SQL Views
| 97
Create and Alter SQL View
Example:
Please create a view on the Production.product table that gives us
a list of products that takes one day to manufacture
| 98
Purpose of SQL Views
| 99
15
Syntax Summary
Refresh your memory
| 100
Remember your Syntax
SELECT *
FROM table_name;
| 101
Remember your Syntax
SELECT column1, column2....columnN
FROM table_name BETWEEN Clause
WHERE column_name BETWEEN val-1 AND val-2;
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name GROUP BY Clause
WHERE CONDITION
GROUP BY column_name;
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE CONDITION HAVING Clause
GROUP BY column_name
HAVING (arithematic function condition);
| 103
Remember your Syntax
| 104
Remember your Syntax
| 105