You are on page 1of 10

Chapter 7 - SQL

Learning Objectives, p324

Review
The Big 3 categories
DML = manipulation (adding, deleting, modifying rows)
DCL = controlling access
DDL = creating tables, etc
this is where we are in Chapter 7

We've been using the GUI in SQL Server Management Studio


now, it's the command line!

Database specific?
How much difference is there?
DML is the most common between vendors
DDL is probably the next most common
er, well... using ISO data types

Let's create a new Chapter7 database

* fig 7-2, 326...


DDL
Create Table
Alter Table
Drop Table
Truncate Table
DML
Insert
Update
Delete
Merge?
Views
Create View
Alter View
Drop View
PSM
functions, triggers, stored procedures

DDL Statements
Create Table, p327
Create Table TableName (
3-part column definition,
optional table contraints
)

Column (parts separated by spaces, multiple cols separated by commas)


1) Column Name
2) Data Type
int = number
date = date
ISO 8601 format '2016-02-21'
nchar(10) = includes the padding (very fast)
Numeric(4,0) = exactly 4 digits, no decimal points
nvarchar(50) = more compact for storage
Should not be part of a PK (if possible)
3) Column Contraints/Properties
Not Null, Null
So, what happens if you leave out a "Not Null" value?
4) Other optional keywords
Identity (Surrogate/Synthetic/Autonumber)
Default
Not really a "contraints", per se, but hey...

Table Contraints
Primary Key, Foreign Key, Unique
each constraint has a name!

Column/Data constraints
NULL/NOT NULL, Check

let's create a Major table


Create Table Major (
MajorID int Not Null,
MajorName nvarchar(50) Not Null,
Advisor nvarchar(100) Not Null,
Constraint MajorPK Primary Key(MajorID)
)

1) The constraint is what "creates" the PK....


2) Each constraint has a name

consider a Student table...


Create Table Student (
StudentID int Not Null identity(1,1),
FirstName nvarchar(50) Not Null,
LastName nvarchar(50) Not Null,
MajorID int Null,
Phone1 nvarchar(15) Null,
Phone2 nvarchar(15) Null,
Phone3 nvarchar(15) Null,
Constraint StudentPK Primary Key(StudentID),
Constraint StudentMajorFK Foreign Key(MajorID) References
Major(MajorID)
on delete no action on update no action
)

1) Notice the Identity "constraint"... start at 1, increment by 1

2) Notice that the FK has a "references" keyword and kinda looks


like a join (without the equal sign)
3) FK constraints are often shown on two lines (but without a
comma!)
4) So, does the order of the table creation matter?

FK constraints actions
No Action (the default)
so, what happens if there is a RI violation?
Cascade
so, what happens if you delete the parent with "on delete
cascade"?
Set Null
Set Default

Let's do a compound Foreign Key example


Constraint SomeCompoundFK Foreign Key(col1, col2) References
SomeOtherTable(col1, col2)
on delete no action on update no action

* Fig 7-9, 333 example...

Relationships, p334
* fig 7-10, p334
Mostly a review from Chapter 6
... only thing added is the "unique" constraint

So, now we have 2 tools in the toolbox (NULL/NOT NULL and


Unique constraint)

optional = FK allow NULLs (the default)


mandatory = FK do not allow NULLs (NOT NULL)

1x-xN FK on the Many side


1|-|1 toss up.... doesn't really matter. Use Unique (or PK)
1O-O1 ditto... doesn't really matter (perhaps the more volatile
table?)
1O-|1 FK on the optional side, Unique on the mandatory side
Nx-xM Use an intersection instead

Unique vs PK

Defaults, 335
in MSSQL.. after NULL/NOT NULL
but I'd hardly call them a column/data "constraint"?!?!?!
Can also be done via a table constraint

[State] nchar(2) Not Null Default 'TX'

1) Not all DBMSs do it *after* the NULL/NOT NULL


2) Hey, why I use square brackets around State?

Used via insert and update


Either "ingore" the column or use the Default keyword

A good use for defaults is to include the current date via


function
TransDate DateTime not null default GetDate()

Data Contrainst, p335


in the column (yuk!... don't do that!)
Age int Check (Age>0 and Age<140)
Not very portable, so do not use...
or at the table level
Constraint StatesCK Check (State in ('TX', 'LA', 'OK',
'NM'))
Constraint ValueCK Check (SomeColumn > 5)

1) All constraints require a name...


2) Notice that the check looks just like parts of a where
clause (with the where)
3) Yes, the parathethese are required

* Fig 7-12, 336

Table/Column constraint summary


NULL/NOT NULL
Primary Key
Foreign Key
Unique
Check

skip a bit...

Alter Table, p340


Alter Table Student
Add ZodiacSign nchar(10) null

1) Rather odd, that the "add" defaults to "column"... no other


operation does!

Alter Table Student


drop column ZodiacSign

... add/drop contrainsts (by name)


Primary keys, Foreign keys, check, etc...

Drop Table, p340


good bye to the table and all it's contents

Drop Table Student

So, what about FKs (in child tables) that point to this parent table?

Alter Table Phone


Drop Constraint StudentFK

Truncate, p341
whack only the data
does this affect RI differently that a drop????

So, what's the diff between Drop and Truncate?

Index, p341
Index helps speed up queries...
it's all about the "where" clause
what about update and deletes?
kinda depends on the complexity of the where clause
what about inserts?

Wait until Chapter 10...

DML Statements 342

Let's do some inserts into the "Major" table


Insert into Major
(MajorID, MajorName, Advisor)
values
(10, 'Accounting', 'Dr. Smith')

1) Column list in parentheses


2) The "values" keyword
3) The data "row" in parentheses
4) See the single quotes on the strings?

Let's do some for the Student table


Insert into Student
(FirstName, LastName, Major, Phone1, Phone2, Phone3)
values
('Bob', 'Smith', 10, '555-1234', NULL, NULL)

1) Notice that we did not specify the StudentID in the column


list or value list!
why is that?
2) See how to specify a null (on a column where null is allowed)
3) Note: NULL is not a string (so no single quotes)

Inserting multiple rows at once...


The term "value" typically appears just once

Insert into Student


(FirstName, LastName, Major, Phone1, Phone2, Phone3)
values
('Sally', 'Smith', 20, '555-1234', '555-2345', NULL),
('Jane', 'Doe', 30, '555-4567', '555-6789', '555-7890')

1) So, each "row" is separated by commas


2) Each "row" is enclosed in parentheses

Wait... why didn't that work?

We need to add some rows to the Major table first!


Insert into Major
(MajorID, MajorName, Advisor)
values
(20, 'Accounting', 'Dr. Smith),
(30, 'CIS', 'Dr. C'),
(40, 'Enginering', 'Dr. Jones')

Now let's try that again...

Strings (and date/datetime literals)


use single quotes

What about Surrogate/Synthetic/Autonumber and Defaults columns?


just ignore them (in both the column list... and the value list)

Short cut for not providing the column names, if:


1) There are no Surrogate/Synthetic/Autonumber columns
2) You are providing values for all columns
3) Values are in proper column oder

Oooh, does that sound like a test question to you?

Insert Into Major


values
(50, 'Art', 'Mr. Smith')

1) Notice the column list is missing... but not the "values"


keyword

Bulk Insert (from another table), p343


Insert Into Student
(StudentID, FirstName, LastName, MajorID, Phone1, Phone2, Phone3)
Select StudentID, FirstName, LastName, MajorID, Phone1, Phone2,
Phone3
From SomeTable;

nested SQL... inner to outer

Hey, let's fix that Multicolumn problem with phone numbers!


now that we've learned more SQL, we can finally fix it
remember that we can have constants in a select (or insert) statement

Create Table Phone (


StudentID int Not Null,
PhoneOrder int Not Null,
PhoneNumber nvarchar(15) not Not Null,
Constraint StudentPhonePK Primary Key(PhoneNumber, StudentID),
Constraint StudentFK Foreign Key(StudentID) References
Student(StudentID)
on update no action on delete no action
)

1) See how to build a compound PK (or FK)


2) So, which table did the constraint go on?

Insert into Phone


(StudentId, PhoneOrder, Phone)
Select StudentId, 1, Phone1 from Student where Phone1 is not null;
Insert into Phone
(StudentId, PhoneOrder, Phone)
Select StudentId, 2, Phone2 from Student where Phone2 is not null;
Insert into Phone
(StudentId, PhoneOrder, Phone)
Select StudentId, 3, Phone3 from Student where Phone3 is not null;

So, 3 separate inserts using a constant as the value for the 2nd
column
...and the specific version of the phone column we want

Now let's whack those columns in Student that we no longer need

Alter table Student


drop column Phone1, Phone2, Phone3

Note: You can drop multiple columns at once!

Let's look at a Default column scenario...

Create table Kumquat (


KumquatID int not null,
FirstName nvarchar(50) not null,
Code int not null default 25,
constraint KumquatPK Primary Key(KumquatID)
)

/* Just ignore the Code column during an insert */


insert into Kumquat
(KumquatID, FirstName)
values
(1, 'Bob'),
(2, 'Sally')
/* Specify a Default during an insert */
Insert into Kumquat
(KumquatID, FirstName, Code)
values
(3, 'john', 42),
(4, 'Mary', default)
--,(5, 'Sue', NULL) -- That won't work because the column is "NOT
NULL"

Update, p349
Update Student Set Major=10
Where StudentID = 1

Carefull... I'd suggest that you do a "dry run" with a Select statement
first
what happens if you don't have a "where" clause?

Multiple items
column / value pairs
separate by commas

Update Student Set LastName='Jones', Major=30


Where StudentID = 1

Bulk update with nested SQL


* example, p350

Merge, p350
skip...

Delete, p351
Delete from Student
where StudentID=1

What did I say about a practical guide for deleting rows?

Let's alter the Student table to make that happen now

Alter Table Student


add Active bit null

Let's assume that everyone is active, so let's fix that...

Update Student
set Active=1

1) Notice that there is no where clause (that's pretty rare)


2) The "boolean" data type in SQL Server is called "bit"
...and has values of either 0 or 1

So, now instead of deleting a record... you just change the Active to 0
Update Student
set Active=0
where StudentID=1

BTW: You'll need to know this for Term Project

------------------------------ break -----------------------------------


Views, p352
Review of "Data vs. Information"

persistent SQL queries (typically produce table/col output)


treat a view "as a" table

Used as a method of "abstraction"


* fig 7-16, 352
Why is that important (or desirable?)

Select * from Last12MonData

So, data is in this "Last 12 month data" table?


1 years worth of data
new data added each month
old data removed each month

Create a "view" that returns the data


alter the view every month
Why do this? Is there a better way?

During transition, I can rename tables, and use views (with the old
names)
until everything has been ported over.

Use of SQL Views


* fig 7-17, p355
oooh, good stuff here... hint, hint, hint

Applications typically don't have full SQL statements in them, they


just use Views (and Stored Procedures) instead.

Example... Hide SSN column

Create View StudentInfo as


Select Student.StudentID, FirstName, LastName, MajorName, PhoneOrder,
Phone
From Student Join Phone on Student.StudentID = Phone.StudentID
Join Major on Major.MajorID = Student.MajorID

So, that's an example of using 2 joins!!!

So, how do you "run a view"?


Select * from StudentInfo

1) So, just "as if" it was a table

No real edit capability... so Alter just "starts over"

Update via Views, 361


tricky subject...
if columns have not been altered/computed
all non-null fields are "in view"
no joins

One oddity in MSSQL Server views


no order by clause!
It's a long story... but it complained about a lot!
"Top (99.99999) Percent" is a (horrible) work around...
but don't rely on this behavior
does that sound like a test question to you?

You'll need to know how to create views for the Term Project
Skip a bit...

Programming... 362
I'll keep this to a minimum...

Functions, p364
Sometimes called a "User Defined Function" (UDF)
3 types... scalar, inline table-valued, multi-statement table-valued
so what's a scalar?
what's the difference between a "scalar" and "vector aggregate"?
A scalar used with group by is called a aggregate

Just like a view but allows for sending a parmeter/returning a value

CREATE FUNCTION GetStudentByID (@ID INT)


RETURNS TABLE
AS
RETURN
Select StudentID, FirstName, LastName, MajorName
From Student Join Major on Major.MajorID = Student.MajorID
Where StudentID=@ID

Then use it like:


Select * from GetStudentByID(2)

So, wait... what's the difference between a view and a function?

1) Notice that a "table function" is used via the Select clause just like a
table

Let's do one with a scalar...

Create Function GetNumPhones(@ID int)


Returns int
As
Begin
declare @answer as int;
selelct @answer = count(PhoneNumber) from Phone where StudentID=@ID;
return @answer;
End

1) One of the few places where the semicolons are required


2) Declaring variable... with type
3) Using the select statement to store a value in a variable

Note: You'll need to use this in your Term Project!

How can it be used?


"as a" column in a select statement

Select StudentID, FirstName, LastName, dbo.GetNumPhones(StudentID) from


Student
Triggers, p367
I want something to happen under a particular set of circumstances
So, what are they for?

Types:
before (not MS SQL)
after
instead of

Use:
defaults values
data contraints
business rules
discount based upon size of order
must have exactly 4 items...
update views
RI
that can't be done normally
Delete the department row when no more employees assigned???

Stored Procedures, p373


Small program written in a PSM language (often very tied to vendor)
So, what are they for?

Oddity: MS SQL Server allows .Net languages

Use:
Surgical application of security
you don't have write permission on a table,
but you have execute permission on SP!
Very common!!!!
Optimization
this used to be a big advantage... not so much now
Hiding complexity
Application programming
all business logic in one place (not distributed between code and
DB)

Triggers vs SP
* fig 7-30, 375

Advantages of SP
* fig 7-31, 375

So, which permission will prevail?


Table permissions?
or
Stored procedure permisions?

Comparison, p376
Functions, triggers, SPs
* fig 7-33
hint, hint...

You might also like