SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
Introduction toSQL
Ref: https://www.w3schools.com/sql/default.asp
What isSQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL is anANSI (American National Standards Institute) standard
WhatCanSQL
do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views
SQL is a
Standard -
BUT....
 There are different versions of the SQL language
 They all support at least the major commands
 Note: Most of the SQL database programs also have their own
proprietary extensions in addition to the SQL standard!
What is
RDBMS?
 RDBMS stands for Relational Database Management System.
 RDBMS is the basis for SQL, and for all modern database systems
such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.
 The data in RDBMS is stored in database objects called tables. A
table is a collection of related data entries and it consists of
columns and rows.
 Look at the "Customers" table:
SELECT * FROM Customers;
SQLSyntax
 DatabaseTables
Columns or Fields, Rows or Records, Indexes, etc…
 SQL Statements
SELECT * FROM Customers;
It’s not Case Sensitive
 SQL Expressions
Column Names, Formula, Sub-Query, etc…
 Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement
 Some ofThe Most Important SQLCommands
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
SQLSELECT
Statement
The SELECT statement is used to select data from a database
SELECT
Syntax
SELECT column1, column2, ...
FROM table_name;
SELECT *
FROM table_name;
SELECT CustomerKey, FirstName, LastName
FROM DimCustomer;
MoreSELECT
Stuff
 TOP N
 ORDER BY
 ORDER BY DESC
 DISTINCT
 Alias Names
 Concatenation
SELECT
WHERE
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SELECT *
FROM DimCustomer
WHERE Gender = ‘F’;
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
MoreWHERE
Stuff
 Dealing with NULL values
 AND, OR, NOT
 LIKE
 %
 _
 IN
SELECT
WHERE
Quiz
 Female Customers
 Female Customers younger than 40
 Female Customers younger than 40 and married
 MaleCustomers with middle name
 MaleCustomers who their names start with ‘Jon’
 Customers with income between 30000-50000
 Single female customers between 25-40 years old how make more
than $100K a year
Aggregation
 MIN
 MAX
 AVG
 COUNT
 SUM
 COUNT(DISTINCT)
GROUP BY  After WHERE Clause
 Before Order By Clause
 HAVING Clause
 Aggregations in GROUP BY
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;
GROUP BY
Quiz
 Customers by Gender
 Customers by Marital Status
 Customers by Age
 Customer Count by Gender
 Customer Count by Gender and Marital Status
 Average Income by Gender
 Female Customers count in 25-40 years old by Age
 …
SQLJOINs
 When do we join?
 Different types of JOINs
 CROSS JOIN
 How to choose which type is appropriate?
 Deal with NULL values
INNER JOIN
SELECT DimCustomer.CustomerKey, DimCustomer.FirstName,
DimCustomer.LastName,
DimGeography.EnglishCountryRegionName, DimGeography.City
FROM DimCustomer INNER JOIN
DimGeography ON DimCustomer.GeographyKey =
DimGeography.GeographyKey
SELECT DimGeography.EnglishCountryRegionName,
DimGeography.City, Customer.CustomerKey,
Customer.FirstName, Customer.LastName,
Sales.SalesOrderNumber, Sales.SalesAmount
FROM FactInternetSales Sales INNER JOIN
DimCustomer Customer ON Customer.CustomerKey =
Sales.CustomerKey INNER JOIN
DimGeography ON Customer.GeographyKey =
DimGeography.GeographyKey
LEFT/RIGHT
JOIN
SELECT P.EnglishProductName, PSC.EnglishProductSubcategoryName
FROM DimProductSubcategory PSC LEFT OUTER JOIN
DimProduct P ON P.ProductSubcategoryKey = PSC.ProductSubcategoryKey
SELECT P.EnglishProductName, PSC.EnglishProductSubcategoryName
FROM DimProductSubcategory PSC RIGHT OUTER JOIN
DimProduct P ON P.ProductSubcategoryKey = PSC.ProductSubcategoryKey
FULLJOIN
SELECT *
FROM DimProductCategory PC FULL OUTER JOIN
DimProductMarginTarget PCT ON PC.ProductCategoryKey =
PCT.ProductCategoryKey
SQLJOINs
Quiz
 Join DimProduct, DimProductSubcategory, DimProductCategory and
select Keys and Names from each table
 Join FactInternetSales, DimCustomer, DimProduct and show which
Product is Sold toWhich Customer with all the measures
 ProductCount by Category
 SalesAmount By Country
 OrderQuantity by Product Color
 SalesAmount and OrderQuantity byYear, Country, ProductCategory
 How many Bikes have we sold to each Country in 1386
 SalesAmount by Customer Gender
 SalesAmount by Customer Gender, MaritalStatus in the US
 Which one bought more Accessories, Men orWomen?
Sub-Queries
 Select Statements within Select Statement
 Used in:
 SELECT Clause
 FROM Clause
 JOINs
 WHERE Clause
Sub-Queries in
SELECT
 One row, One column
 Relates to the main query by usingWHERE
 Needs an Alias Name
 Could use internal joins as many times as needed
SELECT P.ProductKey, P.EnglishProductName, (
SELECT SUM(S.OrderQuantity) FROM FactInternetSales S WHERE
S.ProductKey = P.ProductKey
) AS SalesQuantity
FROM DimProduct P
Sub-Queries in
FROM
 Multiple rows, Multiple columns
 Treated just like aTable
 Needs an Alias Name
 Could use internal joins as many times as needed
SELECT MonthlySales.Year, Sum(TotalSales) ASTotalSalesSummary,
Min(TotalSales) ASTotalSalesMinimum, Max(TotalSales) AS
TotalSalesMaximum, Avg(TotalSales) ASTotalSalesAvg
FROM (
SELECT D.Year, D.MonthKey, Sum(OrderQuantity) ASTotalSales
FROM FactInternetSales S INNER JOIN
DimDatePersian D ON S.OrderDateKey = D.DateKey
Group By D.Year, D.MonthKey
) MonthlySales
Group By MonthlySales.Year
Sub-Queries in
JOINs
 Same as FROM Sub-Queries
 Relate to each other with JOIN
SELECT PRODUCTS.ProductCategoryKey,
PRODUCTS.EnglishProductCategoryName, SUM(OrderQuantity) AS
TotalSales
FROM FactInternetSales S INNER JOIN
(
SELECT PC.ProductCategoryKey, PC.EnglishProductCategoryName,
P.ProductKey
FROM DimProduct P INNER JOIN
DimProductSubCategory PSC ON P.ProductSubcategoryKey =
PSC.ProductSubcategoryKey INNER JOIN
DimProductCategory PC ON PC.ProductCategoryKey =
PSC.ProductCategoryKey
) PRODUCTS ON PRODUCTS.ProductKey = S.ProductKey
GROUP BY PRODUCTS.ProductCategoryKey,
PRODUCTS.EnglishProductCategoryName
Sub-Queries in
FROM
 Multiple rows, One column
 Usually used for IN or NOT IN conditions
 Doesn’t need an Alias Name
 Could use internal joins as many times as needed
SELECT *
FROM FactInternetSales
WHERE ProductKey IN (
SELECT P.ProductKey
FROM DimProduct P INNER JOIN
DimProductSubCategory PSC ON P.ProductSubcategoryKey =
PSC.ProductSubcategoryKey INNER JOIN
DimProductCategory PC ON PC.ProductCategoryKey =
PSC.ProductCategoryKey
WHERE PC.ProductCategoryKey = 1
)
CROSSJOIN
 Cartesian product of theTables involved in the JOIN
 Result rows count =Table1.Rows xTable2.Rows x …
 Used for computing Measures from unrelated Dimensions
 If aWHERE clause is added, the cross join behaves as an inner join
SELECT CUSTOMERS.CustomerKey, PRODUCTS.ProductKey,
(
SELECT ISNULL(SUM(S.OrderQuantity), 0) FROM FactInternetSales S
WHERE S.ProductKey = PRODUCTS.ProductKey and S.CustomerKey =
CUSTOMERS.CustomerKey
)TotalSales
FROM (
SELECT TOP(10) CustomerKey FROM DimCustomer
) CUSTOMERS CROSS JOIN
(
SELECT TOP(10) ProductKey FROM DimProduct ORDER BY ListPrice DESC
) PRODUCTS
ORDER BYTotalSales DESC
Sub-Queries
Quiz
 Select Customers withTotal Purchased Amount
 Select only the Products which have been sold
 Find out OrderQuantity sold in each country from each product
color
 Show monthly SalesAmount distribution in each country
 CombineYears and Customer Gender, and find each combination
Sales
 Yearly Sales for Customers in the US (Use Sub-Query not JOIN)
About Me
Amin Choroomi
CTO & Co-Founder at vdash
Software Developer, Teacher and Consultant
DataVisualization, Analytics, Dashboards
Data Warehousing, Integration, Business Intelligence
http://www.vdash.ir
choroomi@live.com
choroomi@vdashonline.com
https://linkedin.com/in/choroomi
@aminchoroomi
ThankYou

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
Sql views
Sql viewsSql views
Sql views
 
SQL
SQLSQL
SQL
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick LearningOracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
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 tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql - Structured Query Language
Sql - Structured Query LanguageSql - Structured Query Language
Sql - Structured Query Language
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Sql commands
Sql commandsSql commands
Sql commands
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 
DDL And DML
DDL And DMLDDL And DML
DDL And DML
 

Ähnlich wie Introduction to SQL

Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic ConceptsTony Wong
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresSteven Johnson
 
Practical guide to SQL basics
Practical guide to SQL basicsPractical guide to SQL basics
Practical guide to SQL basicsPavani Ganti
 
Sql basics
Sql basicsSql basics
Sql basicsKumar
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for BeginnersProduct School
 
Sql Portfolio(March 31)
Sql Portfolio(March 31)Sql Portfolio(March 31)
Sql Portfolio(March 31)iceolated
 
Database optimization
Database optimizationDatabase optimization
Database optimizationEsraaAlattar1
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introductionSmriti Jain
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioChris Seebacher
 
James Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science PortfolioJames Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science Portfoliocolbydaman
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfoliogregmlewis
 
Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01Gyanendra Kumar
 
SSRS Report with Parameters and Data Filtration
SSRS Report with Parameters and Data FiltrationSSRS Report with Parameters and Data Filtration
SSRS Report with Parameters and Data FiltrationNaji El Kotob
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptxEllenGracePorras
 

Ähnlich wie Introduction to SQL (20)

Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome Measures
 
Practical guide to SQL basics
Practical guide to SQL basicsPractical guide to SQL basics
Practical guide to SQL basics
 
Sql General
Sql General Sql General
Sql General
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Sql basics
Sql basicsSql basics
Sql basics
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for Beginners
 
Sql Portfolio(March 31)
Sql Portfolio(March 31)Sql Portfolio(March 31)
Sql Portfolio(March 31)
 
Database optimization
Database optimizationDatabase optimization
Database optimization
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
James Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science PortfolioJames Colby Maddox Business Intellignece and Computer Science Portfolio
James Colby Maddox Business Intellignece and Computer Science Portfolio
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfolio
 
Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01
 
SQL for ETL Testing
SQL for ETL TestingSQL for ETL Testing
SQL for ETL Testing
 
SSRS Report with Parameters and Data Filtration
SSRS Report with Parameters and Data FiltrationSSRS Report with Parameters and Data Filtration
SSRS Report with Parameters and Data Filtration
 
Sq lite module6
Sq lite module6Sq lite module6
Sq lite module6
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
 

Kürzlich hochgeladen

Mapping the pubmed data under different suptopics using NLP.pptx
Mapping the pubmed data under different suptopics using NLP.pptxMapping the pubmed data under different suptopics using NLP.pptx
Mapping the pubmed data under different suptopics using NLP.pptxVenkatasubramani13
 
Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024
Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024
Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024Guido X Jansen
 
Elements of language learning - an analysis of how different elements of lang...
Elements of language learning - an analysis of how different elements of lang...Elements of language learning - an analysis of how different elements of lang...
Elements of language learning - an analysis of how different elements of lang...PrithaVashisht1
 
CCS336-Cloud-Services-Management-Lecture-Notes-1.pptx
CCS336-Cloud-Services-Management-Lecture-Notes-1.pptxCCS336-Cloud-Services-Management-Lecture-Notes-1.pptx
CCS336-Cloud-Services-Management-Lecture-Notes-1.pptxdhiyaneswaranv1
 
TINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptx
TINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptxTINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptx
TINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptxDwiAyuSitiHartinah
 
Master's Thesis - Data Science - Presentation
Master's Thesis - Data Science - PresentationMaster's Thesis - Data Science - Presentation
Master's Thesis - Data Science - PresentationGiorgio Carbone
 
ChistaDATA Real-Time DATA Analytics Infrastructure
ChistaDATA Real-Time DATA Analytics InfrastructureChistaDATA Real-Time DATA Analytics Infrastructure
ChistaDATA Real-Time DATA Analytics Infrastructuresonikadigital1
 
5 Ds to Define Data Archiving Best Practices
5 Ds to Define Data Archiving Best Practices5 Ds to Define Data Archiving Best Practices
5 Ds to Define Data Archiving Best PracticesDataArchiva
 
How is Real-Time Analytics Different from Traditional OLAP?
How is Real-Time Analytics Different from Traditional OLAP?How is Real-Time Analytics Different from Traditional OLAP?
How is Real-Time Analytics Different from Traditional OLAP?sonikadigital1
 
Rock Songs common codes and conventions.pptx
Rock Songs common codes and conventions.pptxRock Songs common codes and conventions.pptx
Rock Songs common codes and conventions.pptxFinatron037
 
The Universal GTM - how we design GTM and dataLayer
The Universal GTM - how we design GTM and dataLayerThe Universal GTM - how we design GTM and dataLayer
The Universal GTM - how we design GTM and dataLayerPavel Šabatka
 
CI, CD -Tools to integrate without manual intervention
CI, CD -Tools to integrate without manual interventionCI, CD -Tools to integrate without manual intervention
CI, CD -Tools to integrate without manual interventionajayrajaganeshkayala
 
Cash Is Still King: ATM market research '2023
Cash Is Still King: ATM market research '2023Cash Is Still King: ATM market research '2023
Cash Is Still King: ATM market research '2023Vladislav Solodkiy
 
Virtuosoft SmartSync Product Introduction
Virtuosoft SmartSync Product IntroductionVirtuosoft SmartSync Product Introduction
Virtuosoft SmartSync Product Introductionsanjaymuralee1
 
Optimal Decision Making - Cost Reduction in Logistics
Optimal Decision Making - Cost Reduction in LogisticsOptimal Decision Making - Cost Reduction in Logistics
Optimal Decision Making - Cost Reduction in LogisticsThinkInnovation
 
Strategic CX: A Deep Dive into Voice of the Customer Insights for Clarity
Strategic CX: A Deep Dive into Voice of the Customer Insights for ClarityStrategic CX: A Deep Dive into Voice of the Customer Insights for Clarity
Strategic CX: A Deep Dive into Voice of the Customer Insights for ClarityAggregage
 

Kürzlich hochgeladen (16)

Mapping the pubmed data under different suptopics using NLP.pptx
Mapping the pubmed data under different suptopics using NLP.pptxMapping the pubmed data under different suptopics using NLP.pptx
Mapping the pubmed data under different suptopics using NLP.pptx
 
Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024
Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024
Persuasive E-commerce, Our Biased Brain @ Bikkeldag 2024
 
Elements of language learning - an analysis of how different elements of lang...
Elements of language learning - an analysis of how different elements of lang...Elements of language learning - an analysis of how different elements of lang...
Elements of language learning - an analysis of how different elements of lang...
 
CCS336-Cloud-Services-Management-Lecture-Notes-1.pptx
CCS336-Cloud-Services-Management-Lecture-Notes-1.pptxCCS336-Cloud-Services-Management-Lecture-Notes-1.pptx
CCS336-Cloud-Services-Management-Lecture-Notes-1.pptx
 
TINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptx
TINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptxTINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptx
TINJUAN PEMROSESAN TRANSAKSI DAN ERP.pptx
 
Master's Thesis - Data Science - Presentation
Master's Thesis - Data Science - PresentationMaster's Thesis - Data Science - Presentation
Master's Thesis - Data Science - Presentation
 
ChistaDATA Real-Time DATA Analytics Infrastructure
ChistaDATA Real-Time DATA Analytics InfrastructureChistaDATA Real-Time DATA Analytics Infrastructure
ChistaDATA Real-Time DATA Analytics Infrastructure
 
5 Ds to Define Data Archiving Best Practices
5 Ds to Define Data Archiving Best Practices5 Ds to Define Data Archiving Best Practices
5 Ds to Define Data Archiving Best Practices
 
How is Real-Time Analytics Different from Traditional OLAP?
How is Real-Time Analytics Different from Traditional OLAP?How is Real-Time Analytics Different from Traditional OLAP?
How is Real-Time Analytics Different from Traditional OLAP?
 
Rock Songs common codes and conventions.pptx
Rock Songs common codes and conventions.pptxRock Songs common codes and conventions.pptx
Rock Songs common codes and conventions.pptx
 
The Universal GTM - how we design GTM and dataLayer
The Universal GTM - how we design GTM and dataLayerThe Universal GTM - how we design GTM and dataLayer
The Universal GTM - how we design GTM and dataLayer
 
CI, CD -Tools to integrate without manual intervention
CI, CD -Tools to integrate without manual interventionCI, CD -Tools to integrate without manual intervention
CI, CD -Tools to integrate without manual intervention
 
Cash Is Still King: ATM market research '2023
Cash Is Still King: ATM market research '2023Cash Is Still King: ATM market research '2023
Cash Is Still King: ATM market research '2023
 
Virtuosoft SmartSync Product Introduction
Virtuosoft SmartSync Product IntroductionVirtuosoft SmartSync Product Introduction
Virtuosoft SmartSync Product Introduction
 
Optimal Decision Making - Cost Reduction in Logistics
Optimal Decision Making - Cost Reduction in LogisticsOptimal Decision Making - Cost Reduction in Logistics
Optimal Decision Making - Cost Reduction in Logistics
 
Strategic CX: A Deep Dive into Voice of the Customer Insights for Clarity
Strategic CX: A Deep Dive into Voice of the Customer Insights for ClarityStrategic CX: A Deep Dive into Voice of the Customer Insights for Clarity
Strategic CX: A Deep Dive into Voice of the Customer Insights for Clarity
 

Introduction to SQL

  • 2. What isSQL?  SQL stands for Structured Query Language  SQL lets you access and manipulate databases  SQL is anANSI (American National Standards Institute) standard
  • 3. WhatCanSQL do?  SQL can execute queries against a database  SQL can retrieve data from a database  SQL can insert records in a database  SQL can update records in a database  SQL can delete records from a database  SQL can create new databases  SQL can create new tables in a database  SQL can create stored procedures in a database  SQL can create views in a database  SQL can set permissions on tables, procedures, and views
  • 4. SQL is a Standard - BUT....  There are different versions of the SQL language  They all support at least the major commands  Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
  • 5. What is RDBMS?  RDBMS stands for Relational Database Management System.  RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.  The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.  Look at the "Customers" table: SELECT * FROM Customers;
  • 6. SQLSyntax  DatabaseTables Columns or Fields, Rows or Records, Indexes, etc…  SQL Statements SELECT * FROM Customers; It’s not Case Sensitive  SQL Expressions Column Names, Formula, Sub-Query, etc…  Semicolon after SQL Statements? Some database systems require a semicolon at the end of each SQL statement  Some ofThe Most Important SQLCommands  SELECT - extracts data from a database  UPDATE - updates data in a database  DELETE - deletes data from a database  INSERT INTO - inserts new data into a database
  • 7. SQLSELECT Statement The SELECT statement is used to select data from a database
  • 8. SELECT Syntax SELECT column1, column2, ... FROM table_name; SELECT * FROM table_name; SELECT CustomerKey, FirstName, LastName FROM DimCustomer;
  • 9. MoreSELECT Stuff  TOP N  ORDER BY  ORDER BY DESC  DISTINCT  Alias Names  Concatenation
  • 10. SELECT WHERE SELECT column1, column2, ... FROM table_name WHERE condition; SELECT * FROM DimCustomer WHERE Gender = ‘F’; Operator Description = Equal <> Not equal. Note: In some versions of SQL this operator may be written as != > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern IN To specify multiple possible values for a column
  • 11. MoreWHERE Stuff  Dealing with NULL values  AND, OR, NOT  LIKE  %  _  IN
  • 12. SELECT WHERE Quiz  Female Customers  Female Customers younger than 40  Female Customers younger than 40 and married  MaleCustomers with middle name  MaleCustomers who their names start with ‘Jon’  Customers with income between 30000-50000  Single female customers between 25-40 years old how make more than $100K a year
  • 13. Aggregation  MIN  MAX  AVG  COUNT  SUM  COUNT(DISTINCT)
  • 14. GROUP BY  After WHERE Clause  Before Order By Clause  HAVING Clause  Aggregations in GROUP BY SELECT column1, column2, ... FROM table_name WHERE condition GROUP BY column1, column2, ...;
  • 15. GROUP BY Quiz  Customers by Gender  Customers by Marital Status  Customers by Age  Customer Count by Gender  Customer Count by Gender and Marital Status  Average Income by Gender  Female Customers count in 25-40 years old by Age  …
  • 16. SQLJOINs  When do we join?  Different types of JOINs  CROSS JOIN  How to choose which type is appropriate?  Deal with NULL values
  • 17. INNER JOIN SELECT DimCustomer.CustomerKey, DimCustomer.FirstName, DimCustomer.LastName, DimGeography.EnglishCountryRegionName, DimGeography.City FROM DimCustomer INNER JOIN DimGeography ON DimCustomer.GeographyKey = DimGeography.GeographyKey SELECT DimGeography.EnglishCountryRegionName, DimGeography.City, Customer.CustomerKey, Customer.FirstName, Customer.LastName, Sales.SalesOrderNumber, Sales.SalesAmount FROM FactInternetSales Sales INNER JOIN DimCustomer Customer ON Customer.CustomerKey = Sales.CustomerKey INNER JOIN DimGeography ON Customer.GeographyKey = DimGeography.GeographyKey
  • 18. LEFT/RIGHT JOIN SELECT P.EnglishProductName, PSC.EnglishProductSubcategoryName FROM DimProductSubcategory PSC LEFT OUTER JOIN DimProduct P ON P.ProductSubcategoryKey = PSC.ProductSubcategoryKey SELECT P.EnglishProductName, PSC.EnglishProductSubcategoryName FROM DimProductSubcategory PSC RIGHT OUTER JOIN DimProduct P ON P.ProductSubcategoryKey = PSC.ProductSubcategoryKey
  • 19. FULLJOIN SELECT * FROM DimProductCategory PC FULL OUTER JOIN DimProductMarginTarget PCT ON PC.ProductCategoryKey = PCT.ProductCategoryKey
  • 20. SQLJOINs Quiz  Join DimProduct, DimProductSubcategory, DimProductCategory and select Keys and Names from each table  Join FactInternetSales, DimCustomer, DimProduct and show which Product is Sold toWhich Customer with all the measures  ProductCount by Category  SalesAmount By Country  OrderQuantity by Product Color  SalesAmount and OrderQuantity byYear, Country, ProductCategory  How many Bikes have we sold to each Country in 1386  SalesAmount by Customer Gender  SalesAmount by Customer Gender, MaritalStatus in the US  Which one bought more Accessories, Men orWomen?
  • 21. Sub-Queries  Select Statements within Select Statement  Used in:  SELECT Clause  FROM Clause  JOINs  WHERE Clause
  • 22. Sub-Queries in SELECT  One row, One column  Relates to the main query by usingWHERE  Needs an Alias Name  Could use internal joins as many times as needed SELECT P.ProductKey, P.EnglishProductName, ( SELECT SUM(S.OrderQuantity) FROM FactInternetSales S WHERE S.ProductKey = P.ProductKey ) AS SalesQuantity FROM DimProduct P
  • 23. Sub-Queries in FROM  Multiple rows, Multiple columns  Treated just like aTable  Needs an Alias Name  Could use internal joins as many times as needed SELECT MonthlySales.Year, Sum(TotalSales) ASTotalSalesSummary, Min(TotalSales) ASTotalSalesMinimum, Max(TotalSales) AS TotalSalesMaximum, Avg(TotalSales) ASTotalSalesAvg FROM ( SELECT D.Year, D.MonthKey, Sum(OrderQuantity) ASTotalSales FROM FactInternetSales S INNER JOIN DimDatePersian D ON S.OrderDateKey = D.DateKey Group By D.Year, D.MonthKey ) MonthlySales Group By MonthlySales.Year
  • 24. Sub-Queries in JOINs  Same as FROM Sub-Queries  Relate to each other with JOIN SELECT PRODUCTS.ProductCategoryKey, PRODUCTS.EnglishProductCategoryName, SUM(OrderQuantity) AS TotalSales FROM FactInternetSales S INNER JOIN ( SELECT PC.ProductCategoryKey, PC.EnglishProductCategoryName, P.ProductKey FROM DimProduct P INNER JOIN DimProductSubCategory PSC ON P.ProductSubcategoryKey = PSC.ProductSubcategoryKey INNER JOIN DimProductCategory PC ON PC.ProductCategoryKey = PSC.ProductCategoryKey ) PRODUCTS ON PRODUCTS.ProductKey = S.ProductKey GROUP BY PRODUCTS.ProductCategoryKey, PRODUCTS.EnglishProductCategoryName
  • 25. Sub-Queries in FROM  Multiple rows, One column  Usually used for IN or NOT IN conditions  Doesn’t need an Alias Name  Could use internal joins as many times as needed SELECT * FROM FactInternetSales WHERE ProductKey IN ( SELECT P.ProductKey FROM DimProduct P INNER JOIN DimProductSubCategory PSC ON P.ProductSubcategoryKey = PSC.ProductSubcategoryKey INNER JOIN DimProductCategory PC ON PC.ProductCategoryKey = PSC.ProductCategoryKey WHERE PC.ProductCategoryKey = 1 )
  • 26. CROSSJOIN  Cartesian product of theTables involved in the JOIN  Result rows count =Table1.Rows xTable2.Rows x …  Used for computing Measures from unrelated Dimensions  If aWHERE clause is added, the cross join behaves as an inner join SELECT CUSTOMERS.CustomerKey, PRODUCTS.ProductKey, ( SELECT ISNULL(SUM(S.OrderQuantity), 0) FROM FactInternetSales S WHERE S.ProductKey = PRODUCTS.ProductKey and S.CustomerKey = CUSTOMERS.CustomerKey )TotalSales FROM ( SELECT TOP(10) CustomerKey FROM DimCustomer ) CUSTOMERS CROSS JOIN ( SELECT TOP(10) ProductKey FROM DimProduct ORDER BY ListPrice DESC ) PRODUCTS ORDER BYTotalSales DESC
  • 27. Sub-Queries Quiz  Select Customers withTotal Purchased Amount  Select only the Products which have been sold  Find out OrderQuantity sold in each country from each product color  Show monthly SalesAmount distribution in each country  CombineYears and Customer Gender, and find each combination Sales  Yearly Sales for Customers in the US (Use Sub-Query not JOIN)
  • 28. About Me Amin Choroomi CTO & Co-Founder at vdash Software Developer, Teacher and Consultant DataVisualization, Analytics, Dashboards Data Warehousing, Integration, Business Intelligence http://www.vdash.ir choroomi@live.com choroomi@vdashonline.com https://linkedin.com/in/choroomi @aminchoroomi