populating and querying tables

30
Populating and Querying tables Insert and mostly View (DML)

Upload: urbana

Post on 13-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Populating and Querying tables. Insert and mostly View (DML). Contents of this lecture. Inserting data into a single table. Queries On two tables. On two joined tables. On more than two joined tables. Lop-sided queries (outer joins). Tables joined to themselves. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Populating and Querying tables

Populating and Querying tables

Insert and mostly View (DML)

Page 2: Populating and Querying tables

Contents of this lecture• Inserting data into a single table.• Queries

– On two tables.

– On two joined tables.

– On more than two joined tables.

– Lop-sided queries (outer joins).

– Tables joined to themselves.– Group data using the GROUP BY clause– Include or exclude grouped rows by using the HAVING clause

Page 3: Populating and Querying tables

Inserting data into a table• To add a row of data to a table

INSERT INTO <table> VALUES

(value1, value2, …valueN)• If the value list matches the column list

exactly, there is no need to list the column names.

• If the value list does not match the column list exactly, there is a need to list the column names.

Page 4: Populating and Querying tables

Example

• insert into Expert values (2222221,'Dr. O''Meara','Orthopaedic');

• Where the expert table was set up as:-CREATE TABLE Expert (

Expert_Id numeric(7,0),

Expert_Name varchar(50),

Expertise_area varchar(15),

PRIMARY KEY (Expert_Id))

Note also, if you want to put an apostrophe in a string, put in two apostrophes.

Page 5: Populating and Querying tables

Referential integrity

• The above tables have no foreign keys and a straightforward insert does not compromise referential integrity.

• If a table is constrained by foreign key values, then there is a need to see what is in the other table.

• Retrieving data from a database– Data can be retrieved from a table or set of tables using

the SELECT statement

Page 6: Populating and Querying tables

Common errors on insert

• Server: Msg 2627, Level 14, State 1, Line 1 Violation of PRIMARY KEY constraint 'PK__Contract__05D8E0BE'. Cannot insert duplicate key in object 'Contract'.– This happens when you put a value in the primary key field that

already appears in the file – i.e. record already exists.• INSERT statement conflicted with COLUMN FOREIGN

KEY constraint 'FK__Contract__Custom__06CD04F7'. The conflict occurred in database 'pobyrne', table 'customer', column 'Customer_number'.– In this statement, I tried to add a contract to the contract table,

referencing a customer that was not in the customer table. The contract table has customer_number as a foreign key referencing the customer table.

Page 7: Populating and Querying tables

Enquiry Access Paths

• Traversing a data model

• Start with a data model or ERD.

Stock

Stock CodeStock DescriptionUnit Price

* Supplier IdUnitCostPriceStock levelReorder level

Docket

DocketNoOrder Date

* Customer IdDocketPaidSigDocketRcvdSig

* Staff no

Order Line

* DocketNo* Stock CodeQuantityRequired

Customer

Customer IdCustomer NameCustomer Address

Supplier

Supplier IdSupplier NameSupplier AddressAmount Owed

Staff

Staff nameStaff noStaff role

SupplierOrder

* Supplier IdSupplierOrderNoSupplierOrderDateDeliveredDate

SupplierOrderLine

* SupplierOrderNo* Stock CodeStockRequired

Page 8: Populating and Querying tables

ERD

Stock

Stock CodeStock DescriptionUnit Price

* Supplier IdUnitCostPriceStock levelReorder level

Docket

DocketNoOrder Date

* Customer IdDocketPaidSigDocketRcvdSig

* Staff no

Order Line

* DocketNo* Stock CodeQuantityRequired

Customer

Customer IdCustomer NameCustomer Address

Supplier

Supplier IdSupplier NameSupplier AddressAmount Owed

Staff

Staff nameStaff noStaff role

SupplierOrder

* Supplier IdSupplierOrderNoSupplierOrderDateDeliveredDate

SupplierOrderLine

* SupplierOrderNo* Stock CodeStockRequired

Page 9: Populating and Querying tables

Which customers have bought stock supplied by

Entry Point

OPERATION LIST

Supplier Set ofStock

Stock Set ofOrder Line

Order Line Docket Customer

Which customers have bought stock supplied by ‘supplierId’?

Page 10: Populating and Querying tables

Stock

Stock CodeStock DescriptionUnit Price

* Supplier IdUnitCostPriceStock levelReorder level

Docket

DocketNoOrder Date

* Customer IdDocketPaidSigDocketRcvdSig

* Staff no

Order Line

* DocketNo* Stock CodeQuantityRequired

Customer

Customer IdCustomer NameCustomer Address

Supplier

Supplier IdSupplier NameSupplier AddressAmount Owed

Staff

Staff nameStaff noStaff role

SupplierOrder

* Supplier IdSupplierOrderNoSupplierOrderDateDeliveredDate

SupplierOrderLine

* SupplierOrderNo* Stock CodeStockRequired

What are the sales that this staff member made?

Page 11: Populating and Querying tables

What are the sales that this staff member made?

Staff no Staff Set ofDocket

Docket Set ofOrder Line

Order Line

Page 12: Populating and Querying tables

Multi-table queries

Page 13: Populating and Querying tables

Revisiting database structure ExternalSchema

ConceptualSchema

InternalSchema

PhysicalSchema

Page 14: Populating and Querying tables

The external schema

– Level visible to user

– Multiple views of the system

• e.g. View an order - see limited product and customer information

– Only the database Administrator may access the whole database at this level

• Each external view is defined by means of an external schema– Provides definitions of each

external view.

– Written in a Data Definition Language.

– individual to the user or user group.

– accessed through a 3GL, a query language or a special purpose forms or menu-based language

Page 15: Populating and Querying tables

Queries

• User creates a query, to provide a specific view of the data

• Database application converts this into a statement in SQL

• DBMS executes the SQL statement• BASE TABLE - a table storing data• DERIVED TABLE - virtual result table from a

query

Page 16: Populating and Querying tables

Query essentials

• Selection– This is where rows from a table are extracted on the

basis of the value of one or more of the fields

• Projection– This is where columns from a table are extracted on the

basis of the value of one or more of the fields

• Join– This is where rows and columns from more than one

table are extracted

Page 17: Populating and Querying tables

Selection • Selects only those ROWS which satisfy the

selection criteria

• Example:– Set up a query to display claims where the state

is trivial (T):Select * from Claim where Claim_state = 'T'

Page 18: Populating and Querying tables

Projection

• A projection of a table onto a subset of its

attributes (i.e. throw away unnecessary

attributes)

• e.g. project Expert Name and Expertise from

Expert:

– Select Expert_Name, Expertise_area from Expert

Page 19: Populating and Querying tables

Joins

• Tables can be joined together on fields which have the same attributes:SELECT * FROM products, suppliers

WHERE products.supplierId = suppliers.supplierId;

– Note: Tables can be joined in this way even if they were set up without a foreign key.

Page 20: Populating and Querying tables

More usually, the query uses ‘join’

• Select * from products join suppliers on products.supplierId = suppliers.supplierId

Page 21: Populating and Querying tables

3-table join

• If you have a query that involves more than one relationship, you must join over relationships

• For example (Northwind),– “Show me the sales for each product, ordered

by category and product , giving the categoryname and product name.

Page 22: Populating and Querying tables
Page 23: Populating and Querying tables

NorthWind ERD

Orders

OrderDateRequiredDateShippedDateFreightShipNameShipAddressShipCityShipRegionShipPostalCodeShipCountryOrderId

* ShipVia* CustomerId* EmployeeId

Products

ProductIdProductName

* CategoryIdQuantityPerUnitUnitPriceUnitsInStockUnitsOnOrderReorderLevelDiscontinued

* SupplierId

Shippers

ShipperIdCompanyNamePhone

Suppliers

SupplierIdCompanyNameContactNameContactTitleAddressCityRegionPostalCodeCountryPhoneFaxHomePage

Categories

CategoryIdCategoryNameDescriptionPicture

Order details

* OrderId* ProductIdUnitPriceQuantityDiscount

Customers

CustomerIdCompanyNameContactNameContactTitleAddressCityRegionPostalCodeCountryPhoneFax

Employee

EmployeeIdLastNameFirstNameTitleTitleOfCourtesyBirthDateHireDateAddressCityRegionPostalCodeCountryHomePhoneExtensionPhotoNotesPhotoPath

* ReportsTo

Note:ShipVia is the name ofthe foreign key in OrderDetails that refers tothe Shippers entity.ReportsTo is the name ofthe foreign key in therecursive relationshipin the Employee entity

Page 24: Populating and Querying tables

Enquiry Access PathSales for product by category

Entry PointOPERATION LIST

Categories Set ofProducts

Products Set ofOrder details

Order details

Page 25: Populating and Querying tables

Joins required

• Categories needs to join with products

• Products needs to join with Order details

• Joins can be nestedA join B on A.x = B.x

join C on B.y = C.y

Join D on C.z = D.z

etc.

Page 26: Populating and Querying tables

• In this example, there are 2 joins• Categories join products on

Categories.categoryId = Products.CategoryId • Products join [order details] on

products.productId = [order details].productId

– There is also a derived column, from the [order details] table. Income = (unitPrice * quantity) - discount

Page 27: Populating and Querying tables

Queryuse Northwind;

Select categoryName, ProductName,

(([order details].unitPrice*Quantity)-Discount)

as income

from

categories join products on categories.categoryid = products.categoryid

join [order details]

on products.productid = [order details].productid;

Page 28: Populating and Querying tables

Result

categoryName ProductName income

--------------- ---------------------------------------- ------------------------

Beverages Chai 647.79999

Beverages Chai 259.20001

Beverages Chai 288.0

Beverages Chai 215.85001

Beverages Chai 172.8

Beverages Chai 215.85001

Beverages Chai 144.0

Beverages Chai 345.60001

Beverages Chai 216.0

Beverages Chai 719.79999

Beverages Chai 143.85001

Beverages Chai 180.0

Beverages Chai 360.0

Beverages Chai 54.0

Page 29: Populating and Querying tables

Improve layout of outputSelect categoryName,

cast(ProductName as char(12))as Product,

cast(([order details].unitPrice*Quantity)-Discount as decimal(10,2)) as income

from

categories join products on categories.categoryid = products.categoryid

join [order details] on products.productid = [order details].productid

Page 30: Populating and Querying tables

Improved output

categoryName Product income --------------- ------------ ------------ Beverages Chai 647.80Beverages Chai 259.20Beverages Chai 288.00Beverages Chai 215.85Beverages Chai 172.80Beverages Chai 215.85Beverages Chai 144.00Beverages Chai 345.60Beverages Chai 216.00Beverages Chai 719.80