Top Banner
Structured Query Language Hans-Petter Halvorsen SQL Server and SQL Step by step Exercises
41

SQL Server and SQL

Jan 01, 2017

Download

Documents

doanduong
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SQL Server and SQL

StructuredQueryLanguage

Hans-PetterHalvorsen

SQLServerandSQL

StepbystepExercises

Page 2: SQL Server and SQL

DatabaseSystems

Hans-PetterHalvorsen,M.Sc.

Page 3: SQL Server and SQL

DatabaseSystems

3

ADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredindifferenttables.- “Everything”todayisstoredindatabases!

Examples:• Bank/Accountsystems• InformationinWebpagessuchasFacebook,Wikipedia,YouTube,etc.

• Fronter,TimeEdit,etc.• …lotsofotherexamples!

Page 4: SQL Server and SQL

DatabaseManagementSystems(DBMS)• MicrosoftSQLServer

– Enterprise,Developerversions,etc.(Professionaluse)– Expressversionisfreeofcharge

• Oracle• MySQL (ownedbyOracle,butpreviouslyownedbySun

Microsystems)- MySQLcanbeusedfreeofcharge(opensourcelicense),WebsitesthatuseMySQL:YouTube,Wikipedia,Facebook

• MicrosoftAccess• IBMDB2• Sybase• etc.

4

WewilluseSQLserverbecauseitisverypopularintheindustrytoday,andwecanuseitforfreeviatheMicrosoftDreamSparkPremiumSubscription – whichisavailableforthestudentsandstaffatTelemarkUniversityCollege,orusetheExpressversionwhichisavailableforfreeforeverybody.

Page 5: SQL Server and SQL

MicrosoftSQLServer

5

SQLServerconsistsofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- itisjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudioisgraphicaltoolforconfiguringandviewingtheinformationinthedatabase.Itcanbeinstalledontheserverorontheclient(orboth).

ThenewestversionofMicrosoftSQLServeris“SQLServer2014”

Page 6: SQL Server and SQL

DatabaseDesign

6

Page 7: SQL Server and SQL

DatabaseDesign– ERDiagram

7

ERDiagram(Entity-RelationshipDiagram)• UsedforDesignandModelingofDatabases.• SpecifyTablesandrelationship betweenthem(PrimaryKeysandForeignKeys)

PrimaryKeyPrimaryKey

ForeignKey

TableName

TableName

RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys(PK)andForeignKeys(FK).Note!YoucanonlyhaveonePKinatable,butyoumayhaveseveralFK’s.

ColumnNames

Example:

Page 8: SQL Server and SQL

8

PrimaryKeyPrimaryKey

ForeignKey

TableName

TableName

ColumnNames

Page 9: SQL Server and SQL

Database- “BestPractice”

9

• Tables:Useuppercaseandsingular formintablenames– notplural,e.g.,“STUDENT”(not“students”)

• Columns:UsePascalnotation,e.g.,“StudentId”• PrimaryKey:• Ifthetablenameis“COURSE”,namethePrimaryKeycolumn“CourseId”,etc.

• “Always”useInteger andIdentity(1,1) forPrimaryKeys.UseUNIQUEconstraintforothercolumnsthatneedstobeunique,e.g.“RoomNumber”

• SpecifyRequired Columns(NOTNULL)– i.e.,whichcolumnsthatneedtohavedataornot

• Standardizeonfew/theseDataTypes:int,float,varchar(x),datetime,bit

• UseEnglishfortableandcolumnnames• Avoidabbreviations!(Use“RoomNumber”– not“RoomNo”,“RoomNr”,...)

Page 10: SQL Server and SQL

10

Students:CreatethisExampleusingERwin.CreatetheTablesinSQLServer.

DatabaseDesignExercise

Page 11: SQL Server and SQL

SQLServer

Hans-PetterHalvorsen,M.Sc.

Page 12: SQL Server and SQL

MicrosoftSQLServer– CreateaNewDatabase

12

1

2

Nameyoudatabase,e.g.,WEATHER_SYSTEM

Page 13: SQL Server and SQL

MicrosoftSQLServer

13

1

2

3

4

5

WriteyourQueryhere

TheresultfromyourQuery

YourDatabase

YourTables

YourSQLServer

Page 14: SQL Server and SQL

14

MicrosoftSQLServer

Makesuretouncheckthisoption!

Doyougetanerrorwhentryingtochangeyourtables?

Page 15: SQL Server and SQL

CreateTablesusingtheDesignerToolsinSQLServer

15

Evenifyoucando“everything”usingtheSQLlanguage,itissometimeseasiertodosomethinginthedesignertoolsintheManagementStudioinSQLServer.Insteadofcreatingascriptyoumayaswelleasilyusethedesignerforcreatingtables,constraints,insertingdata,etc.

Select“NewTable…”: Next,thetabledesignerpopsupwhereyoucanaddcolumns,datatypes,etc.

1 2

Inthisdesignerwemayalsospecifyconstraints,suchasprimarykeys,unique,foreignkeys,etc.

Page 16: SQL Server and SQL

CreateTableswiththe“DatabaseDiagram”

16

3

4

5

1 2

YoumayselectexistingtablesorcreatenewTables

CreateNewTable

EnterColumns,selectDataTypes,PrimaryKeys,etc.

Page 17: SQL Server and SQL

StructuredQueryLanguageSQL

Hans-PetterHalvorsen,M.Sc.

Page 18: SQL Server and SQL

WhatisSQL

• SQL– StructuredQueryLanguage• SQLisastandardlanguageforaccessingdatabases.

18

Page 19: SQL Server and SQL

SQL– StructuredQueryLanguage

19

• insert into STUDENT (Name , Number, SchoolId)values ('John Smith', '100005', 1)

• select SchoolId, Name from SCHOOL

• select * from SCHOOL where SchoolId > 100

• update STUDENT set Name='John Wayne' where StudentId=2

• delete from STUDENT where SchoolId=3

QueryExamples:

Wehave4differentQueryTypes:INSERT,SELECT,UPDATEand DELETE

Page 20: SQL Server and SQL

ImportantSQLCommands• SELECT- extractsdatafromadatabase• UPDATE- updatesdatainadatabase• DELETE- deletesdatafromadatabase• INSERTINTO- insertsnewdataintoadatabase• CREATEDATABASE- createsanewdatabase• ALTERDATABASE- modifiesadatabase• CREATETABLE- createsanewtable• ALTERTABLE- modifiesatable• DROPTABLE- deletesatable• CREATEINDEX- createsanindex(searchkey)• DROPINDEX- deletesanindex

20

Page 21: SQL Server and SQL

SQL

DDL DML

StructuredQueryLanguage(SQL)

DataDefinitionLanguage(DDL) DataManipulationLanguage(DML)

Create Drop

Rename Alter

CRUD

CREATETables DELETETables

RENAMETables ALTERTables

Create

Read

Update

Delete

INSERTINTO

SELECT

UPDATE

DELETE

Page 22: SQL Server and SQL

CreateTablesusingSQL

22

CREATE TABLE [SCHOOL](

SchoolId int IDENTITY(1, 1) NOT NULL PRIMARY KEY,

SchoolName varchar(50) NOT NULL UNIQUE,Description varchar(1000) NULL,Address varchar50) NULL,Phone varchar(50) NULL,PostCode varchar(50) NULL,PostAddress varchar(50) NULL,

) GO......

Example:

Page 23: SQL Server and SQL

SQLQueries

23

Students:CreatethefollowingTableandDatausingSQL

TableName:CUSTOMER

Page 24: SQL Server and SQL

INSERT

24

Example:INSERTINTOCustomers(CustomerName,ContactName,Address,City,PostalCode,Country)VALUES('Cardinal','TomB.Erichsen','Skagen21','Stavanger','4006','Norway');

Page 25: SQL Server and SQL

SELECT

25

Students:WriteandExecutethefollowingQueries.

SELECT*FROMCUSTOMER

SELECT*FROMCUSTOMERWHERECustomerID=1

SELECTCustomerName,CityFROMCUSTOMER

SELECTDISTINCTCityFROMCUSTOMER

SELECT*FROMCUSTOMERWHERECountry='Mexico'

SQLisNOTcasesensitive:selectisthesameasSELECT

SELECT*FROMCUSTOMERWHERECountry='Germany’ANDCity='Berlin'

SELECT*FROMCUSTOMERWHERECity='Berlin’ORCity='München'

SELECT*FROMCUSTOMERORDERBYCountry

SELECT*FROMCUSTOMERORDERBYCountryDESC

Page 26: SQL Server and SQL

UPDATE

26

Students:WriteandExecutethefollowingQueries.

UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg'WHERECustomerName='AlfredsFutterkiste'

UpdateWarning!Becarefulwhenupdatingrecords.WhathappensifwehadomittedtheWHEREclause,intheexampleabove,likethis:

UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg';

Page 27: SQL Server and SQL

DELETE

27

Students:WriteandExecutethefollowingQueries.

DELETEFROMCUSTOMERWHERECustomerName='AlfredsFutterkiste'ANDContactName='MariaAnders'

Itispossibletodeleteallrowsinatablewithoutdeletingthetable

DELETE*FROMCUSTOMER

Page 28: SQL Server and SQL

SQLQueries

28

Students:CreatetheTablesshownaboveusingSQL

Students:InsertsomeDataintotheTablesusingSQL

Page 29: SQL Server and SQL

SELECT

29Students:GetalldatafromtheBOOKtableusingSQL

Page 30: SQL Server and SQL

AdvancedSQLFeatures• Views:Viewsarevirtualtableforeasieraccesstodatastoredinmultipletables.

• StoredProcedures:AStoredProcedureisaprecompiledcollectionofSQLstatements.Inastoredprocedureyoucanuseifsentence,declarevariables,etc.

• Triggers:Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableinadatabase.

• Functions:WithSQLandSQLServeryoucanuselotsofbuilt-infunctionsoryoumaycreateyourownfunctions

30

Page 31: SQL Server and SQL

GetDatafrommultiple tablesinasingleQueryusingJoins

31

selectSchoolName,CourseNamefromSCHOOLinnerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId

Example:

YoulinkPrimaryKeysandForeignKeystogether

Students:TrythisExample

Page 32: SQL Server and SQL

CreatingViewsusingSQL

32

IF EXISTS (SELECT nameFROM sysobjectsWHERE name = 'CourseData' AND type = 'V')

DROP VIEW CourseDataGO

CREATE VIEW CourseDataAS

SELECTSCHOOL.SchoolId, SCHOOL.SchoolName, COURSE.CourseId, COURSE.CourseName,COURSE.Description

FROMSCHOOL INNER JOIN COURSE ON SCHOOL.SchoolId = COURSE.SchoolIdGO

select * from CourseDataYoucanUsetheViewasanordinarytableinQueries:

AViewisa“virtual”tablethatcancontaindatafrommultipletables

InsidetheViewyoujointhedifferenttablestogetherusingtheJOIN operator

TheNameoftheView

CreateView:

UsingtheView:

Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit

Students:CreatethisViewandmakesureitworks

Page 33: SQL Server and SQL

CreatingViewsusingtheEditor

33

1

2

3

4Addnecessarytables

SavetheView

GraphicalInterfacewhereyoucanselectcolumnsyouneed

Page 34: SQL Server and SQL

StoredProcedure

34

IFEXISTS(SELECTnameFROMsysobjectsWHEREname ='StudentGrade'AND type='P')

DROPPROCEDUREStudentGradeOG

CREATEPROCEDUREStudentGrade@Studentvarchar(50),@Coursevarchar(10),@Gradevarchar(1)

AS

DECLARE@StudentId int,@CourseId int

selectStudentIdfromSTUDENTwhereStudentName =@Student

selectCourseId fromCOURSEwhereCourseName =@Course

insertintoGRADE(StudentId,CourseId,Grade)values (@StudentId,@CourseId,@Grade)GO

execute StudentGrade 'John Wayne', 'SCE2006', 'B'

AStoredProcedureislikeMethodinC#- itisapieceofcodewithSQLcommandsthatdoaspecifictask– andyoureuseit

InputArguments

Internal/LocalVariables

ProcedureName

SQLCode(the“body”oftheStoredProcedure)

Note!Eachvariablestartswith@

CreateStoredProcedure:

UsingtheStoredProcedure:

Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit

Students:CreatethisStoredProcedureandmakesureitworks

Page 35: SQL Server and SQL

Trigger

35

IF EXISTS (SELECT nameFROM sysobjectsWHERE name = 'CalcAvgGrade' AND type = 'TR')

DROP TRIGGER CalgAvgGradeGO

CREATE TRIGGER CalcAvgGrade ON GRADEFOR UPDATE, INSERT, DELETEAS

DECLARE@StudentId int,@AvgGrade float

select @StudentId = StudentId from INSERTED

select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId

update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId

GO

ATriggerisexecutedwhenyouinsert,updateordeletedatainaTablespecifiedintheTrigger.

InsidetheTriggeryoucanuseordinarySQLstatements,createvariables,etc.

NameoftheTrigger

SpecifywhichTabletheTriggershallworkon

Internal/LocalVariables

SQLCode(The“body”oftheTrigger)

SpecifywhatkindofoperationstheTriggershallacton

Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisveryhandytouseinsideatrigger

CreatetheTrigger:Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit

Students:CreatethisTriggerandmakesureitworks

Page 36: SQL Server and SQL

Quiz

36

http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL

TestyourskillswiththisMultiplechoiceTest

Page 37: SQL Server and SQL

37

SQLTutorial

Page 38: SQL Server and SQL

CreateTablesusingSQL

38

if not exists (select * from dbo.sysobjects where id = object_id(N'[SCHOOL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

CREATE TABLE [SCHOOL](

[SchoolId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[SchoolName] [varchar](50) NOT NULL UNIQUE,[Description] [varchar](1000) NULL,[Address] [varchar](50) NULL,[Phone] [varchar](50) NULL,[PostCode] [varchar](50) NULL,[PostAddress] [varchar](50) NULL,

) GO......

Students:CreatethenecessaryTablesinSQLServer(eitherwithaSQLScriptorusetheDesignerToolsinSQLServer)

Page 39: SQL Server and SQL

References• H.-P.Halvorsen.(2014).StructuredQueryLanguage.Available:

http://home.hit.no/~hansha/?tutorial=sql• NTNU.(2013).TDT4140Systemutvikling.Available:

http://www.ntnu.no/studier/emner/TDT4140• UiO.(2013).INF1050- Systemutvikling.Available:

http://www.uio.no/studier/emner/matnat/ifi/INF1050/• O.Widder.(2013).geek&poke.Available:http://geek-and-poke.com• B.Lund.(2013).Lunch.Available:http://www.lunchstriper.no,

http://www.dagbladet.no/tegneserie/lunch/• S.Adams.Dilbert.Available:http://dilbert.com

39

Page 40: SQL Server and SQL

40

Page 41: SQL Server and SQL

Hans-PetterHalvorsen,M.Sc.

UniversityCollegeofSoutheastNorwaywww.usn.no

E-mail:[email protected]:http://home.hit.no/~hansha/