49
loading...
This website collects cookies to deliver better user experience
CREATE DATABASE
statement we can do just that. Interacting with the database is as simple as using the USE DATABASE
statement followed by any other statements you’d like.CREATE TABLE
statement allows us to create a table with a given name. There are many aspects to the CREATE TABLE
statement described under the following topics: table name, temporary tables, table cloning and copying, column data types and attributes, indexes/foreign keys/check constraints, table options, and table partitioning. Let’s put this into practice and create a database with tables:CREATE DATABASE MaxOverflowExample;
USE MaxOverflowExample;
CREATE TABLE Customer (
CustNo CHAR(8),
CustFirstName VARCHAR(20) NOT NULL,
CustLastName VARCHAR(30) NOT NULL,
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(10),
CustBal DECIMAL(12,2),
CONSTRAINT PKCustomer PRIMARY KEY (CustNo)
);
CREATE TABLE Employee(
EmpNo CHAR(8),
EmpFirstName VARCHAR(20) NOT NULL,
EmpLastName VARCHAR(30) NOT NULL,
EmpPhone CHAR(15),
EmpEMail VARCHAR(50) NOT NULL,
CONSTRAINT PKEmployee PRIMARY KEY (EmpNo),
CONSTRAINT UniqueEMail UNIQUE (EmpEMail)
);
CREATE TABLE OrderTbl (
OrdNo CHAR(8),
OrdDate DATE NOT NULL,
CustNo CHAR(8) NOT NULL,
EmpNo CHAR(8),
CONSTRAINT PKOrderTbl PRIMARY KEY (OrdNo) ,
CONSTRAINT FKCustNo FOREIGN KEY (CustNo) REFERENCES Customer (CustNo),
CONSTRAINT FKEmpNo FOREIGN KEY (EmpNo) REFERENCES Employee (EmpNo)
);
INSERT INTO
statement. When we use an INSERT
statement, we have to match up our data to conform to the data types and constraints we defined in our CREATE TABLE
statement.USE MaxOverflowExample;
INSERT INTO Customer
(CustNo, CustFirstName, CustLastName, CustCity, CustState, CustZip, CustBal)
VALUES('C0954327','Sheri','Gordon','Littleton','CO','80129-5543',230.00);
INSERT INTO Employee
(EmpNo, EmpFirstName, EmpLastName, EmpPhone, EmpEMail)
VALUES ('E8544399','Joe','Jenkins','(303) 221-9875','[email protected]');
INSERT INTO OrderTbl
(OrdNo, OrdDate, CustNo, EmpNo)
VALUES ('O9919699','2017-02-11','C0954327','E8544399');
SELECT
statement. SELECT
queries can become quite complex when dealing with a production level database. Here, I demonstrate how you can get all the data from all three tables we created.USE MaxOverflowExample;
SELECT * FROM Customer;
SELECT * FROM Employee;
SELECT * FROM Ordertbl;
UPDATE
and DELETE
statements. All that’s needed is to specify the primary key of the row we’d like to either update or delete.UPDATE
and DELETE
statements that don’t include WHERE clauses that reference the primary key column(s). This saves you from affecting every row in the given table.USE MaxOverflowExample;
-- Update customer first name
UPDATE Customer
SET CustFirstName = 'George'
WHERE CustNo = 'C0954327';
-- Delete rows added
DELETE FROM OrderTbl
WHERE OrdNo = 'O9919699';
DELETE FROM Employee
WHERE EmpNo = 'E8544399';
DELETE FROM Customer
WHERE CustNo = 'C0954327';