relational dbs and sql designing your web database (ch. 8)

28
Relational DBs and SQL Designing Your Web Database (Ch. 8) Creating and Working with a MySQL Database (Ch. 9, 10) 1

Upload: nerita

Post on 04-Feb-2016

49 views

Category:

Documents


0 download

DESCRIPTION

Relational DBs and SQL Designing Your Web Database (Ch. 8) Creating and Working with a MySQL Database (Ch. 9, 10). DML – Adding Table Rows. SQL requires the use of the INSERT command to enter data into a table. INSERT command’s basic syntax: INSERT INTO tablename - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Relational DBs and SQL

Designing Your Web Database (Ch. 8)→Creating and Working with a MySQL Database (Ch. 9, 10)

1

Page 2: Relational DBs and SQL Designing Your Web Database (Ch. 8)

SQL requires the use of the INSERT command to enter data into a table.

INSERT command’s basic syntax:

INSERT INTO tablename

VALUES (value_1, value_2, … , value_n);

This version of INSERT: adds one table row (tuple) at a time requires a value to be specified for every column of the table; values

are specified in the same order columns were defined in

DML – Adding Table Rows

2

Page 3: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Example:insert into customers values (1, "Julie Smith", "25 Oak Street", "Airport West");

insert into orders values (NULL, 1, 49.99, "2007-04-15");

Notes:The row contents are delimited by parenthesesAttribute entries are separated by commasString and date values must be quoted (‘ or “)Numerical entries are not enclosed in any special charactersUse NULL for: unknown values for columns that aren’t NOT NULL; auto-increment columns (filled automatically if set to null or no value provided)

DML – Adding Table Rows (cont)

3

Page 4: Relational DBs and SQL Designing Your Web Database (Ch. 8)

If you want to fill in only some of the columns or if you want to specify them in a different order, list the specific columns in the INSERT statement:

insert into customers (name, city) values ("Alan Wong", "Box Hill");

Insert multiple rows into a table at once:Each row in its own set of parenthesesRows separated by commas

insert into customers values

(1, "Julie Smith", "25 Oak Street", "Airport West"),

(2, "Alan Wong", "1/47 Haines Avenue", "Box Hill");

DML – Adding Table Rows (cont)

4

Page 5: Relational DBs and SQL Designing Your Web Database (Ch. 8)

book_insert.sqlA script to populate the books database:http://www.nku.edu/~frank/csc301/Examples/MySQL/

book_insert.sql

Page 6: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Use the UPDATE command to modify data in a table.UPDATE command’s syntax:

UPDATE tablenameSET column_1 = expression_1 [, column_2 = expression_2 …][WHERE condition_list];

expression = a simple value (76 or ‘Florida’), or a formula (price – 10)condition_list = one or more conditional expressions connected by logical operators (and, or, not)

If more than one attribute is to be updated per tuple, separate modifications with commas

DML – Updating Table Rows

6

Page 7: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Examples:UPDATE booksSET price = price * 1.1; increase all the book prices by 10%

UPDATE customersSET address = ‘250 Olsens Road’WHERE customer_id = 4;update a certain customer’s address – PK used to identify the customer

Notes:The WHERE clause is optional If a WHERE clause is not specified, all rows from the specified table

will be modified.

DML – Updating Table Rows (cont)

7

Page 8: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Use the DELETE command to delete data from a table.

DELETE command’s syntax:

DELETE FROM tablename

[WHERE condition_list ];

Notes:WHERE clause is optionalIf a WHERE clause is not specified, all rows from the specified

table will be deleted

DML – Deleting Table Rows

8

Page 9: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Examples:

DELETE FROM customersWHERE customer_id = 4; delete data about a customer who didn’t place orders for a long time

DELETE FROM books WHERE price < 4;

delete all cheap books (none, one, or more tuples can satisfy the condition)

DELETE FROM books;delete all books; table is not deleted, but remains empty

DML – Deleting Table Rows (cont)

9

Page 10: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Most database use is issuing queries to retrieve data from the db.SELECT command is used to list the contents of a table (or more

tables).The simplest form (syntax) of a SELECT query is:

SELECT column_list

FROM tablename;

Column_list represents one or more attributes from tablename, separated by commas

Asterisk (*) can be used as a wildcard character to list all attributes for the selected rows (when column_list is *)

DML – Listing Table Rows

10

Page 11: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Example:

SELECT name, city FROM customers;

the result contains all the rows and only the two specified columns of table customers.

The results of a query are presented in table form:This behaves like a table (can be used in other queries for ex.),

but isn’t stored as one.

DML – Listing Table Rows (cont)

11

Page 12: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Can limit data selected by placing conditional restrictions on the rows to be included in the output → with the WHERE clause of the SELECT statement.

Syntax:SELECT column_listFROM tablename[ WHERE condition_list ] ;

Will retrieve all the rows that match the conditions specified in the optional WHERE clause

If no rows match the specified criteria result = an empty set of tuples (not an error!)

12

DML – Listing Table Rows (cont)

condition_list = one or more conditional expressions connected by logical operators

Page 13: Relational DBs and SQL Designing Your Web Database (Ch. 8)

WHERE clause example:

SELECT title FROM books WHERE price > 40; Conditional restrictions in the condition_list :

column_name comparison_operator valueexpression comparison_operator expressionexpression – with columns and values (constants) as operands;

Comparisons include the usual “suspects” =, !=, <, etc. Also can use BETWEEN value1 AND value2

If a data field is empty, can test with IS NULL operator SELECT name FROM customers WHERE address IS NULL;

Finds records with no address specified 13

DML – Listing Table Rows (cont)

Page 14: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Can match patterns with LIKEPattern can be simple characters up to RE% matches any number of characters, _ matches 1 character

Can match multiple conditions using AND and ORCan negate a condition using NOT

Example:

SELECT title

FROM books

WHERE price > 40 AND author like “Thomas%”;

14

DML – Listing Table Rows (cont)

Page 15: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Can sort results of query with ORDER BY:

SELECT column_listFROM tablename[ORDER BY column1 [ASC | DESC], column2 [ASC | DESC] …];

Notes:Although ORDER BY produces a sorted output, the actual table

contents are unaffected by the ORDER BY clause!ORDER BY clause must be listed last in SELECT (except for LIMIT)

Example:SELECT title, price, author FROM books ORDER BY price, author;

all books info sorted by price and, for same price, ordered by the author15

DML – Listing Table Rows (cont)

default

Page 16: Relational DBs and SQL Designing Your Web Database (Ch. 8)

The real power of a RDBMS resides in the ability to combine (join) tables – on common attributes.

A join is performed when data is retrieved from more than one table at a time.

Example: which customers placed orders this month? the customers and orders tables are used to determine the answer

16

DML – Joining DB Tables

Page 17: Relational DBs and SQL Designing Your Web Database (Ch. 8)

To create a natural join (= report only the pairs of rows in which the common attribute’s values match):the tables to be joined are enumerated in the FROM clause of the

SELECT command;join conditions are specified in the WHERE clause.

join condition = an equality comparison between the foreign key and the primary key of the two related tables.

If join conditions are not specified, the Cartesian product of all tables in the FROM clause is created = a row for each possible combination of rows from each of the tables listed in FROM 17

DML – Joining DB Tables (cont)

Page 18: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Example:

SELECT orders.orderid, orders.amount, orders.dateFROM customers, ordersWHERE customers.name = 'Julie Smith' AND

customers.customerid = orders.customerid;

source tables to be joined join condition

When same column name is defined in several of the joined tablesMust specify the source table of the column, in all SELECT clauses

that use it: tablename.columnnameOtherwise syntax error: ambiguous reference to an attribute.

18

DML – Joining DB Tables (cont)

Page 19: Relational DBs and SQL Designing Your Web Database (Ch. 8)

All of the SELECT SQL clauses can be applied on the joined tables.

When joining 3+ tables, join conditions needs to be specified for pairs of tables.

Generally, when N tables are listed in the SELECT clause, the number of join conditions is N-1.

Q: names of all customers who have placed at least one order that included a book about Java?

19

DML – Joining DB Tables (cont)

Page 20: Relational DBs and SQL Designing Your Web Database (Ch. 8)

An alias can be used to identify a source table in a SELECT command.

Aliases are alternative table names used to simplify commands.Any legal table name can be used as an alias.Syntax: FROM tablename AS alias, …An alias is valid only in the SELECT command that defines it!Example:

SELECT o.orderid, o.amount, o.dateFROM customers as c, orders as oWHERE c.name = 'Julie Smith' AND c.customerid = o.customerid;

20

DML – Joining DB Tables (cont)

Page 21: Relational DBs and SQL Designing Your Web Database (Ch. 8)

SELECT can be used to perform various summaries of the data, by using one of the aggregate functions:

– COUNT – the # of rows containing non-null values for a column

– MIN and MAX – the minimum, respectively maximum value encountered in a column

– SUM – the sum of all values for a column

– AVG – the arithmetic mean (average) of all values for a column

Syntax: SELECT aggregate_function ([DISTINCT] column)…

Example: SELECT max(price) FROM books;

21

DML – Grouping & Aggregating Data

Page 22: Relational DBs and SQL Designing Your Web Database (Ch. 8)

The aggregate functions yield only one value based on all of the values found in the table: a single maximum value, a single count, a single sum etc.

Aggregate functions can be used only in the column list of the SELECT command.

22

DML – Grouping & Aggregating Data

Page 23: Relational DBs and SQL Designing Your Web Database (Ch. 8)

To compute aggregate functions based on groups of values use the GROUP BY and HAVING clauses of the SELECT SQL command.

SELECT column_list

FROM table_list

[ WHERE condition_list ]

[GROUP BY g_column_list

[HAVING g_condition_list] ]

[ORDER BY column1 [ASC | DESC], …];

23

DML – Grouping & Aggregating Data

Page 24: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Example: how many books has each customer ordered?

SELECT c.name, sum(i.quantity) as nr_items

FROM customers as c, orders as o, order_items as i

WHERE c.customerid = o.customerid and o.orderid = i.orderid

GROUP BY c.customerid, c.name;

24

DML – Grouping & Aggregating Data

Page 25: Relational DBs and SQL Designing Your Web Database (Ch. 8)

The GROUP BY clause is used in combination with aggregate functions

How it works:The rows selected according to the SELECT, FROM and

WHERE clauses are divided into groups that have the same value for all columns in g_column_list.

For each group, only one row will be reported in the result columnlist of the SELECT clause may contain only columns

from g_column_list or aggregate functions applied on other columns one value per group for each of the expressions in the SELECT clause.

25

DML – Grouping & Aggregating Data

Page 26: Relational DBs and SQL Designing Your Web Database (Ch. 8)

The HAVING clause can be used only in combination with the GROUP BY clause: HAVING g_condition_list g_condition_list specifies qualification conditions for groups; Only for groups that verify g_condition_list, a row will be

included in the result. g_condition_list can contain only expressions that have a

unique value for a group = expressions formed with columns in from g_column_list or with aggregate functions applied on other columns.

NOTE: condition_list in the WHERE clause specifies qualification conditions for rows.

26

DML – Grouping & Aggregating Data

Page 27: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Example: how many books has each customer ordered; include only the customers that ordered 2 or more?

SELECT c.name, sum(i.quantity) as nr_items

FROM customers as c, orders as o, order_items as i

WHERE c.customerid = o.customerid and o.orderid = i.orderid

GROUP BY c.customerid, c.name

HAVING nr_items >= 2;

27

DML – Grouping & Aggregating Data

Page 28: Relational DBs and SQL Designing Your Web Database (Ch. 8)

Non-standard clause!Useful in Web applicationsAllows to specify a range of rows to be returned, syntax:

LIMIT start, endUsually combined with ORDER BYExample – two most expensive books:

SELECT * FROM books ORDER BY price DESCLIMIT 2;

28

DML – LIMIT clause