SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
SQL Programming Overview
January 23, 2009
Goals/ObjectivesGoals/Objectives
Gain an understanding of:
◦ SQL Programming including database structures,
manipulation of database contents and retrieval of
contents
◦ How it relates to FeaturePlan
Be able to … speak confidently about SQL and provide
efficient solutions for the reporting needs of our customers.
2
AgendaAgenda
History of SQL
SQL Fundamentals
Data Definition
Data Modifications
SingleTable SELECT StatementsSingleTable SELECT Statements
Joins
Set Operators
Aggregate Functions
Subqueries
Views
Execution Plans
Resources
History of SQLHistory of SQL
During the 1970s, a group at IBM San Jose Research Laboratory
developed the System R relational database management system
Donald D. Chamberlin and Raymond F. Boyce of IBM
subsequently created the Structured English Query Language
(SEQUEL) to manipulate and manage data stored in System R.
The first non-commercial non-SQL RDBMS, Ingres, was
developed in 1974 at the U.C. Berkeley.
In the late 1970s, Relational Software, Inc. (now Oracle
Corporation) developed their own SQL-based RDBMS
In the summer of 1979, Relational Software, Inc. introduced the
first commercially available implementation of SQL, OracleV2
(Version2) forVAX computers. OracleV2 beat IBM's release of
the System/38 RDBMS to market by a few weeks.
History of SQL (cont’d)History of SQL (cont’d)
SQL was adopted as a standard by ANSI in 1986 and ISO in 1987. In the original
SQL standard,ANSI declared that the official pronunciation for SQL is "es
queue el“.
The SQL standard has gone through a number of revisions:
Year Name Comments
1986 SQL-86 First published by ANSI. Ratified by ISO in 1987.
1989 SQL-89 Minor revision, adopted as FIPS 127-1.1989 SQL-89 Minor revision, adopted as FIPS 127-1.
1992 SQL-92 Major revision (ISO 9075), Entry Level SQL-92 adopted as FIPS 127-2.
1999 SQL:1999 Added regular expression matching, recursive queries, triggers, support for
procedural and control-of-flow statements, non-scalar types, and some object-
oriented features.
2003 SQL:2003 Introduced XML-related features, window functions, standardized sequences, and
columns with auto-generated values (including identity-columns).
2006 SQL:2006 ISO/IEC 9075-14:2006 defines ways in which SQL can be used in conjunction with
XML. It defines ways of importing and storing XML data in an SQL database,
manipulating it within the database and publishing both XML and conventional
SQL-data in XML form.
2008 SQL:2008 Defines more flexible windowing functions
SQL FundamentalsSQL Fundamentals
SQL is the only way to build, manipulate and access a relational
database
Table
◦ Columns and Rows
RelationshipsRelationships
◦ Primary keys (unique column or combination of columns)
◦ Foreign keys (a column that references primary key of another
table)
Normalization
◦ Each table describes one thing only
SQL Server BasicsSQL Server Basics
Keywords are not case sensitive
Table and column names are stored as they are entered and SQL
Server can be either case sensitive or insensitive
Elements are comma separated
Comments are enclosed between /* and */ or preceded by –
Generally SQL statements are terminated by semi-colon (SQL
Server does not require it)
Data DefinitionData Definition
Data Types
◦ Each database column has to have a valid data type
◦ Data types are only partially standardized
SQL Server: TINYINT, INT, Numeric, Decimal, Float, Real, Char,Varchar,
Text, Datetime, Binary, Image
Create TablesCreate Tables
◦ Defines the structure of the table
CREATETABLE Divisions
(DivisionID Numeric(5) NOT NULL
, DivisionNameVarchar(40) NOT NULL);
Alter Tables
◦ Modifies the structure of the table
ALTERTABLE Divisions
ADD DivisionCityVarchar(40) NOT NULL;
or ALTER COLUMN DivisionNameVarchar(80) NOT NULL;
or DROP COLUMN DivisionCityVarchar(40) NOT NULL;
Data Definition (cont’d)Data Definition (cont’d)
DROPTables
◦ DROPTABLE Divisions;
Constraints are used to enforce valid data in columns
◦ NOT NULL (the column will not allow null values)
◦ CHECK (value is checked against constants or other columns)
◦ PRIMARY KEY (enforces uniqueness of primary key)◦ PRIMARY KEY (enforces uniqueness of primary key)
◦ UNIQUE (enforces uniqueness of alternate keys)
◦ FOREIGN KEY (specifies a relationship between tables)
Indexes (like a virtual table with pointers to physical table)
◦ In general, rows are unsorted
◦ Indexes are sorted on the indexed value
◦ Indexes are created on a single column or combination of columns
NOTE: Null means unknown or missing value, not blank or zero
Data ModificationData Modification
INSERT
◦ Adds new rows to a table
INSERT INTO Departments
(DivisionID, DepartmentID, DepartmentName)
VALUES (1, 100,‘Accounting’);
UPDATEUPDATE
◦ Modifies the column values in existing rows
UPDATE Employee
SET CurrentSalary = CurrentSalary + 100
WHERE Employee = 4;
DELETE
◦ Removes rows from a table
DELETE FROM Employees
WHERE Employee = 7;
Data Modification (cont’d)Data Modification (cont’d)
TRANSACTIONS
◦ A set of INSERT/UPDATE/DELETE operations that belong
together as a logical unit of work
◦ COMMIT (ends the transaction with success and makes updates
permanent)
◦ ROLLBACK (ends the transaction with failure and undoes the
updates)updates)
INSERT INTO ConferenceRooms(RoomID,Name,Capacity)
VALUES(101,'Auditorium',250);
INSERT INTO ConferenceRooms(RoomID,Name,Capacity)
VALUES(300,'3rd Floor Small room',10);
INSERT INTO ConferenceRooms(RoomID,Name,Capacity)
VALUES(310,'3rd Floor Tiny room',6);
INSERT INTO ConferenceRooms(RoomID,Name,Capacity)
VALUES(400,'Attic Closet',3);
COMMIT;
Single Table SELECT StatementsSingle Table SELECT Statements
The SELECT statement retrieves data from database tables
SELECT select_list (describes the columns of the result set.)
[ INTO new_table_name ] (specifies that the result set is used to create a new table)
FROM table_list (Contains a list of the tables from which the result set data is retrieved)FROM table_list (Contains a list of the tables from which the result set data is retrieved)
[WHERE search_conditions ] (filter that defines the conditions each row in the source
tables must meet)
[ GROUP BY group_by_list ] (partitions the result set into groups based on the values)
[ HAVING search_conditions ] (an additional filter that is applied to the result set)
[ ORDER BY order_list [ ASC | DESC ] ] (defines the order in which the rows in the
result set are sorted)
Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d)
TheWHERE clause specifies a filter condition
SELECT EmployeeID, FirstName, LastName
,CurrentSalary*12 ASYearlySalary
FROM Employees
WHERE EmployeeID = 3;
SELECT EmployeeID, LastName
FROM Employees
Conditional Operators
◦ = <> > < >= <=
◦ IN , NOT IN (test for several values)
◦ BETWEEN, NOT BETWEEN (intervals)
◦ IS NULL, IS NOT NULL
◦ LIKE, NOT LIKE ( % or _ )
◦ EXISTS, NOT EXISTS (sub queries)
Conditions can be combined with NOT AND OR
FROM Employees
WHERE LastName LIKE 'D%'
AND FirstName LIKE '_a%‘;
Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d)
The ORDER BY statement defines the sort order of the rows
SELECT LastName
,FirstName
,CurrentSalary,CurrentSalary
FROM Employees
ORDER BY CurrentSalary DESC
,LastName ASC
,FirstName ASC;
Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d)
NULL means unknown or missing value
◦ NULL is not the same as blank
◦ NULL is not the same as zero
◦ NULL is not the same as the text ‘NULL’
◦ NULL is not equal to any value◦ NULL is not equal to any value
◦ NULL is not different to any value
◦ NULL is not equal to NULL
◦ In SQL Server, NULL sorts as the lowest value
DISTINCT can be used to suppress duplicates
Joins (INNER)Joins (INNER)
Joins are used to combine information from multiple tables
Basic Syntax of an INNER Join (excludes data that does NOT
satisfy the join)
Joins (INNER)Joins (INNER)
SELECT column_name(s)
FROM table_name1 JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SELECT column_name(s)SELECT column_name(s)
FROM table_name1 INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Inner joins are default, so the word Inner can be omitted
Joins (OUTER)Joins (OUTER)
Joins are used to combine information from multiple tables
Basic Syntax of an OUTER Join (include rows from one table that have
no matching row)
LEFT OUTER JOIN
Joins (CROSS)Joins (CROSS)
Each row in one table is paired to every row in the other table
A cross join is also called a cartesian product
SELECT *
FROM employee CROSS JOIN departmentFROM employee CROSS JOIN department
A
B
1
2
3
A 1
A 2
A 3
B 1
B 2
B 3
Joins (OUTER)Joins (OUTER)
table1 LEFT OUTER JOIN table2 – all rows from table 1 will be included
table1 RIGHT OUTER JOIN table2 – all rows from table 2 will be included
table1 FULL OUTER JOIN table2 – all rows from each table will be includedtable1 FULL OUTER JOIN table2 – all rows from each table will be included
SELECT column_name(s)
FROM table_name1
LEFT OUTER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Set OperatorsSet Operators
UNION, INTERSECT and EXCEPT
UNIONUNION
SELECT zip FROM hotel.customerWHERE zip > '90000'
UNION
SELECT zip FROM hotel.hotelWHERE zip > '90000‘
Creates one table with rows from both SELECTs
Suppresses duplicate rows
Set OperatorsSet Operators
UNION, INTERSECT and EXCEPT
INTERSECT
SELECT zip FROM hotel.customerWHERE zip < '30000'SELECT zip FROM hotel.customerWHERE zip < '30000'
INTERSECT
SELECT zip FROM hotel.hotelWHERE zip < '30000'
Returns the rows that occur in both queries
EXCEPT
SELECT zip FROM hotel.hotelWHERE zip < '30000'
EXCEPT
SELECT zip FROM hotel.customerWHERE zip < '30000‘
Returns the rows from one query except those that occur in the other
-basically a minus
Row FunctionsRow Functions
Row functions take input parameters and return a value
◦ Math Functions
◦ String Functions
◦ Date and Time Functions
◦ Data Type Conversions◦ Data Type Conversions
◦ CASE Statements
◦ NULL Functions
Row FunctionsRow Functions -- MathMath
ABS
DEGREES
RAND
ACOS
EXP
ROUND
ASIN
LOG
SIN
ATN2
LOG10
SQRT
CEILINGASIN
FLOOR
SIGN
ATAN
SELECT ROUND(123.9994,
3)
Here is the result set.
123.9990
CEILING
PI
SQUARE
COS
POWER
TAN
COT
RADIANS
Row FunctionsRow Functions -- StringString
ASCII
NCHAR
SOUNDEX
CHAR
PATINDEX
SPACE
CHARINDEX
DIFFERENCE
REPLACE
STUFF
LEFT
REPLICATE
SUBSTRINGCHARINDEX
QUOTENAME
STR
SELECT LEFT('abcdefg',2)
Here is the result set.
ab
SUBSTRING
LEN
REVERSE
UNICODE
LOWER
RIGHT
UPPER
LTRIM
RTRIM
Row FunctionsRow Functions –– Date & TimeDate & Time
DATEADD
DATEDIFF
DATENAME
DATEPART
DAY
GETDATEGETDATE
GETUTCDATE
MONTH
YEAR
SELECT GETDATE()
Here is the result set:
July 29 1998 2:50 PM
bigint
numeric
bit
smallint
decimal
smallmoney
Row FunctionsRow Functions –– Data TypeData Type
datetime2
smalldatetime
datetime
time
Character
Strings
Image
cursor
timestamp
hierarchyid
uniqueidentifier
sql_variantsmallmoney
int
tinyint
Money
float
real
Date and Time
date
datetimeoffset
Strings
char
varchar
Text
nchar
nvarchar
Ntext
binary
varbinary
sql_variant
xml
Table
SELECT
CAST(myval AS
decimal(10,5))
Row FunctionsRow Functions -- CaseCase
The CASE expression enables many forms of conditional processing to be
placed into a SQL statement.
SELECT title, price,
Budget = CASE priceBudget = CASE price
WHEN price > 20.00THEN 'Expensive‘
WHEN price BETWEEN 10.00 AND 19.99THEN 'Moderate'
WHEN price < 10.00THEN 'Inexpensive'
ELSE 'Unknown'
END,
FROM titles
Row FunctionsRow Functions -- NullNull
A null value in an expression causes the result of the expression to be
null
Testing for NULL in aWHERE clause
SELECT Name,Weight
FROM Production.Product
WHEREWeight IS NULL;
Aggregate FunctionsAggregate Functions
SUM AVG MAX MIN COUNT
SELECT AVG(UnitPrice * Quantity) As AveragePrice
FROMWidgetOrders
WHERE Continent = “North America”
SELECT COUNT(*) AS 'Number of Large Orders'
FROMWidgetOrders
WHERE Quantity > 100
SELECT MAX(Quantity * UnitPrice)As 'Largest Order'
FROMWidgetOrders
Aggregate FunctionsAggregate Functions –– GROUP BYGROUP BY
The GROUP BY statement is used in conjunction with the aggregate
functions to group the result-set by one or more columns.
SELECT Customer,SUM(OrderPrice)SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
Aggregate FunctionsAggregate Functions –– HAVINGHAVING
The HAVING clause was added to SQL because theWHERE keyword
could not be used with aggregate functions.
SELECT Customer,SUM(OrderPrice)
FROM OrdersFROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
Customer SUM(OrderPrice)
Nilsen 1700
SubqueriesSubqueries
A SELECT statement embedded into another statement is called a
subquery
SELECT SUM(Sales) FROM Store_Information
WHERE Store_name INWHERE Store_name IN
(SELECT store_name FROM Geography
WHERE region_name = 'West')
IN or NOT IN will handle extra lists returned by the sub query
Operators (>, <, =, etc.) can be used when single values are returned
CorrelatedCorrelated SubqueriesSubqueries
If a subquery may reference columns from the main query table, this is
called a correlated
SELECT DISTINCT c.LastName, c.FirstName
FROM Person.Contact cFROM Person.Contact c
JOIN HumanResources.Employee e ON e.ContactID =
c.ContactID
WHERE 5000.00 IN
(SELECT Bonus FROM Sales.SalesPerson sp
WHERE e.EmployeeID = sp.SalesPersonID) ;
ViewsViews -- InlineInline
A view is a virtual table based on the result-set of an SQL statement
An inline view is a table within the
SELECT height
FROM (SELECT height FROM test WHERE id = :b1FROM (SELECT height FROM test WHERE id = :b1
ORDER BY id DESC, acc_date DESC, height DESC)
WHERE ROWNUM = 1;
ViewsViews -- StoredStored
A view is a virtual table based on the result-set of an SQL statement
CREATEVIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
A view does not store data
If you do insert, update, delete on a view the data values in the
underlying tables will be updated
◦ This is not possible on all views
◦ Computed columns cannot be updated
◦ Not permitted on aggregate views or views with set operators
◦ Join views may or may not be updateable
ResourcesResources
BOOKS:
SQL in a Nutshell (English)
(A Desktop Quick Reference - ISBN: 9781565927445)
Publisher: Oreilly & Associates Inc
WEBSITES:
W3Schools SQLTutorial
http://www.w3schools.com/sql/default.asp

Contenu connexe

Tendances

Relational database management system
Relational database management systemRelational database management system
Relational database management systemPraveen Soni
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands1keydata
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1Swapnali Pawar
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsAshwin Dinoriya
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
Sql basics and DDL statements
Sql basics and DDL statementsSql basics and DDL statements
Sql basics and DDL statementsMohd Tousif
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDev Chauhan
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLPrashant Kumar
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 

Tendances (20)

SQL
SQLSQL
SQL
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Relational database management system
Relational database management systemRelational database management system
Relational database management system
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Database Overview
Database OverviewDatabase Overview
Database Overview
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Sql basics
Sql  basicsSql  basics
Sql basics
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Sql basics and DDL statements
Sql basics and DDL statementsSql basics and DDL statements
Sql basics and DDL statements
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL DDL
SQL DDLSQL DDL
SQL DDL
 
MySQL Essential Training
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 

Similaire à Sql overview-1232931296681161-1

SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfDraguClaudiu
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...SakkaravarthiS1
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptxSheethal Aji Mani
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL FundamentalsBrian Foote
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
 

Similaire à Sql overview-1232931296681161-1 (20)

SQL Query
SQL QuerySQL Query
SQL Query
 
SQL | DML
SQL | DMLSQL | DML
SQL | DML
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Hira
HiraHira
Hira
 
Introduction to SQL..pdf
Introduction to SQL..pdfIntroduction to SQL..pdf
Introduction to SQL..pdf
 
lovely
lovelylovely
lovely
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
Adbms
AdbmsAdbms
Adbms
 
Sql slid
Sql slidSql slid
Sql slid
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
Module 3
Module 3Module 3
Module 3
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Lab
LabLab
Lab
 

Plus de sagaroceanic11

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reportssagaroceanic11
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensicssagaroceanic11
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimessagaroceanic11
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attackssagaroceanic11
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attackssagaroceanic11
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidencesagaroceanic11
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computerssagaroceanic11
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays worldsagaroceanic11
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mwaresagaroceanic11
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overviewsagaroceanic11
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisationsagaroceanic11
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecyclesagaroceanic11
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3sagaroceanic11
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overviewsagaroceanic11
 

Plus de sagaroceanic11 (20)

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reports
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensics
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimes
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attacks
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attacks
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidence
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computers
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays world
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mware
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overview
 
Virtualisation basics
Virtualisation basicsVirtualisation basics
Virtualisation basics
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisation
 
6 service operation
6 service operation6 service operation
6 service operation
 
5 service transition
5 service transition5 service transition
5 service transition
 
4 service design
4 service design4 service design
4 service design
 
3 service strategy
3 service strategy3 service strategy
3 service strategy
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecycle
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
 
Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
 

Dernier

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Dernier (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Sql overview-1232931296681161-1

  • 2. Goals/ObjectivesGoals/Objectives Gain an understanding of: ◦ SQL Programming including database structures, manipulation of database contents and retrieval of contents ◦ How it relates to FeaturePlan Be able to … speak confidently about SQL and provide efficient solutions for the reporting needs of our customers. 2
  • 3. AgendaAgenda History of SQL SQL Fundamentals Data Definition Data Modifications SingleTable SELECT StatementsSingleTable SELECT Statements Joins Set Operators Aggregate Functions Subqueries Views Execution Plans Resources
  • 4. History of SQLHistory of SQL During the 1970s, a group at IBM San Jose Research Laboratory developed the System R relational database management system Donald D. Chamberlin and Raymond F. Boyce of IBM subsequently created the Structured English Query Language (SEQUEL) to manipulate and manage data stored in System R. The first non-commercial non-SQL RDBMS, Ingres, was developed in 1974 at the U.C. Berkeley. In the late 1970s, Relational Software, Inc. (now Oracle Corporation) developed their own SQL-based RDBMS In the summer of 1979, Relational Software, Inc. introduced the first commercially available implementation of SQL, OracleV2 (Version2) forVAX computers. OracleV2 beat IBM's release of the System/38 RDBMS to market by a few weeks.
  • 5. History of SQL (cont’d)History of SQL (cont’d) SQL was adopted as a standard by ANSI in 1986 and ISO in 1987. In the original SQL standard,ANSI declared that the official pronunciation for SQL is "es queue el“. The SQL standard has gone through a number of revisions: Year Name Comments 1986 SQL-86 First published by ANSI. Ratified by ISO in 1987. 1989 SQL-89 Minor revision, adopted as FIPS 127-1.1989 SQL-89 Minor revision, adopted as FIPS 127-1. 1992 SQL-92 Major revision (ISO 9075), Entry Level SQL-92 adopted as FIPS 127-2. 1999 SQL:1999 Added regular expression matching, recursive queries, triggers, support for procedural and control-of-flow statements, non-scalar types, and some object- oriented features. 2003 SQL:2003 Introduced XML-related features, window functions, standardized sequences, and columns with auto-generated values (including identity-columns). 2006 SQL:2006 ISO/IEC 9075-14:2006 defines ways in which SQL can be used in conjunction with XML. It defines ways of importing and storing XML data in an SQL database, manipulating it within the database and publishing both XML and conventional SQL-data in XML form. 2008 SQL:2008 Defines more flexible windowing functions
  • 6. SQL FundamentalsSQL Fundamentals SQL is the only way to build, manipulate and access a relational database Table ◦ Columns and Rows RelationshipsRelationships ◦ Primary keys (unique column or combination of columns) ◦ Foreign keys (a column that references primary key of another table) Normalization ◦ Each table describes one thing only
  • 7. SQL Server BasicsSQL Server Basics Keywords are not case sensitive Table and column names are stored as they are entered and SQL Server can be either case sensitive or insensitive Elements are comma separated Comments are enclosed between /* and */ or preceded by – Generally SQL statements are terminated by semi-colon (SQL Server does not require it)
  • 8. Data DefinitionData Definition Data Types ◦ Each database column has to have a valid data type ◦ Data types are only partially standardized SQL Server: TINYINT, INT, Numeric, Decimal, Float, Real, Char,Varchar, Text, Datetime, Binary, Image Create TablesCreate Tables ◦ Defines the structure of the table CREATETABLE Divisions (DivisionID Numeric(5) NOT NULL , DivisionNameVarchar(40) NOT NULL); Alter Tables ◦ Modifies the structure of the table ALTERTABLE Divisions ADD DivisionCityVarchar(40) NOT NULL; or ALTER COLUMN DivisionNameVarchar(80) NOT NULL; or DROP COLUMN DivisionCityVarchar(40) NOT NULL;
  • 9. Data Definition (cont’d)Data Definition (cont’d) DROPTables ◦ DROPTABLE Divisions; Constraints are used to enforce valid data in columns ◦ NOT NULL (the column will not allow null values) ◦ CHECK (value is checked against constants or other columns) ◦ PRIMARY KEY (enforces uniqueness of primary key)◦ PRIMARY KEY (enforces uniqueness of primary key) ◦ UNIQUE (enforces uniqueness of alternate keys) ◦ FOREIGN KEY (specifies a relationship between tables) Indexes (like a virtual table with pointers to physical table) ◦ In general, rows are unsorted ◦ Indexes are sorted on the indexed value ◦ Indexes are created on a single column or combination of columns NOTE: Null means unknown or missing value, not blank or zero
  • 10. Data ModificationData Modification INSERT ◦ Adds new rows to a table INSERT INTO Departments (DivisionID, DepartmentID, DepartmentName) VALUES (1, 100,‘Accounting’); UPDATEUPDATE ◦ Modifies the column values in existing rows UPDATE Employee SET CurrentSalary = CurrentSalary + 100 WHERE Employee = 4; DELETE ◦ Removes rows from a table DELETE FROM Employees WHERE Employee = 7;
  • 11. Data Modification (cont’d)Data Modification (cont’d) TRANSACTIONS ◦ A set of INSERT/UPDATE/DELETE operations that belong together as a logical unit of work ◦ COMMIT (ends the transaction with success and makes updates permanent) ◦ ROLLBACK (ends the transaction with failure and undoes the updates)updates) INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(101,'Auditorium',250); INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(300,'3rd Floor Small room',10); INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(310,'3rd Floor Tiny room',6); INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(400,'Attic Closet',3); COMMIT;
  • 12. Single Table SELECT StatementsSingle Table SELECT Statements The SELECT statement retrieves data from database tables SELECT select_list (describes the columns of the result set.) [ INTO new_table_name ] (specifies that the result set is used to create a new table) FROM table_list (Contains a list of the tables from which the result set data is retrieved)FROM table_list (Contains a list of the tables from which the result set data is retrieved) [WHERE search_conditions ] (filter that defines the conditions each row in the source tables must meet) [ GROUP BY group_by_list ] (partitions the result set into groups based on the values) [ HAVING search_conditions ] (an additional filter that is applied to the result set) [ ORDER BY order_list [ ASC | DESC ] ] (defines the order in which the rows in the result set are sorted)
  • 13. Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d) TheWHERE clause specifies a filter condition SELECT EmployeeID, FirstName, LastName ,CurrentSalary*12 ASYearlySalary FROM Employees WHERE EmployeeID = 3; SELECT EmployeeID, LastName FROM Employees Conditional Operators ◦ = <> > < >= <= ◦ IN , NOT IN (test for several values) ◦ BETWEEN, NOT BETWEEN (intervals) ◦ IS NULL, IS NOT NULL ◦ LIKE, NOT LIKE ( % or _ ) ◦ EXISTS, NOT EXISTS (sub queries) Conditions can be combined with NOT AND OR FROM Employees WHERE LastName LIKE 'D%' AND FirstName LIKE '_a%‘;
  • 14. Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d) The ORDER BY statement defines the sort order of the rows SELECT LastName ,FirstName ,CurrentSalary,CurrentSalary FROM Employees ORDER BY CurrentSalary DESC ,LastName ASC ,FirstName ASC;
  • 15. Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d) NULL means unknown or missing value ◦ NULL is not the same as blank ◦ NULL is not the same as zero ◦ NULL is not the same as the text ‘NULL’ ◦ NULL is not equal to any value◦ NULL is not equal to any value ◦ NULL is not different to any value ◦ NULL is not equal to NULL ◦ In SQL Server, NULL sorts as the lowest value DISTINCT can be used to suppress duplicates
  • 16. Joins (INNER)Joins (INNER) Joins are used to combine information from multiple tables Basic Syntax of an INNER Join (excludes data that does NOT satisfy the join)
  • 17. Joins (INNER)Joins (INNER) SELECT column_name(s) FROM table_name1 JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s)SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name Inner joins are default, so the word Inner can be omitted
  • 18. Joins (OUTER)Joins (OUTER) Joins are used to combine information from multiple tables Basic Syntax of an OUTER Join (include rows from one table that have no matching row) LEFT OUTER JOIN
  • 19. Joins (CROSS)Joins (CROSS) Each row in one table is paired to every row in the other table A cross join is also called a cartesian product SELECT * FROM employee CROSS JOIN departmentFROM employee CROSS JOIN department A B 1 2 3 A 1 A 2 A 3 B 1 B 2 B 3
  • 20. Joins (OUTER)Joins (OUTER) table1 LEFT OUTER JOIN table2 – all rows from table 1 will be included table1 RIGHT OUTER JOIN table2 – all rows from table 2 will be included table1 FULL OUTER JOIN table2 – all rows from each table will be includedtable1 FULL OUTER JOIN table2 – all rows from each table will be included SELECT column_name(s) FROM table_name1 LEFT OUTER JOIN table_name2 ON table_name1.column_name=table_name2.column_name
  • 21. Set OperatorsSet Operators UNION, INTERSECT and EXCEPT UNIONUNION SELECT zip FROM hotel.customerWHERE zip > '90000' UNION SELECT zip FROM hotel.hotelWHERE zip > '90000‘ Creates one table with rows from both SELECTs Suppresses duplicate rows
  • 22. Set OperatorsSet Operators UNION, INTERSECT and EXCEPT INTERSECT SELECT zip FROM hotel.customerWHERE zip < '30000'SELECT zip FROM hotel.customerWHERE zip < '30000' INTERSECT SELECT zip FROM hotel.hotelWHERE zip < '30000' Returns the rows that occur in both queries EXCEPT SELECT zip FROM hotel.hotelWHERE zip < '30000' EXCEPT SELECT zip FROM hotel.customerWHERE zip < '30000‘ Returns the rows from one query except those that occur in the other -basically a minus
  • 23. Row FunctionsRow Functions Row functions take input parameters and return a value ◦ Math Functions ◦ String Functions ◦ Date and Time Functions ◦ Data Type Conversions◦ Data Type Conversions ◦ CASE Statements ◦ NULL Functions
  • 24. Row FunctionsRow Functions -- MathMath ABS DEGREES RAND ACOS EXP ROUND ASIN LOG SIN ATN2 LOG10 SQRT CEILINGASIN FLOOR SIGN ATAN SELECT ROUND(123.9994, 3) Here is the result set. 123.9990 CEILING PI SQUARE COS POWER TAN COT RADIANS
  • 25. Row FunctionsRow Functions -- StringString ASCII NCHAR SOUNDEX CHAR PATINDEX SPACE CHARINDEX DIFFERENCE REPLACE STUFF LEFT REPLICATE SUBSTRINGCHARINDEX QUOTENAME STR SELECT LEFT('abcdefg',2) Here is the result set. ab SUBSTRING LEN REVERSE UNICODE LOWER RIGHT UPPER LTRIM RTRIM
  • 26. Row FunctionsRow Functions –– Date & TimeDate & Time DATEADD DATEDIFF DATENAME DATEPART DAY GETDATEGETDATE GETUTCDATE MONTH YEAR SELECT GETDATE() Here is the result set: July 29 1998 2:50 PM
  • 27. bigint numeric bit smallint decimal smallmoney Row FunctionsRow Functions –– Data TypeData Type datetime2 smalldatetime datetime time Character Strings Image cursor timestamp hierarchyid uniqueidentifier sql_variantsmallmoney int tinyint Money float real Date and Time date datetimeoffset Strings char varchar Text nchar nvarchar Ntext binary varbinary sql_variant xml Table SELECT CAST(myval AS decimal(10,5))
  • 28. Row FunctionsRow Functions -- CaseCase The CASE expression enables many forms of conditional processing to be placed into a SQL statement. SELECT title, price, Budget = CASE priceBudget = CASE price WHEN price > 20.00THEN 'Expensive‘ WHEN price BETWEEN 10.00 AND 19.99THEN 'Moderate' WHEN price < 10.00THEN 'Inexpensive' ELSE 'Unknown' END, FROM titles
  • 29. Row FunctionsRow Functions -- NullNull A null value in an expression causes the result of the expression to be null Testing for NULL in aWHERE clause SELECT Name,Weight FROM Production.Product WHEREWeight IS NULL;
  • 30. Aggregate FunctionsAggregate Functions SUM AVG MAX MIN COUNT SELECT AVG(UnitPrice * Quantity) As AveragePrice FROMWidgetOrders WHERE Continent = “North America” SELECT COUNT(*) AS 'Number of Large Orders' FROMWidgetOrders WHERE Quantity > 100 SELECT MAX(Quantity * UnitPrice)As 'Largest Order' FROMWidgetOrders
  • 31. Aggregate FunctionsAggregate Functions –– GROUP BYGROUP BY The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SELECT Customer,SUM(OrderPrice)SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer Customer SUM(OrderPrice) Hansen 2000 Nilsen 1700 Jensen 2000
  • 32. Aggregate FunctionsAggregate Functions –– HAVINGHAVING The HAVING clause was added to SQL because theWHERE keyword could not be used with aggregate functions. SELECT Customer,SUM(OrderPrice) FROM OrdersFROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000 Customer SUM(OrderPrice) Nilsen 1700
  • 33. SubqueriesSubqueries A SELECT statement embedded into another statement is called a subquery SELECT SUM(Sales) FROM Store_Information WHERE Store_name INWHERE Store_name IN (SELECT store_name FROM Geography WHERE region_name = 'West') IN or NOT IN will handle extra lists returned by the sub query Operators (>, <, =, etc.) can be used when single values are returned
  • 34. CorrelatedCorrelated SubqueriesSubqueries If a subquery may reference columns from the main query table, this is called a correlated SELECT DISTINCT c.LastName, c.FirstName FROM Person.Contact cFROM Person.Contact c JOIN HumanResources.Employee e ON e.ContactID = c.ContactID WHERE 5000.00 IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.EmployeeID = sp.SalesPersonID) ;
  • 35. ViewsViews -- InlineInline A view is a virtual table based on the result-set of an SQL statement An inline view is a table within the SELECT height FROM (SELECT height FROM test WHERE id = :b1FROM (SELECT height FROM test WHERE id = :b1 ORDER BY id DESC, acc_date DESC, height DESC) WHERE ROWNUM = 1;
  • 36. ViewsViews -- StoredStored A view is a virtual table based on the result-set of an SQL statement CREATEVIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No A view does not store data If you do insert, update, delete on a view the data values in the underlying tables will be updated ◦ This is not possible on all views ◦ Computed columns cannot be updated ◦ Not permitted on aggregate views or views with set operators ◦ Join views may or may not be updateable
  • 37. ResourcesResources BOOKS: SQL in a Nutshell (English) (A Desktop Quick Reference - ISBN: 9781565927445) Publisher: Oreilly & Associates Inc WEBSITES: W3Schools SQLTutorial http://www.w3schools.com/sql/default.asp