SQL DDL and DML
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-1
© 2006 Pearson Prentice Hall
Constraints
• Constraints can be defined within the CREATE
TABLE statement, or they can be added to the
table after it is created using the ALTER table
statement
• Five types of constraints:
– PRIMARY KEY may not have null values
– UNIQUE may have null values
– NULL/NOT NULL
– FOREIGN KEY
– CHECK
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-2
© 2006 Pearson Prentice Hall
Creating Relationships
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-3
© 2006 Pearson Prentice Hall
SQL for Constraints
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-4
© 2006 Pearson Prentice Hall
ALTER Statement
• ALTER statement changes table structure,
properties, or constraints after it has been
created
• Example:
ALTER TABLE ASSIGNMENT
ADD CONSTRAINT EmployeeFK FOREIGN KEY (EmployeeNum)
REFERENCES EMPLOYEE (EmployeeNumber)
ON UPDATE CASCADE
ON DELETE NO ACTION;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-5
© 2006 Pearson Prentice Hall
Adding and Dropping Columns
• The following statement will add a column
named MyColumn to the CUSTOMER
table:
ALTER TABLE CUSTOMER ADD MyColumn Char(5) NULL;
• You can drop an existing column with the
statement:
ALTER TABLE CUSTOMER DROP COLUMN MyColumn;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-6
© 2006 Pearson Prentice Hall
Adding and Dropping Constraints
• ALTER can be used to add a constraint as
follows:
ALTER TABLE CUSTOMER ADD CONSTRAINT MyConstraint CHECK
([Name] NOT IN ('Robert No Pay'));
• ALTER can be used to drop a constraint:
ALTER TABLE CUSTOMER DROP CONSTRAINT MyConstraint;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-7
© 2006 Pearson Prentice Hall
Removing Tables
• SQL DROP TABLE:
DROP TABLE [TRANSACTION];
• If there are constraints:
ALTER TABLE CUSTOMER_ARTIST_INT
DROP CONSTRAINT Customer_Artist_Int_CustomerFK;
ALTER TABLE [TRANSACTION]
DROP CONSTRAINT TransactionCustomerFK;
DROP TABLE CUSTOMER;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-8
© 2006 Pearson Prentice Hall
SQL DML - INSERT
• INSERT command:
INSERT INTO ARTIST ([Name], Nationality, Birthdate,
DeceasedDate)
VALUES ('Tamayo', 'Mexican', 1927, 1998);
• Bulk INSERT:
INSERT INTO ARTIST ([Name], Nationality, Birthdate)
SELECT [Name], Nationality, Birthdate
FROM IMPORTED_ARTIST;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-9
© 2006 Pearson Prentice Hall
SQL DML: UPDATE
• UPDATE command:
UPDATE CUSTOMER
SET City = 'New York City'
WHERE CustomerID = 1000;
• Bulk UPDATE:
UPDATE CUSTOMER
SET AreaCode = '333'
WHERE City = 'Denver';
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-10
© 2006 Pearson Prentice Hall
SQL DML: DELETE
• DELETE command:
DELETE FROM CUSTOMER
WHERE CustomerID = 1000;
• If you omit the WHERE clause, you will
delete every row in the table!
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition 7-11
© 2006 Pearson Prentice Hall