StructuredQueryLanguage
Hans-PetterHalvorsen
SQLServerandSQL
StepbystepExercises
DatabaseSystems
Hans-PetterHalvorsen,M.Sc.
DatabaseSystems
3
ADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredindifferenttables.- “Everything”todayisstoredindatabases!
Examples:• Bank/Accountsystems• InformationinWebpagessuchasFacebook,Wikipedia,YouTube,etc.
• Fronter,TimeEdit,etc.• …lotsofotherexamples!
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.
MicrosoftSQLServer
5
SQLServerconsistsofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- itisjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudioisgraphicaltoolforconfiguringandviewingtheinformationinthedatabase.Itcanbeinstalledontheserverorontheclient(orboth).
ThenewestversionofMicrosoftSQLServeris“SQLServer2014”
DatabaseDesign
6
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:
8
PrimaryKeyPrimaryKey
ForeignKey
TableName
TableName
ColumnNames
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”,...)
10
Students:CreatethisExampleusingERwin.CreatetheTablesinSQLServer.
DatabaseDesignExercise
SQLServer
Hans-PetterHalvorsen,M.Sc.
MicrosoftSQLServer– CreateaNewDatabase
12
1
2
Nameyoudatabase,e.g.,WEATHER_SYSTEM
MicrosoftSQLServer
13
1
2
3
4
5
WriteyourQueryhere
TheresultfromyourQuery
YourDatabase
YourTables
YourSQLServer
14
MicrosoftSQLServer
Makesuretouncheckthisoption!
Doyougetanerrorwhentryingtochangeyourtables?
CreateTablesusingtheDesignerToolsinSQLServer
15
Evenifyoucando“everything”usingtheSQLlanguage,itissometimeseasiertodosomethinginthedesignertoolsintheManagementStudioinSQLServer.Insteadofcreatingascriptyoumayaswelleasilyusethedesignerforcreatingtables,constraints,insertingdata,etc.
Select“NewTable…”: Next,thetabledesignerpopsupwhereyoucanaddcolumns,datatypes,etc.
1 2
Inthisdesignerwemayalsospecifyconstraints,suchasprimarykeys,unique,foreignkeys,etc.
CreateTableswiththe“DatabaseDiagram”
16
3
4
5
1 2
YoumayselectexistingtablesorcreatenewTables
CreateNewTable
EnterColumns,selectDataTypes,PrimaryKeys,etc.
StructuredQueryLanguageSQL
Hans-PetterHalvorsen,M.Sc.
WhatisSQL
• SQL– StructuredQueryLanguage• SQLisastandardlanguageforaccessingdatabases.
18
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
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
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
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:
SQLQueries
23
Students:CreatethefollowingTableandDatausingSQL
TableName:CUSTOMER
INSERT
24
Example:INSERTINTOCustomers(CustomerName,ContactName,Address,City,PostalCode,Country)VALUES('Cardinal','TomB.Erichsen','Skagen21','Stavanger','4006','Norway');
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
UPDATE
26
Students:WriteandExecutethefollowingQueries.
UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg'WHERECustomerName='AlfredsFutterkiste'
UpdateWarning!Becarefulwhenupdatingrecords.WhathappensifwehadomittedtheWHEREclause,intheexampleabove,likethis:
UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg';
DELETE
27
Students:WriteandExecutethefollowingQueries.
DELETEFROMCUSTOMERWHERECustomerName='AlfredsFutterkiste'ANDContactName='MariaAnders'
Itispossibletodeleteallrowsinatablewithoutdeletingthetable
DELETE*FROMCUSTOMER
SQLQueries
28
Students:CreatetheTablesshownaboveusingSQL
Students:InsertsomeDataintotheTablesusingSQL
SELECT
29Students:GetalldatafromtheBOOKtableusingSQL
AdvancedSQLFeatures• Views:Viewsarevirtualtableforeasieraccesstodatastoredinmultipletables.
• StoredProcedures:AStoredProcedureisaprecompiledcollectionofSQLstatements.Inastoredprocedureyoucanuseifsentence,declarevariables,etc.
• Triggers:Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableinadatabase.
• Functions:WithSQLandSQLServeryoucanuselotsofbuilt-infunctionsoryoumaycreateyourownfunctions
30
GetDatafrommultiple tablesinasingleQueryusingJoins
31
selectSchoolName,CourseNamefromSCHOOLinnerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId
Example:
YoulinkPrimaryKeysandForeignKeystogether
Students:TrythisExample
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
CreatingViewsusingtheEditor
33
1
2
3
4Addnecessarytables
SavetheView
GraphicalInterfacewhereyoucanselectcolumnsyouneed
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
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
Quiz
36
http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL
TestyourskillswiththisMultiplechoiceTest
37
SQLTutorial
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)
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
40
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/