SlideShare ist ein Scribd-Unternehmen logo
1 von 37
SQL Basics
Some common queries
SELECT
USE AdventureWorks
GO
SELECT ContactID,
Title,
FirstName,
LastName
FROM Person.Contact
Comment:
Person is the Schema and
Contact is the Table
Comment:
Person is the Schema and
Contact is the Table
SELECT ALL
USE AdventureWorks
GO
SELECT *
FROM Person.Contact
Comment: Good
practise to
explicity
reference only
necessary
columns
Comment: Good
practise to
explicity
reference only
necessary
columns
FILTER
USE AdventureWorks
GO
SELECT Title,
FirstName,
LastName
FROM Person.Contact
WHERE Title = 'Ms.'
AND
USE AdventureWorks
GO
SELECT Title,
FirstName,
LastName
FROM Person.Contact
WHERE Title = 'Ms.' AND
LastName = 'Antrim'
OR
USE AdventureWorks
GO
SELECT Title,
FirstName,
LastName
FROM Person.Contact
WHERE Title = 'Ms.' OR
LastName = 'Antrim'
NOT
USE AdventureWorks
GO
SELECT Title,
FirstName,
LastName
FROM Person.Contact
WHERE NOT Title = 'Ms.'
WITHOUT PARENTHESIS
USE AdventureWorks
GO
SELECT Title,
FirstName,
LastName
FROM Person.Contact
WHERE Title = 'Ms.' AND
FirstName = 'Catherine' OR
LastName = 'Adams'
With Parentheses
SELECT ContactID,
Title,
FirstName,
MiddleName,
LastName
FROM Person.Contact
WHERE (Title = 'Ms.' AND
FirstName = 'Catherine') OR
LastName = 'Adams'
BETWEEN
USE AdventureWorks
GO
SELECT SalesOrderID,
ShipDate
FROM Sales.SalesOrderHeader
WHERE ShipDate BETWEEN '7/28/2002' AND '7/29/2002'
Less Than
USE AdventureWorks
GO
SELECT ProductID,
Name,
StandardCost
FROM Production.Product
WHERE StandardCost < 110.0000
IS NULL
USE AdventureWorks
GO
SELECT ProductID,
Name,
Weight
FROM Production.Product
WHERE Weight IS NULL
IN
USE AdventureWorks
GO
SELECT ProductID,
Name,
Color
FROM Production.Product
WHERE Color IN ('Silver', 'Black', 'Red')
LIKE
USE AdventureWorks
GO
SELECT ProductID,
Name
FROM Production.Product
WHERE Name LIKE 'B%'
Escape
USE AdventureWorks
GO
SELECT ProductID,
Name
FROM Production.Product
WHERE Name LIKE '%/_%' ESCAPE '/'
ORDER BY
USE AdventureWorks
GO
SELECT p.Name,
h.EndDate,
h.ListPrice
FROM Production.Product p
INNER JOIN Production.ProductListPriceHistory h ON
p.ProductID = h.ProductID
ORDER BY p.Name, h.EndDate
ORDER - DESC
USE AdventureWorks
GO
SELECT p.Name,
h.EndDate,
h.ListPrice
FROM Production.Product p
INNER JOIN Production.ProductListPriceHistory h ON
p.ProductID = h.ProductID
ORDER BY p.Name DESC, h.EndDate DESC
Comment:
Although queries
sometimes appear
to return data
properly without
an ORDER BY
clause, the natural
ordering of results
is determined by
the physical key
column order in
the clustered index
Comment:
Although queries
sometimes appear
to return data
properly without
an ORDER BY
clause, the natural
ordering of results
is determined by
the physical key
column order in
the clustered index
ORDER BY Unselected Column
USE AdventureWorks
GO
SELECT p.Name
FROM Production.Product p
TOP
USE AdventureWorks
GO
SELECT TOP 10 v.Name,
v.CreditRating
FROM Purchasing.Vendor v
ORDER BY v.CreditRating DESC, v.Name
Variables
USE AdventureWorks
GO
DECLARE @Percentage float
SET @Percentage = 1
SELECT TOP (@Percentage) PERCENT
Name
FROM Production.Product
ORDER BY Name
GROUP BY
USE AdventureWorks
GO
SELECT OrderDate,
SUM(TotalDue) TotalDueByOrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN '7/1/2001' AND '7/31/2001'
GROUP BY OrderDate
GROUP BY ALL
USE AdventureWorks
GO
SELECT OrderDate,
SUM(TotalDue) TotalDueByOrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN '7/1/2001' AND '7/31/2001'
GROUP BY ALL OrderDate
HAVING
USE AdventureWorks
GO
SELECT s.Name,
COUNT(w.WorkOrderID) Cnt
FROM Production.ScrapReason s
INNER JOIN Production.WorkOrder w ON
s.ScrapReasonID = w.ScrapReasonID
GROUP BY s.Name
HAVING COUNT(*)>50
DISTINCT
USE AdventureWorks
GO
SELECT DISTINCT HireDate
FROM HumanResources.Employee
AVG
USE AdventureWorks
GO
SELECT AVG(ListPrice)
FROM Production.Product
AVG and DISTINCT
USE AdventureWorks
GO
SELECT AVG(DISTINCT ListPrice)
FROM Production.Product
Column ALIASES
USE AdventureWorks
GO
SELECT Color AS 'Grouped Color',
AVG(DISTINCT ListPrice) AS 'Average Distinct List Price',
AVG(ListPrice) 'Average List Price'
FROM Production.Product
GROUP BY Color
INFORMATION SCHEMA
USE AdventureWorks
GO
SELECT column_name + ' IS NULL AND '
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'Employee'
ORDER BY ORDINAL_POSITION
String concatenation
USE AdventureWorks
GO
SELECT 'The ' +
p.name +
' is only ' +
CONVERT(varchar(25),p.ListPrice) +
'!'
FROM Production.Product p
WHERE p.ListPrice between 100 AND 120
ORDER BY p.ListPrice
Comma Delimited List
USE AdventureWorks
GO
DECLARE @Shifts varchar(20)
SET @Shifts = ''
SELECT @Shifts = @Shifts + s.Name + ','
FROM HumanResources.Shift s
ORDER BY s.EndTime
SELECT @Shifts
SELECT INTO
USE AdventureWorks
GO
SELECT CustomerID,
Name,
SalesPersonID,
Demographics
INTO Store_Archive
FROM Sales.Store
Comment:
This creates a
table called
Store_Archive
Comment:
This creates a
table called
Store_Archive
Create a schema with SELECT
USE AdventureWorks
GO
SELECT CustomerID,
Name,
SalesPersonID,
Demographics
INTO Store_Archive2
FROM Sales.Store
WHERE 1=0
Puzzle
I've got The Customers table : T1 .. has two columns :
ID(int) , IsDeleted(bit)
I want in a one sql query to return :
NumberOfAllCustomers --
NumberOfDeletedCustomers --
NumberOfExistingCustomers
Prepare data for puzzle
USE tempdb;
IF OBJECT_ID('dbo.T1') IS NOT NULL
DROP TABLE dbo.T1;
CREATE TABLE dbo.t1
(
ID INT NOT NULL,
IsDeleted bit
);
INSERT INTO dbo.T1(ID, IsDeleted) VALUES (1,0);
INSERT INTO dbo.T1(ID, IsDeleted) VALUES (2,1);
INSERT INTO dbo.T1(ID, IsDeleted) VALUES (3,0);
INSERT INTO dbo.T1(ID, IsDeleted) VALUES (4,1);
INSERT INTO dbo.T1(ID, IsDeleted) VALUES (5,0);
GO
Check expected answers
SELECT Count(ID) AS NumberOfAllExistingCustomers
FROM T1
SELECT Count(ID) AS NumberOfDeletedCustomers
FROM T1 WHERE IsDeleted = 1
SELECT Count(ID) AS NumberOfExistingCustomers
FROM T1 WHERE IsDeleted = 0
Answer One
SELECT COUNT(*) AS NumberOfAllCustomers,
SUM(CASE IsDeleted WHEN 1 THEN 1 END)
AS NumberOfDeletedCustomers,
SUM(CASE IsDeleted WHEN 0 THEN 1 END)
AS NumberOfExistingCustomers
FROM T1
GO
Answer Two
select numberOfAllCustomers, numberOfDeletedCustomers,
numberOfAllCustomers - numberOfDeletedCustomers
AS
NumberOfExistingCustomers
from (
select
(select count(id) from t1) numberOfAllCustomers,
(select count(id) from t1 where isdeleted=cast(1 as bit))
numberOfDeletedCustomers
) t;

Weitere ähnliche Inhalte

Ähnlich wie T-Sql basics

supporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tableMahabubur Rahaman
 
Hacking Your Way to Better Security - ZendCon 2016
Hacking Your Way to Better Security - ZendCon 2016Hacking Your Way to Better Security - ZendCon 2016
Hacking Your Way to Better Security - ZendCon 2016Colin O'Dell
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfarishmarketing21
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basicwali1195189
 
Hacking Your Way To Better Security - DrupalCon Baltimore 2017
Hacking Your Way To Better Security - DrupalCon Baltimore 2017Hacking Your Way To Better Security - DrupalCon Baltimore 2017
Hacking Your Way To Better Security - DrupalCon Baltimore 2017Colin O'Dell
 
e computer notes - Restricting and sorting data
e computer notes -  Restricting and sorting datae computer notes -  Restricting and sorting data
e computer notes - Restricting and sorting dataecomputernotes
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Achmad Solichin
 
Appendix A Tables
Appendix A   TablesAppendix A   Tables
Appendix A TablesLiquidHub
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankpptnewrforce
 
Sql server query collection
Sql server query collectionSql server query collection
Sql server query collectionRabin Koirala
 
Stored Procedures and MUMPS for DivConq
 Stored Procedures and  MUMPS for DivConq  Stored Procedures and  MUMPS for DivConq
Stored Procedures and MUMPS for DivConq eTimeline, LLC
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2Belal Arfa
 

Ähnlich wie T-Sql basics (20)

Higher SQL
Higher SQLHigher SQL
Higher SQL
 
Les02
Les02Les02
Les02
 
supporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered table
 
Hacking Your Way to Better Security - ZendCon 2016
Hacking Your Way to Better Security - ZendCon 2016Hacking Your Way to Better Security - ZendCon 2016
Hacking Your Way to Better Security - ZendCon 2016
 
Chapter08
Chapter08Chapter08
Chapter08
 
Les02
Les02Les02
Les02
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basic
 
Hacking Your Way To Better Security - DrupalCon Baltimore 2017
Hacking Your Way To Better Security - DrupalCon Baltimore 2017Hacking Your Way To Better Security - DrupalCon Baltimore 2017
Hacking Your Way To Better Security - DrupalCon Baltimore 2017
 
e computer notes - Restricting and sorting data
e computer notes -  Restricting and sorting datae computer notes -  Restricting and sorting data
e computer notes - Restricting and sorting data
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
Intro toswift1
Intro toswift1Intro toswift1
Intro toswift1
 
Module03
Module03Module03
Module03
 
Appendix A Tables
Appendix A   TablesAppendix A   Tables
Appendix A Tables
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
Sql server query collection
Sql server query collectionSql server query collection
Sql server query collection
 
Stored Procedures and MUMPS for DivConq
 Stored Procedures and  MUMPS for DivConq  Stored Procedures and  MUMPS for DivConq
Stored Procedures and MUMPS for DivConq
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
 

Mehr von rchakra

Requirement management presentation to a software team
Requirement management presentation to a software teamRequirement management presentation to a software team
Requirement management presentation to a software teamrchakra
 
Subversion client
Subversion clientSubversion client
Subversion clientrchakra
 
Subversion
SubversionSubversion
Subversionrchakra
 
Sql 2005 the ranking functions
Sql 2005   the ranking functionsSql 2005   the ranking functions
Sql 2005 the ranking functionsrchakra
 
Sql basics 2
Sql basics 2Sql basics 2
Sql basics 2rchakra
 
Sql architecture
Sql architectureSql architecture
Sql architecturerchakra
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Intro to Microsoft.NET
Intro to Microsoft.NET Intro to Microsoft.NET
Intro to Microsoft.NET rchakra
 
Object oriented programming systems
Object oriented programming systemsObject oriented programming systems
Object oriented programming systemsrchakra
 
Subversion Admin
Subversion AdminSubversion Admin
Subversion Adminrchakra
 
Intro to UML 2
Intro to UML 2Intro to UML 2
Intro to UML 2rchakra
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threadsrchakra
 

Mehr von rchakra (12)

Requirement management presentation to a software team
Requirement management presentation to a software teamRequirement management presentation to a software team
Requirement management presentation to a software team
 
Subversion client
Subversion clientSubversion client
Subversion client
 
Subversion
SubversionSubversion
Subversion
 
Sql 2005 the ranking functions
Sql 2005   the ranking functionsSql 2005   the ranking functions
Sql 2005 the ranking functions
 
Sql basics 2
Sql basics 2Sql basics 2
Sql basics 2
 
Sql architecture
Sql architectureSql architecture
Sql architecture
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Intro to Microsoft.NET
Intro to Microsoft.NET Intro to Microsoft.NET
Intro to Microsoft.NET
 
Object oriented programming systems
Object oriented programming systemsObject oriented programming systems
Object oriented programming systems
 
Subversion Admin
Subversion AdminSubversion Admin
Subversion Admin
 
Intro to UML 2
Intro to UML 2Intro to UML 2
Intro to UML 2
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 

T-Sql basics

Hinweis der Redaktion

  1. Person is the Schema and Contact is the Table