Populating and Querying tables
description
Transcript of Populating and Querying tables
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.– Group data using the GROUP BY clause– Include or exclude grouped rows by using the HAVING clause
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.
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.
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
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.
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
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
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’?
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?
What are the sales that this staff member made?
Staff no Staff Set ofDocket
Docket Set ofOrder Line
Order Line
Multi-table queries
Revisiting database structure ExternalSchema
ConceptualSchema
InternalSchema
PhysicalSchema
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
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
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
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'
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
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.
More usually, the query uses ‘join’
• Select * from products join suppliers on products.supplierId = suppliers.supplierId
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.
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
Enquiry Access PathSales for product by category
Entry PointOPERATION LIST
Categories Set ofProducts
Products Set ofOrder details
Order details
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.
• 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
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;
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
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
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