SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity...

30
SQL Workshop Creation and Maintenance Doug Shook

Transcript of SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity...

Page 1: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

SQL Workshop

Creation and Maintenance

Doug Shook

Page 2: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

2

Data Definition Language (DDL) Used to create, modify, and delete DB objects

– Typically performed by a DBA– Also useful during testing

Can be created through tools (like Management Studio)

Page 3: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

3

Object Names Formatting rules

– First character must be a letter, underscore, or number sign

– All characters after the first must be letters– Keywords cannot be used for identifiers– No spaces or special characters

• Varies by platform

First character(s)– @ -> local variable– # -> temporary table or procedure– ## -> Global temp object

Page 4: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

4

Object NamesValid regular identifiers

Employees

#PaidInvoices

ABC$123

Invoice_Line_Items

@TotalDue

Valid delimited identifiers [%Increase]

"Invoice Line Items"

[@TotalDue]

Page 5: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

5

CREATE DATABASE Used to create an empty database

– Supported on all systems• But implemented differently...

Creates a transaction log file– Can be used to transfer databases

Can also be used to create a copy– FOR ATTACH

Page 6: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

6

CREATE DATABASEBasic syntax of the CREATE DATABASE statement

CREATE DATABASE database_name [ON [PRIMARY] (FILENAME = 'file_name')] [FOR ATTACH]

Create a new database CREATE DATABASE New_AP;

The response from the system Command(s) completed successfully.

Attach an existing database file CREATE DATABASE Test_AP ON PRIMARY (FILENAME = 'C:\Murach\SQL Server 2012\Databases\Test_AP.mdf') FOR ATTACH;

The response from the system Command(s) completed successfully.

Page 7: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

7

CREATE TABLE Contains column definitions

– Column name– Data type– Attributes

• NULL | NOT NULL• PRIMARY KEY | UNIQUE• IDENTITY• DEFAULT• SPARSE

Page 8: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

8

CREATE TABLECreate a table without column attributes

CREATE TABLE Vendors (VendorID INT, VendorName VARCHAR(50));

Create a table with column attributes CREATE TABLE Invoices (InvoiceID INT PRIMARY KEY IDENTITY, VendorID INT NOT NULL, InvoiceDate SMALLDATETIME NULL, InvoiceTotal MONEY NULL DEFAULT 0);

A column definition that uses the SPARSE attribute

VendorAddress2 VARCHAR(50) SPARSE NULL

Page 9: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

9

CREATE INDEX Recall the properties of indexes

– Clustered vs. Nonclustered

Additional properties to consider– Full table– Filtered– Ascending vs. Descending

Page 10: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

10

CREATE INDEXBasic syntax of the CREATE INDEX statement

CREATE [CLUSTERED|NONCLUSTERED] INDEX index_name ON table_name (col_name_1 [ASC|DESC] [, col_name_2 [ASC|DESC]]...) [WHERE filter-condition]

Create a nonclustered index on a single column CREATE INDEX IX_VendorID ON Invoices (VendorID);

Create a nonclustered index on two columns CREATE INDEX IX_Invoices ON Invoices (InvoiceDate DESC, InvoiceTotal);

Note SQL Server automatically creates a clustered index for a table’s

primary key.

Page 11: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

11

CREATE INDEXCreate a filtered index for a subset of data in a column

CREATE INDEX IX_InvoicesPaymentFilter ON Invoices (InvoiceDate DESC, InvoiceTotal) WHERE PaymentDate IS NULL;

Create a filtered index for categories in a column CREATE INDEX IX_InvoicesDateFilter ON Invoices (InvoiceDate DESC, InvoiceTotal) WHERE InvoiceDate > '2012-02-01';

Page 12: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

12

Constraints Used to enforce referential integrity

Column-level constraints Constraint Description NOT NULL Prevents null values from being stored in the

column. PRIMARY KEY Requires that each row in the table have a

unique value in the column. Null values are not allowed.

UNIQUE Requires that each row in the table have a unique value in the column.

CHECK Limits the values for a column. [FOREIGN KEY] Enforces referential integrity between a column REFERENCES in the new table and a column in a related table.

Page 13: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

13

ConstraintsTable-level constraints Constraint Description PRIMARY KEY Requires that each row in the table have a unique

set of values over one or more columns. Null values are not allowed.

UNIQUE Requires that each row in the table have a unique set of values over one or more columns.

CHECK Limits the values for one or more columns. [FOREIGN KEY] Enforces referential integrity between one or more REFERENCES columns in the new table and one or more columns in the related table.

Page 14: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

14

ConstraintsCreate a table with a two-column primary key constraint

CREATE TABLE InvoiceLineItems1 (InvoiceID INT NOT NULL, InvoiceSequence SMALLINT NOT NULL, InvoiceLineItemAmount MONEY NOT NULL, PRIMARY KEY (InvoiceID, InvoiceSequence));

Page 15: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

15

ConstraintsCreate a table with two column-level check constraints

CREATE TABLE Invoices1 (InvoiceID INT NOT NULL IDENTITY PRIMARY KEY, InvoiceTotal MONEY NOT NULL CHECK (InvoiceTotal >= 0), PaymentTotal MONEY NOT NULL DEFAULT 0 CHECK (PaymentTotal >= 0));

The same check constraints coded at the table level

CREATE TABLE Invoices2 (InvoiceID INT NOT NULL IDENTITY PRIMARY KEY, InvoiceTotal MONEY NOT NULL, PaymentTotal MONEY NOT NULL DEFAULT 0, CHECK ((InvoiceTotal >= 0) AND (PaymentTotal >= 0)));

Page 16: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

16

Foreign Key Constraints Used to define the relationship between two tables

Column level foreign keys can only link two columns– Table level can include multiple columns per table

Must specify what to do upon DELETE or UPDATE– CASCADE propagates the updates to other tables– NO ACTION does nothing

• Typically preferred• Default option

Page 17: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

17

Foreign Key ConstraintsA column-level foreign key constraint

A statement that creates the primary key table CREATE TABLE Vendors9 (VendorID INT NOT NULL PRIMARY KEY, VendorName VARCHAR(50) NOT NULL);

A statement that creates the foreign key table CREATE TABLE Invoices9 (InvoiceID INT NOT NULL PRIMARY KEY, VendorID INT NOT NULL REFERENCES Vendors9 (VendorID), InvoiceTotal MONEY NULL);

Page 18: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

18

Foreign Key ConstraintsA column-level foreign key constraint (continued)

An INSERT statement that fails because a related row doesn’t exist INSERT Invoices9 VALUES (1, 99, 100);

The response from the system The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Invoices9__Vendo__1367E606". The conflict occurred in database "New_AP", table "dbo.Vendors9", column 'VendorID'. The statement has been terminated.

Page 19: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

19

DROP Used in conjunction with INDEX, TABLE, or DATABASE

– Tables can only be deleted if there are no foreign key constraints

– Deleting a table deletes the data, indexes, triggers and constraints• Views and procedures must be deleted separately

– Delete operations have no undo

Page 20: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

20

ALTER TABLE Used to add or removed columns or constraints

– Also used to modify existing columns

SQL Server will not perform the ALTER if data will be lost

– How might this data loss occur?

Page 21: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

21

ALTER TABLEAdd a new column

ALTER TABLE Vendors ADD LastTranDate SMALLDATETIME NULL;

Drop a column ALTER TABLE Vendors DROP COLUMN LastTranDate;

Add a new check constraint ALTER TABLE Invoices WITH NOCHECK ADD CHECK (InvoiceTotal >= 1);

Add a foreign key constraint ALTER TABLE InvoiceLineItems WITH CHECK ADD FOREIGN KEY (AccountNo) REFERENCES GLAccounts(AccountNo);

Change the data type of a column ALTER TABLE InvoiceLineItems ALTER COLUMN InvoiceLineItemDescription VARCHAR(200);

Page 22: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

22

Sequences New to SQL Server 2012

– Automatically generates a sequence of integers– Can specify starting value and increment– Can specify minimum and maximum values

Page 23: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

23

SequencesCreate a sequence that starts with 1

CREATE SEQUENCE TestSequence1 START WITH 1;

Specify a starting value and an increment CREATE SEQUENCE TestSequence2 START WITH 10 INCREMENT BY 10;

Specify all optional parameters CREATE SEQUENCE TestSequence3 AS int START WITH 100 INCREMENT BY 10 MINVALUE 0 MAXVALUE 1000000 CYCLE CACHE 10;

Page 24: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

24

SequencesCreate a table with a sequence column CREATE TABLE SequenceTable( SequenceNo INT, Description VARCHAR(50));

Insert the next value for a sequence INSERT INTO SequenceTable VALUES (NEXT VALUE FOR TestSequence3, 'First inserted row') INSERT INTO SequenceTable VALUES (NEXT VALUE FOR TestSequence3, 'Second inserted row');

Get the current value of the sequence SELECT current_value FROM sys.sequences WHERE name = 'TestSequence3';

Page 25: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

25

SequencesThe syntax of the DROP SEQUENCE statement

DROP SEQUENCE sequence_name1[, sequence_name2]...

A statement that drops a sequence DROP SEQUENCE TestSequence2;

The syntax of the ALTER SEQUENCE statement ALTER SEQUENCE sequence_name [RESTART [WITH starting_integer]] [INCREMENT BY increment_integer] [{MINVALUE minimum_integer | NO MINVALUE}] [{MAXVALUE maximum_integer | NO MAXVALUE}] [{CYCLE|NOCYCLE}] [{CACHE cache_size|NOCACHE}]

A statement that alters a sequence ALTER SEQUENCE TestSequence1 INCREMENT BY 9 MINVALUE 1 MAXVALUE 999999 CACHE 9 CYCLE;

Page 26: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

26

Scripts Any SQL statements can be put into a script

DDL scripts are particularly useful– Tweaking DB design– Restarting a faulty database– Copying a structure that is known to work

Unlike traditional programming, not executed line by line

– Execution is split into batches– Batches are separated with GO statements

Let’s look at the AP database script

Page 27: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

27

Exercises Create a new database named Membership

Write the CREATE TABLE statements needed to implement the following design in the Membership database. Decide which columns should allow null values and explain your decision. Define the dues column with a default of zero and a check constraint to only allow positive values.

Page 28: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

28

Exercises Write CREATE INDEX statements to create indexes on the GroupID column and the IndividualID column of the GroupMembership table.

Write an ALTER TABLE statement that adds a new column, DuesPaid, to the Individuals table. Use the int data type, disallow null values, and assign a default value of 0.

Page 29: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

29

Exercises Write an ALTER TABLE statement that adds two new check constraints to the Invoices table of the AP database. The first should allow (1) PaymentDate to be null only if PaymentTotal is zero and (2) PaymentDate to be not null only if PaymentTotal is greater than zero. The second constraint should prevent the sum of PaymentTotal and CreditTotal from being greater than InvoiceTotal.

Page 30: SQL Workshopdshook/sqlworkshop/Slides/p8.pdfConstraints Used to enforce referential integrity Column-level constraints Constraint Description NOT NULL Prevents null values from being

30

Exercises Delete the GroupMembership table from the Membership database. Then, write a CREATE TABLE statement that recreates the table, this time with a unique constraint that prevents an individual from being a member in the same group twice.