Вы находитесь на странице: 1из 37

1.

8 Database and data modelling

1.8.3 Data Definition Language (DDL)


and Data Manipulation Language
(DML)
1.8.3.1 Data Definition Language
• write simple SQL commands using a sub-set of commands for:

○ creating a database
○ creating a table definition
○ changing a table definition
○ adding a primary key or foreign key to a table
All of the above using the SQL sub-set:
– CREATE DATABASE, CREATE TABLE
– ADD PRIMARY KEY
1.8.3.1 Data Definition Language
1. CREATING TABLE

CREATE TABLE LECTURERS


( LECTURER_ID TEXT(4),
LECTURER_NAME TEXT(50),
SUBJECT_ID TEXT(4),
CONTACTNO TEXT(12));
1.8.3.1 Data Definition Language
2. CREATING TABLE WITH PRIMARY KEY

CREATE TABLE SUBJECTS


( SUBJECT_ID TEXT(4),
TITLE TEXT(50),
LEVEL TEXT(2),
NO_OF_ASSIGNMENT INT,
PRIMARY KEY (SUBJECT_ID) );
1.8.3.1 Data Definition Language
3. SETTING PRIMARY KEY WITH ALTER TABLE

ALTER TABLE LECTURERS


ADD PRIMARY KEY (LECTURER_ID)

ALTER TABLE LECTURERS


ADD FEE SINGLE ;

ALTER TABLE LECTURERS


DROP FEE ;
Microsoft Access Data Types
Data type Description Storage
Text Use for text or combinations of text and numbers. 255 characters
maximum
Memo Memo is used for larger amounts of text. Stores up to 65,536
characters. Note: You cannot sort a memo field. However, they are
searchable
Byte Allows whole numbers from 0 to 255 1 byte
Integer Allows whole numbers between -32,768 and 32,767 2 bytes
Long Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
Single Single precision floating-point. Will handle most decimals 4 bytes
Double Double precision floating-point. Will handle most decimals 8 bytes
Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 8 bytes
decimal places. Tip: You can choose which country's currency to use
AutoNumber AutoNumber fields automatically give each record its own number, 4 bytes
usually starting at 1
Date/Time Use for dates and times 8 bytes
Yes/No A logical field can be displayed as Yes/No, True/False, or On/Off. In 1 bit
code, use the constants True and False (equivalent to -1 and
0). Note: Null values are not allowed in Yes/No fields
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large up to 1GB
OBjects)
1.8.3.1 Data Definition Language
4. SETTING FOREIGN KEY
(i) when table is declared

CREATE TABLE LECTURERS1


( LECTURER_ID TEXT(4),
LECTURER_NAME TEXT(50),
SUBJECT_ID TEXT(4),
CONTACTNO TEXT(12),
FOREIGN KEY (SUBJECT_ID)
REFERENCES SUBJECTS(SUBJECT_ID));
1.8.3.1 Data Definition Language
(ii) using alter table

ALTER TABLE LECTURERS


ADD FOREIGN KEY (SUBJECT_ID)
REFERENCES SUBJECTS(SUBJECT_ID)
1.8.3.1 Data Definition Language
(iii). DROP/REMOVE a FOREIGN KEY Constraint

• ALTER TABLE LECTURERS


• DROP CONSTRAINT FK_SUBJECT_ID ;
CREATE TABLE products
( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);

CREATE TABLE inventory


( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
);

ALTER TABLE inventory


DROP CONSTRAINT fk_inv_product_id;
Class Activity
Create the following table, set the primary and foreign keys

Customers Table Orders Table Order_Product Table


Customer_ID OrderID Order_ID
CustomerName CustomerID Product_ID
Address OrderAmount 1 order
City - 3 to 4 products
OrderDate
PostalCode
1 customer
Country - 3 to 4 orders Product Table

10 customer records ProductID


Supplier Table ProductDescription
SupplierID SupplierID
SupplierName SellingPrice
ContactNo CostPrice
Address UnitsPerPack
5 supplier records 10 product records
1.8.3.2 Data Manipulation Language
• interpret a given SQL script
• write a SQL script for querying or modifying data which are
stored in (at most two) database tables
• All of the above using the SQL sub-set:
Queries:
○ SELECT, FROM, WHERE, ORDER BY, GROUP BY, INNER JOIN
Data maintenance:
○ INSERT INTO
○ DELETE FROM
○ UPDATE
1.8.3.2 Data Manipulation Language

1. SQL SELECT Syntax, to indicate the fields to be displayed


SELECT column_name,column_name
FROM table_name;

Example

SELECT CustomerName,City
FROM Customers;
1.8.3.2 Data Manipulation Language
2. SELECT *, means to list every field in the table

Example

SELECT *
FROM Customers;
1.8.3.2 Data Manipulation Language
3. SQL WHERE Clause

SQL WHERE Syntax

SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

Example

SELECT *
FROM Customers
WHERE Country='Mexico';
1.8.3.2 Data Manipulation Language
3.1 Selecting data based on date data type.

Example : Write a query to list all orders placed after January 2017.

SELECT *
FROM orders
WHERE order_date >#02/01/2017#;

Question : Write a query to list all orders placed in the month of February
2017.
Answer

SELECT *
FROM orders
WHERE order_date >=#02/01/2017# AND ORDER_DATE <=#02/28/2017#;
1.8.3.2 Data Manipulation Language
3.2 Selecting data based on numeric data type.

Example : Write a query to list all orders with amounts more than $100.

SELECT *
FROM orders
WHERE order_amount >=100

Question : Write a query to list all products with a packing units of more
than 5.
Answer

SELECT *
from product
where units_per_pack >=5
1.8.3.2 Data Manipulation Language
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:

Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be
written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
1.8.3.2 Data Manipulation Language
4. SQL ORDER BY Keyword
SQL ORDER BY Syntax
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;

Example 1
SELECT *
FROM Customers
ORDER BY Country;

Example 2
SELECT *
FROM Customers
ORDER BY Country DESC;

Example 3
SELECT *
FROM Customers
ORDER BY Country ASC, Customer_Name DESC;
1.8.3.2 Data Manipulation Language
Selecting data from more than one table : INNER JOIN
1.8.3.2 Data Manipulation Language
5. SQL INNER JOIN Keyword
The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are rows in the "Customers" table that do not have matches
in "Orders", these customers will NOT be listed.
1.8.3.2 Data Manipulation Language
Question : Write a query to list all orders placed by customers, sorted in
ascending order of customer name.
SELECT Customers.Customer_Name, Orders.Order_ID
FROM Customers
INNER JOIN Orders
ON Customers.Customer_ID=Orders.Customer_ID
ORDER BY Customers.Customer_Name;
1.8.3.2 Data Manipulation Language
Question : Write a query to list all orders placed by customer 0001.
SELECT *
from customers
inner join orders
on customers.customer_ID =
ORDERS.CUSTOMER_ID
WHERE customers.customer_ID="0001" ;
1.8.3.2 Data Manipulation Language
Question : Write a query to list all products supplied by supplier 0001.

SELECT *
from SUPPLIER
inner join PRODUCT
on SUPPLIER.SUPPLIER_ID =
PRODUCT.SUPPLIER_ID
WHERE SUPPLIER.SUPPLIER_ID="0001" ;
1.8.3.2 Data Manipulation Language

Question : Write a query to list the product id and product description


bought by customer 0001
1.8.3.2 Data Manipulation Language

3. SELECT ORDERS.ORDER_ID, ORDER_PRODUCT.PRODUCT_ID,


CUSTOMERS.CUSTOMER_ID, PRODUCT.PRODUCT_DESCRIPTION
from (((ORDER_PRODUCT
inner join orders
on ORDER_PRODUCT.ORDER_ID = ORDERS.ORDER_ID)
INNER JOIN CUSTOMERS
ON CUSTOMERS.CUSTOMER_ID = ORDERS.ORDER_ID)
INNER JOIN PRODUCT
ON ORDER_PRODUCT.PRODUCT_ID = PRODUCT.PRODUCT_ID)
WHERE CUSTOMERS.CUSTOMER_ID="0001";
1.8.3.2 Data Manipulation Language
6. SQL GROUP BY Statement
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
Example
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;
Example
SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;
1.8.3.2 Data Manipulation Language

Example : Write a query to list the number of orders placed by each customer.

Example
SELECT customer_id, count(orders.order_id) as TotalNUmberoforders
from orders
group by customer_id;

Question : Write a query to list the number of orders for each product.
Answer

SELECT product_id, count(order_product.order_id) as TotalNUmberoforders


from order_product
group by product_id;
1.8.3.2 Data Manipulation Language
7. SQL INSERT INTO Syntax
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only
their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
Example

INSERT INTO Customers (Customer_ID, Customer_Name, Address, City, Postal_Code, Country)


VALUES ("0012","Nile","No. 51, Kiara Hills","Kuala Lumpur","50480","Malaysia");

Question : Write a query to enter two additional product information into the product table.
1.8.3.2 Data Manipulation Language
8. SQL DELETE Statement
The DELETE statement is used to delete records in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value;
Notice the WHERE clause in the SQL DELETE statement!
The WHERE clause specifies which record or records that should be deleted.
If you omit the WHERE clause, all records will be deleted!
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';
Delete All Data
It is possible to delete all rows in a table without deleting the table. This means that the
table structure, attributes, and indexes will be intact:
DELETE FROM table_name;
or
DELETE * FROM table_name;
Note: Be very careful when deleting records. You cannot undo this statement!
Example

DELETE FROM Customers


WHERE Customer_ID=‘0008’;
1.8.3.2 Data Manipulation Language
9. SQL UPDATE Statement
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

Notice the WHERE clause in the SQL UPDATE statement!


The WHERE clause specifies which record or records that should be updated. If you
omit the WHERE clause, all records will be updated!

Example
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
1.8.3.2 Data Manipulation Language
Past Year Question ( Topical Past Year 1.8)

1. Page 17 Question (c)

2. Page 20 Question (c)

3. Page 23 Question (d), (e), (f)

4. Page 26 Question (c), (d), (e)

5. Page 32 Question (f)

6. Page 35 Question (f)

7. Page 36 Question (d)

8. Page 39 Question (d)

Вам также может понравиться