SQL
Server and SQL
Structured Query Language
Step by step Exercises
Hans-Petter Halvorsen
Database
Systems
Hans-Petter Halvorsen, M.Sc.
Database Systems
A Database is a structured way to store lots of
information. The information is stored in different
tables.
- “Everything” today is stored in databases!
Examples:
• Bank/Account systems
• Information in Web pages such as Facebook,
Wikipedia, YouTube, etc.
• Fronter, TimeEdit, etc.
• … lots of other examples!
3
Database Management Systems (DBMS)
• Microsoft SQL Server
– Enterprise, Developer versions, etc. (Professional use)
– Express version is free of charge
• Oracle
• MySQL (owned by Oracle, but previously owned by Sun
Microsystems) - MySQL can be used free of charge (open
source license), Web sites that use MySQL: YouTube,
Wikipedia, Facebook
• Microsoft Access
• IBM DB2
• Sybase
• etc.
We will use SQL server because it is very popular in the industry today, and we can use it for
free via the Microsoft DreamSpark Premium Subscription – which is available for the
students and staff at Telemark University College, or use the Express version which is available
for free for everybody. 4
Microsoft SQL Server
SQL Server consists of a Database Engine and a Management Studio. The Database Engine has no graphical interface - it
is just a service running in the background of your computer (preferable on the server). The Management Studio is
graphical tool for configuring and viewing the information in the database. It can be installed on the server or on the
client (or both).
The newest version of Microsoft SQL
Server is “SQL Server 2014”
5
Database Design
6
Database Design – ER Diagram
ER Diagram (Entity-Relationship Diagram)
• Used for Design and Modeling of Databases.
• Specify Tables and relationship between them (Primary Keys and
Foreign Keys) Table Name
Example:
Table Name
Column
Names
Primary Key
Primary Key
Foreign Key
Relational Database. In a relational database all the tables have one or more relation with each other using Primary Keys
7
(PK) and Foreign Keys (FK). Note! You can only have one PK in a table, but you may have several FK’s.
Table Name
Table Name
Column
Names
Primary Key
Primary Key
Foreign Key
8
Database - “Best Practice”
• Tables: Use upper case and singular form in table names – not
plural, e.g., “STUDENT” (not “students”)
• Columns: Use Pascal notation, e.g., “StudentId”
• Primary Key:
• If the table name is “COURSE”, name the Primary Key column
“CourseId”, etc.
• “Always” use Integer and Identity(1,1) for Primary Keys. Use
UNIQUE constraint for other columns that needs to be unique,
e.g. “RoomNumber”
• Specify Required Columns (NOT NULL) – i.e., which columns that
need to have data or not
• Standardize on few/these Data Types: int, float, varchar(x),
datetime, bit
• Use English for table and column names
• Avoid abbreviations! (Use “RoomNumber” – not “RoomNo”,
“RoomNr”, ...) 9
Database Design Exercise
Students: Create this Example
using ERwin.
Create the Tables in SQL Server. 10
SQL Server
Hans-Petter Halvorsen, M.Sc.
Microsoft SQL Server – Create a New Database
2
1 Name you database, e.g.,
WEATHER_SYSTEM
12
Microsoft SQL Server
3
Your SQL Server 4
1
Your Database Write your Query here
2
Your
Tables
5 The result from your Query
13
Microsoft SQL Server
Do you get an error
when trying to
change your tables?
Make sure to uncheck
this option!
14
Create Tables using the Designer Tools
in SQL Server
Even if you can do “everything” using the SQL language, it is sometimes easier to do
something in the designer tools in the Management Studio in SQL Server.
Instead of creating a script you may as well easily use the designer for creating tables,
constraints, inserting data, etc.
1 2
Select “New Table …”: Next, the table designer pops up where you
can add columns, data types, etc.
In this designer we may also specify constraints, such as
primary keys, unique, foreign keys, etc.
15
Create Tables with the “Database Diagram”
2
1
You may select
existing tables or
create new Tables
Create New Table
5
3
Enter Columns, select Data Types,
4 Primary Keys, etc.
16
SQL
Structured Query Language
Hans-Petter Halvorsen, M.Sc.
What is SQL
• SQL – Structured Query Language
• SQL is a standard language for accessing
databases.
18
SQL – Structured Query Language
Query Examples:
• 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
We have 4 different Query Types: INSERT, SELECT, UPDATE and DELETE
19
Important SQL Commands
• 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
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
20
SQL Structured Query Language (SQL)
DDL DML
Data Definition Language (DDL) Data Manipulation Language (DML)
CRUD
Create Drop
CREATE Tables DELETE Tables Create INSERT INTO
Alter Read SELECT
Rename
ALTER Tables
RENAME Tables Update UPDATE
Delete DELETE
Create Tables using SQL
Example:
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
...
...
22
SQL Queries
Table Name: CUSTOMER
Students: Create the following Table and Data using SQL
23
INSERT
Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
24
SELECT
Students: Write and Execute the following Queries.
SELECT * FROM CUSTOMER
SQL is NOT case sensitive: select is the same as SELECT
SELECT CustomerName, City FROM CUSTOMER
SELECT DISTINCT City FROM CUSTOMER
SELECT * FROM CUSTOMER WHERE Country='Mexico'
SELECT * FROM CUSTOMER WHERE CustomerID=1
SELECT * FROM CUSTOMER WHERE Country='Germany’ AND City='Berlin'
SELECT * FROM CUSTOMER WHERE City='Berlin’ OR City='München'
SELECT * FROM CUSTOMER ORDER BY Country
SELECT * FROM CUSTOMER ORDER BY Country DESC
25
UPDATE
Students: Write and Execute the following Queries.
UPDATE CUSTOMER
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste'
Update Warning!
Be careful when updating records. What happens if we had
omitted the WHERE clause, in the example above, like this:
UPDATE CUSTOMER
SET ContactName='Alfred Schmidt', City='Hamburg';
26
DELETE
Students: Write and Execute the following Queries.
DELETE FROM CUSTOMER
WHERE CustomerName='Alfreds Futterkiste'
AND ContactName='Maria Anders'
It is possible to delete all rows in a table without deleting the table
DELETE * FROM CUSTOMER
27
SQL Queries
Students: Create the Tables shown above using SQL
Students: Insert some Data into the Tables using SQL
28
SELECT
Students: Get all data from the BOOK table using SQL
29
Advanced SQL Features
• Views: Views are virtual table for easier access to
data stored in multiple tables.
• Stored Procedures: A Stored Procedure is a
precompiled collection of SQL statements. In a
stored procedure you can use if sentence, declare
variables, etc.
• Triggers: A database trigger is code that is
automatically executed in response to certain
events on a particular table in a database.
• Functions: With SQL and SQL Server you can use
lots of built-in functions or you may create your
own functions
30
Get Data from multiple tables in a
single Query using Joins
Example:
Students: Try this Example
select
SchoolName,
CourseName
from You link Primary Keys and Foreign Keys together
SCHOOL
inner join COURSE on SCHOOL.SchoolId = COURSE.SchoolId 31
Create View: Creating Views using SQL
IF EXISTS (SELECT name A View is a “virtual” table that
FROM sysobjects
WHERE name = 'CourseData' can contain data from multiple
AND type = 'V') tables
DROP VIEW CourseData
GO
This part is not necessary – but if you make any
changes, you need to delete the old version before
CREATE VIEW CourseData
you can update it
AS
SELECT
SCHOOL.SchoolId, The Name of the View
SCHOOL.SchoolName,
COURSE.CourseId,
COURSE.CourseName, Inside the View you join the
COURSE.Description
different tables together using
FROM the JOIN operator
SCHOOL
INNER JOIN COURSE ON SCHOOL.SchoolId = COURSE.SchoolId
GO
Students: Create this View and make sure it works
Using the View: You can Use the View as an
select * from CourseData ordinary table in Queries :
32
Creating Views using the Editor
3
Graphical Interface where you can select columns you need
1
4
Add necessary tables
Save the View 33
Create Stored Procedure:
Stored Procedure
IF EXISTS (SELECT name
FROM sysobjects
A Stored Procedure is like Method in C#
WHERE name = 'StudentGrade' - it is a piece of code with SQL
AND type = 'P')
DROP PROCEDURE StudentGrade commands that do a specific task – and
OG you reuse it
CREATE PROCEDURE StudentGrade This part is not necessary – but if you make any
@Student varchar(50), changes, you need to delete the old version before
@Course varchar(10), you can update it
@Grade varchar(1)
Procedure Name
AS
Input Arguments
DECLARE
@StudentId int, Internal/Local Variables
@CourseId int
Note! Each variable starts with @
select StudentId from STUDENT where StudentName = @Student
select CourseId from COURSE where CourseName = @Course
SQL Code (the “body” of the
insert into GRADE (StudentId, CourseId, Grade) Stored Procedure)
values (@StudentId, @CourseId, @Grade)
GO
Students: Create this Stored Procedure and make
Using the Stored Procedure: sure it works
execute StudentGrade 'John Wayne', 'SCE2006', 'B'
34
Trigger
A Trigger is executed when you insert, update or delete data in a Table specified in
the Trigger.
This part is not necessary – but if you make any
changes, you need to delete the old version before
Create the Trigger: you can update it
IF EXISTS (SELECT name
FROM sysobjects Inside the
WHERE name = 'CalcAvgGrade'
AND type = 'TR')
Trigger you can
DROP TRIGGER CalgAvgGrade
Name of the Trigger use ordinary SQL
GO
statements,
CREATE TRIGGER CalcAvgGrade ON GRADE Specify which Table the create variables,
FOR UPDATE, INSERT, DELETE
AS Trigger shall work on etc.
Specify what kind of operations the Trigger
DECLARE
@StudentId int, shall act on
@AvgGrade float
Internal/Local Variables
select @StudentId = StudentId from INSERTED
SQL Code
select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId (The “body”
update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId of the Trigger)
GO
Students: Create this Trigger and make sure it works
Note! “INSERTED” is a temporarily table containing the latest inserted data, and it is very
handy to use inside a trigger 35
Quiz
Test your skills with this Multiple choice Test
http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL
36
SQL Tutorial
37
Create Tables using SQL
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: Create the necessary Tables in SQL Server (either with a SQL
38
Script or use the Designer Tools in SQL Server )
References
• H.-P. Halvorsen. (2014). Structured Query Language. Available:
http://home.hit.no/~hansha/?tutorial=sql
• NTNU. (2013). TDT4140 Systemutvikling. 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-Petter Halvorsen, M.Sc.
University College of Southeast Norway
www.usn.no
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/