Presentation is loading. Please wait.

Presentation is loading. Please wait.

Populating and Querying tables Insert, Update, Delete and View (DML)

Similar presentations


Presentation on theme: "Populating and Querying tables Insert, Update, Delete and View (DML)"— Presentation transcript:

1 Populating and Querying tables Insert, Update, Delete and View (DML)

2 Inserting data into a table To add a row of data to a table INSERT INTO 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.

3 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.

4 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

5 Revisiting Joe’s Yard…

6 Hierarchy of data structure

7 Layers of tables The tables Customer, Staff and Supplier have only primary keys. They are the foundation layer. Layer 1. The tables Docket, Stock and Supplier Order have foreign keys that only reference the foundation layer. They are Layer 2. Order line and Supplier order line depend on the tables in Layer 2. They are layer 3.

8 Remember the bricks…

9 Layer 1 The customer row is added, with key CustomerId, the Staff with key StaffNo and the Supplier with key SupplierId.

10 Layer 2 Docket Stock Supplier Order CustomerStaff Supplier The stock and the supplier Order depend on the Supplier, both having foreign key SupplierId. The Docket depends on BOTH Staff and Customer, having foreign keys CustomerPdSig, CustomerRcvdSig and CustomerId.

11 Layer 3 SupplierStaff Customer Docket Stock Supplier Order Both the supplier order line and the order line depend on the stock, having stockcode as a foreign key and part of their key. Order line depends on docket. Supplier order line depends on Supplier Order

12 The built database

13 Recap Look back at the blocks. –The table creates are the structure or the framework - i.e. the architect’s drawing –The inserts are like the bricks. You cannot insert into a table unless there is supporting data in the table on which it depends. Do –Creates starting with the one(s) with no dependents –Inserts starting with the one(s) with no dependents –Deletes starting with the one(s) on which no other depends –Drops starting with the one(s) on which no other depends

14 Revisiting database structure External Schema Conceptual Schema Internal Schema Physical Schema

15 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

16 SQL, DML and DDL Data manipulation and definition

17 SQL Standard Query Language is used widely to access databases. Implemented SQL (Oracle, MS SQL Server, Access) varies a little from the standard, but is reasonably standard It consists of a data definition language - DDL (Create, Alter, Drop) And a Data Manipulation Language - DML (Select, Union, Update, Delete, Insert Into, Select Into, Transform, Parameter)

18 DLL - Add a table CREATE TABLE table_name {(column_name data_type [NOT NULL] [UNIQUE][DEFAULT default_option] [CHECK (search_condition)][,…]} [PRIMARY KEY (list_of_columns),] {[UNIQUE (list_of_columns),][,…]} {[FOREIGN KEY {(list_of_foreign_key_columns) REFERENCES parent_table_name[(list_of_candidate_key_columns)], [MATCH {PARTIAL | FULL} {[CHECK (search_condition)][,…]}) [] optional, {} one or more, lower case – user supplied names, upper case reserved words, [|] either or, () are part of the syntax.

19 Basic create DDL - Create a table Create table Publisher (PubID VARCHAR(10) NOT NULL, PubName VARCHAR(100), PubPhone VARCHAR(20)) Create table Books (ISBN VARCHAR(13) NOT NULL, Title VARCHAR(100), Price Decimal(7,2), PubID VARCHAR(10))

20 With keys Create table Publisher (PubID VARCHAR(10) UNIQUE NOT NULL, PubName VARCHAR(100), PubPhone VARCHAR(20), primary key (PubID)) Create table Books (ISBN VARCHAR(13), Title VARCHAR(100), Price Decimal(7,2), PubID VARCHAR(10), PRIMARY KEY (ISBN), FOREIGN KEY (PubID) REFERENCES PUBLISHER)

21 DDL - Add a table Syntax is as follows:- CREATE TABLE TableName (ColumnDefinition,… [,Multi-ColumnConstraint,…]); Column definition is ColumnDefinition ::= ColumnName DataType[(size)][Single-ColumnConstraint]

22 Constraints

23 DDL - Single column constraint Single-ColumnConstraint:== CONSTRAINT IndexName [PRIMARY KEY | UNIQUE | REFERENCES ReferencedTable [(ReferencedColumn,…)] ] The ReferencedColumn is only necessary if the field being referenced is not the primary key of the referenced table

24 DDL - Multi-column constraints This constraint clause can appear after all column definitions: CONSTRAINT IndexName [PRIMARY KEY (ColumnName,…) | UNIQUE (ColumnName,…) | FOREIGN KEY (ReferencingColumn,…) REFERENCES ReferencedTable[(ReferencedColumn,…)] ]

25 DDL - Create a table Create table Publisher (PubID TEXT(10) CONSTRAINT PrimaryKeyName PRIMARY KEY, PubName TEXT(100), PubPhone TEXT(20)); Create table Books (ISBN TEXT(13) CONSTRAINT PrimaryKeyName PRIMARY KEY, Title TEXT(100), Price MONEY, PubID TEXT(10) CONSTRAINT FOREIGN KEY PubID REFERENCES PUBLISHER(PubID));

26 Constraints on a single column [ NULL | NOT NULL ] { PRIMARY KEY | UNIQUE } FOREIGN KEY ] REFERENCES ref_table [ ( ref_column ) –[ ON DELETE { CASCADE | NO ACTION } ] –[ ON UPDATE { CASCADE | NO ACTION } ] CHECK ( logical_expression )

27 Table constraints. ::= [ CONSTRAINT constraint_name ] – { [ { PRIMARY KEY | UNIQUE } { ( column [ ASC | DESC ] [,...n ] ) } [ WITH FILLFACTOR = fillfactor ] [ ON { filegroup | DEFAULT } ] ] –FOREIGN KEY [ ( column [,...n ] ) ] REFERENCES ref_table [ ( ref_column [,...n ] ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] [ NOT FOR REPLICATION ] | CHECK [ NOT FOR REPLICATION ] ( search_conditions )

28 Widely used constraints Primary key Foreign key Unique Check (logical expression) Not null – do we always want this?

29 DDL - ALTER or DROP TABLE Alter is used to –Add a new column to the table –Delete a column from the table Drop is used to delete a table

30 DDL - Syntax for Alter and Drop ALTER TABLE TableName ADD ColName ColType[(size)] [unique][not null] | DROP COLUMN ColName DROP TABLE TableName

31 Create examples This allows certain constraints to be placed on a column or attribute –E.g. CREATE TABLE CLASS (CLASS_name char(10) CHECK (class_name in ('wmt1','wmt2','wmt3')), class_tutor char(10) unique, not null, max_students integer CHECK max_students between 1 and 100 default 50, primary key (class_name))

32 Table Manipulation CREATE table … ALTER table … DROP table … These operations work on the TABLE This is equivalent to a file.

33 Alter /* Put in a field that allows the accident to be categorised as Trivial, Moderate, Serious or Disastrous */ alter table Accident add column accident_category char(1) check (accident_category in ('T','M','S','D'));

34 Row manipulation INSERT adds new rows of data to a table. UPDATE modifies existing data in a table. DELETE removes rows of data from a table.

35 UPDATE SET WHERE <condition; e.g. UPDATE Northwind.dbo.Products SET UnitPrice = UnitPrice * 1.1 WHERE CategoryID = 2

36 DELETE DELETE FROM WHERE Delete from BusDriver where Staff_No = 5544322;

37 Exercise The following tables form part of a database held in a relational DBMS: –Hotel (Hotel_No, Name, Address) –Room (Room_No, Hotel_No, Type, Price) –Booking (Hotel_No,Guest_No, Date_from, Date_To, Room_No) –Guest (Guest_No, Name, Address) where –Hotel contains hotel details and Hotel_No is the primary key, –Room contains room details for each hotel and (Hotel_No, Room_No) forms the primary key, –Booking contains details of the bookings and the primary key comprises (Hotel_No, Guest_No and Date_From) –Guest contains guest details and Guest_No is the primary key. Create the database.


Download ppt "Populating and Querying tables Insert, Update, Delete and View (DML)"

Similar presentations


Ads by Google