Insert data
INSERT
Insert complete line
INSERT INTO Customers
VALUES('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA',
NULL,
NULL);
One to one attribute
INSERT INTO Customers(cust_id,
cust_name,
cust_city,
cust_address,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
VALUES('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA',
NULL,
NULL);
Insert part of the line
INSERT INTO Customers(cust_id,
cust_name,
cust_city,
cust_address,
cust_state,
cust_zip,
cust_country)
VALUES('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA');
Attribute allows part is NULL, the default value is given, or
Insertion of data retrieved
INSERT SELECT
Statement
INSERT INTO Customers(.....)
SELECT ..... FROM CustNew;
Copied from one table into another
CREATE TABLE CustCopy AS
SELECT * FROM Customers;
Update and delete data
UPDATE
UPDATE Customers
SET cust_contact = 'Sam Roberts',
cust_email = '[email protected]'
WHERE cust_id = '1000000006';
DELETE
DELETE FROM Customers
WHERE cust_id = '1000000006';
If UPDATE
and DELETE
without WHERE
words is to change / delete each row
Create and manipulate tables
CREATE
CREATE TABLE Orders
(
order_num INTEGER NOT NULL,
order_date DATETIME NOT NULL,
cust_id CHAR(10) NOT NULL
);
Specify a default value
Followed by theDEFAULT
CREATE TABLE OrderItems
(
order_num INTEGER NOT NULL,
order_item INTEGER NOT NULL,
prod_id CHAR(10) NOT NULL,
quantity INTEGER NOT NULL DEFAULT 1,
item_price DECIMAL(8, 2) NOT NULL
);
ALTER
Increase Column
ALTER TABLE Vendors
ADD vend_phone CHAR(20);
Remove Columns
ALTER TABLE Vendors
DROP COLUMN vend_phone;
Delete table
DROP TABLE CustCopy;
Using Views
VIEW
Create a view
CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id
FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND OrderItems.order_num = Orders.order_num;
Stored Procedures
All the encapsulation process, simplify operation
Affairs
cursor
Advanced SQL Features
constraint
Primary key
Uniquely identifies
CREATE TABLE Orders
(
order_num INTEGER NOT NULL, PRIMARY KEY,
order_date DATETIME NOT NULL,
cust_id CHAR(10) NOT NULL
);
Or create a table and then add
ALTER TABLE Orders
ADD CONSTRAINT PRIMARY KEY (order_num);
Foreign key
CREATE TABLE Orders
(
order_num INTEGER NOT NULL, PRIMARY KEY,
order_date DATETIME NOT NULL,
cust_id CHAR(10) NOT NULL , REFERENCES Customers(cust_id)
);
or
ALTER TABLE Orders
ADD CONSTRAINT
FOREIGN KEY (cust_id) REFERENCES Customers (cust_id);
Check constraints
CREATE TABLE OrderItems
(
order_num INTEGER NOT NULL,
order_item INTEGER NOT NULL,
prod_id CHAR(10) NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
item_price DECIMAL(8, 2) NOT NULL
);
or
ADD CONSTRAINT CHECK (gender LIKE '[MF]');