View
12
Download
1
Category
Preview:
DESCRIPTION
SQL. Chapter 9:. An Introduction to Structured Query Language (SQL). (With Considerable Modifications). SQL. Why SQL??. “De facto standard in RDBMS”. Can be implemented on all platforms. Processes data on a SET Level. Works with groups of data (Tables). - PowerPoint PPT Presentation
Citation preview
CIS4365: Professor Kirs Slide Number: 1
SQL
Chapter 9:An Introduction to Structured
Query Language (SQL)(With Considerable Modifications)
CIS4365: Professor Kirs Slide Number: 2
SQL
Why SQL?? “De facto standard in RDBMS” Can be implemented on all platforms Processes data on a SET Level
Works with groups of data (Tables) Relatively Few Statements
Portability Ease of Learning Ease of use
Developed around concept of Data Definition Language (DDL) Data Manipulation Language (DML) Data Control Language (DCL)
CIS4365: Professor Kirs Slide Number: 3
SQL
Database Definition Recall our Physician Table:
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields
We know the fields we need, and perhaps even what field names we will use, BUT what type of data will we use to store the information ???
What Types of data are there ???
CIS4365: Professor Kirs Slide Number: 4
SQLDatabase DefinitionBasic Data Types: (C Data Types used for illustration)Character char/signed 1-byte -128 to + 127
unsigned char 1-byte 0 to + 255
Integer int/signed 2-bytes -32,768 to 32,767
unsigned int 2-bytes 0 to 65,537
long/signed 4-bytes -2,147,483,648 to 2,147,483,647
unsigned long 4-bytes 0 to 4,294,967,295
Real float 4-bytes 7 decs. precisiondouble 8-bytes 10 decs. precisionlong double 16-bytes 10 decs. precision
(Maybe)(OR) int/signed 4-bytes -2,147,483,648 to 2,147,483,647
(Maybe)(OR) char/signed 2-byte -32,768 to 32,767
(Maybe)(OR) unsigned char 2-bytes 0 to 65,537
(Maybe)(OR) unsigned int 4-bytes 0 to 4,294,967,295
(OR) long/signed 8-bytes -9,223,372,036,854,780,000 to …….
(OR) unsigned long 4-bytes 0 to 18,467,440,737,906,000,000
CIS4365: Professor Kirs Slide Number: 5
SQL
Database DefinitionOf course, there are additional abstract data structures
Arrays A fixed number of contiguous data elements all of the same type
Strings An array of data type char
Structs A combination of two or more data types• Structured data objects• Records
Others • Date/Time• Graphics• OLE (Object Linking and Embedding)• Hyperlinks
CIS4365: Professor Kirs Slide Number: 6
SQL
Database DefinitionOracle Allows for the following Basic data types to be entered into Fields (There are others)
CHAR • A string
Characters
• The length (N) MUST be specified• If less than N characters are entered, N
spaces will STILL be allocated
• Up to 255 characters are allowed• Usage: Fieldname CHAR(N)
CIS4365: Professor Kirs Slide Number: 7
SQL
Database Definition
VARCHAR • A string
Characters
• The length (N) MUST be specified• ONLY the number characters are entered
will be allocated space
• Up to 255 characters are allowed• Usage: fieldname VARCHAR(N)
VARCHAR2, LONG VARCHAR
CIS4365: Professor Kirs Slide Number: 8
SQL
Database DefinitionNumeric Data Types
INTEGER Typically, up to 10 - 11 digits are allowed• Range (Typically):
-2,147,483,648 through +2,147,483,647
SMALLINT Typically, up to 4 - 5 digits are allowed• Range (Typically):
-32,768 through +32,767
• Usage: fieldname INTEGER
• Usage: fieldname SMALLINT
CIS4365: Professor Kirs Slide Number: 9
SQL
Database DefinitionNumeric Data Types
DECIMAL(m,n)
A Real (Floating-Point) Number with m total digits (INCLUDING the sign and decimal point) and n decimals to the right of the decimal point• m may (Typically) be as large as 19
• Usage: fieldname DECIMAL(10,4)
• n may (Typically) be as large as 7 - 8
This allows for a number between99999.9999 through -9999.999 (The sign counts)
But ONLY to 3 decimal point of precision
CIS4365: Professor Kirs Slide Number: 10
SQL
Database DefinitionDate and Time Data Types
DATE Date Value• (Typically) Displayed as mm/dd/yy• Usage: fieldname DATE
TIME Time Value• (Typically) Displayed as hh:mm:ss• Useful in Time Stamping• Usage: fieldname TIME
CIS4365: Professor Kirs Slide Number: 11
SQL
Database Definition NOW, Returning to our Physician Table:
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields
Let’s assume the following Field Names and Data types:
physid CHAR(9)physname CHAR(30)specialty CHAR(15)street CHAR(20)city CHAR(20)
state CHAR(2)
zip CHAR(5)
CIS4365: Professor Kirs Slide Number: 12
SQL
Before going on to SQL, Let’s see how other languages might create the record
Database Definition
01 PHYSICIAN05 PHYSID PIC X(9).05 PHYSNAME PIC X(30).05 SPECIALTY PIC X(15).05 STREET PIC X(20).05 CITY PIC X(20).05 STATE PIC X(2).05 ZIP PIC X(5).
In COBOL:
CIS4365: Professor Kirs Slide Number: 13
SQL
Database Definition
In Pascal:
type physician = recordphysid: array[1..9] of char;physname: array[1..30] of char;specialty: array[1..15] of char;street: array[1..20] of char;city: array[1..20] of char; state: array[1..2] of char;zip: array[1..5] of char;
end;
In C:struct physician{ char physid[10]; char physname[31]; char specialty[16]; char street[21]; char city[21];
char state[3];char zip[6];
};
CIS4365: Professor Kirs Slide Number: 14
SQL
Database Definition The SQL Commands Needed to create the table are
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields CREATE TABLE physician
( physid CHAR(9), physname CHAR(30), specialty CHAR(15), street CHAR(20), city CHAR(20), state CHAR(2), zip CHAR(5) );
Every SQL Command ends with a semicolon
CIS4365: Professor Kirs Slide Number: 15
SQL
Database Definition Let’s Examine the command
CREATE TABLE physician( physid CHAR(9), physname CHAR(30), specialty CHAR(15), street CHAR(20), city CHAR(20), state CHAR(2), zip CHAR(5) );
• We have CREATEd a new table (file) called physician
• Each record we enter will contain 7 fields
• Each record will require 9 + 30 + 15 + 20 + 20 + 2 + 5 = 101 Bytes of Storage
• We encased our field declarations between parentheses ()
• Each field (except for the last) was separated by a comma ( , )
CIS4365: Professor Kirs Slide Number: 16
SQL
Database DefinitionBut don’t we know more about the table?? Yes, We Know:
• The Table physician has as its primary key the field physid
• It wouldn’t make sense to leave the physname field blank (although theoretically, we could)
We Could also make some assumptions:• The physician lives in Texas (Code: TX)
CIS4365: Professor Kirs Slide Number: 17
SQL
Database Definition Let’s rewrite the command:
Adding these Qualifiers will assure that the fields will NOT be left empty
CREATE TABLE physician( physid CHAR(9) NOT NULL, physname
CHAR(30) NOT NULL,
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields
This is Superfluous. WHY ???
CIS4365: Professor Kirs Slide Number: 18
SQL
Database Definition Let’s rewrite the command:
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields CREATE TABLE physician
( physid CHAR(9) NOT NULL, physname
CHAR(30) NOT NULL,specialty CHAR(15), street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’,
If nothing is entered into the state field, TX will be entered by default
CIS4365: Professor Kirs Slide Number: 19
SQL
Database Definition Let’s rewrite the command:
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields CREATE TABLE physician
( physid CHAR(9) NOT NULL, physname
CHAR(30) NOT NULL,specialty CHAR(15), street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’,
zip CHAR(5), PRIMARY KEY (physid) );
physid has been identified as the primary key
CIS4365: Professor Kirs Slide Number: 20
SQL
Database Definition We Can get also add additional constraints
CREATE TABLE physician( physid CHAR(9) NOT NULL, physname CHAR(30) NOT NULL, specialty CHAR(15) NOT NULL, street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’, zip CHAR(5), PRIMARY KEY (physid) UNIQUE (specialty) );
• Let’s assume that we can only have one (1) specialist in each area:
CIS4365: Professor Kirs Slide Number: 21
SQL
Database Definition We need to ‘Back-Track’
The Network Schema
The Network Subschema
The conceptual Organization of the entire database
The conceptual Organization of the database as “seen” by the applications programs accessing it
• Remember that we previously discussed Schemas
We need to Develop our tables with this in mind
CIS4365: Professor Kirs Slide Number: 22
SQL
Database Definition A Schema consists of
• Tables (which we previously created)• Views (Or Virtual Table)
A subset of rows and columns Not a physical entity (as are tables) Can be treated as tables
• User Authorization
Created by the DBMS each time they are referenced by the user as a query
Usernames allowed (and how allowed) to access the tables
CIS4365: Professor Kirs Slide Number: 23
SQL
Database Definition A more appropriate CREATE might have been:
CREATE SCHEMAATHORIZATION pkirs
CREATE TABLE physician( physid CHAR(9),
physname CHAR(30) NOT NULL, specialty CHAR(15) NOT NULL, street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’, zip CHAR(5), PRIMARY KEY (physid) UNIQUE (specialty) );
CIS4365: Professor Kirs Slide Number: 24
SQL
Database Definition Some Basic CREATE TABLE Guidelines
• Choose Numeric data types ONLY if calculations are to be performed on the field
• Make the lengths of the character columns long enough to accommodate future values (Remember the Y2K Problem)
• Apply the same guidelines for DECIMAL data• Don’t automatically choose VARCHAR over CHAR• Use EXACTLY the same data types for columns which
will be compared often or used in calculations together • Use NOT NULL when a column MUST contain a value• PRIMARY KEYS ARE ALWAYS NOT NULL
CIS4365: Professor Kirs Slide Number: 25
SQL
Database Definition Let’s Consider the relationship between our
Physician and Patient tables
Physician PatientTreats
Remember what this means:• A Patient MUST have one (and ONLY one)
Physician• A Physician MAY have more than 1 (one)
Patient
CIS4365: Professor Kirs Slide Number: 26
SQL
Database Definition We Previously defined our Patient fields:
Patient Table Attributes/Fields
PatID
Name
Address
PhysID
And how Patient relates to our Physician table:
PhysID
Name
Specialty
Street
City
State
ZipCode
Physician Table Attributes/Fields
physid has in Patient is a foreign key
CIS4365: Professor Kirs Slide Number: 27
SQL
Database Definition We now need to define our Patient fields:
Patient Table Attributes/Fields
PatID
Name
……..
PhysID
Let’s Pretend that field Address doesn’t Exist
CREATE TABLE patient( patid CHAR(9) NOT NULL, nameCHAR(30) NOT NULL,physid CHAR(9) NOT NULL, PRIMARY KEY (patid) FOREIGN KEY (physid)
REFERENCES physician (physid));
We have established our relationship between patient and physician
CIS4365: Professor Kirs Slide Number: 28
SQL
Database Definition Again, Let’s Examine the command
• We have CREATEd a new table (file) called patient
• Each record we enter will contain 3 fields
• Each record will require 9 + 30 + 9 = 48 Bytes of Storage
• We encased our field declarations between parentheses ()
• Each field (except for the last) was separated by a comma ( , )
CREATE TABLE patient( patid CHAR(9) NOT NULL, name CHAR(30) NOT NULL,
physid CHAR(9) NOT NULL, PRIMARY KEY (patid), FOREIGN KEY (physid)
REFERENCES physician (physid) );
• We have linked two (2) tables together
CIS4365: Professor Kirs Slide Number: 29
SQL
Database Definition We are on the way to building a Script (Program)
• A text file that contains SQL commands So far, our Script would appear as:
CREATE SCHEMAATHORIZATION pkirs
CREATE TABLE physician( physid CHAR(9) NOT NULL,
physname CHAR(30)NOT NULL,
specialty CHAR(15) NOT NULL, street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’, zip CHAR(5), PRIMARY KEY (physid) UNIQUE (specialty) );
physid CHAR(9) NOT NULL, PRIMARY KEY (patid), FOREIGN KEY (physid)
REFERENCES physician (physid) );
CREATE TABLE patient( patid CHAR(9) NOT NULL, name CHAR(30) NOT NULL,
CIS4365: Professor Kirs Slide Number: 30
SQL
Database Definition
Patient IllnessSuffer
Finally, Let’s create two more tables
Remember, this is a Many-to-Many Relationship
M1
M
1Patient Table
PatID
Name
……..
PhysID
IllCode
Name
Others
Illness TableSuffers Table
Date/Time
Others
PatID
IllCode
CIS4365: Professor Kirs Slide Number: 31
SQL
Database Definition First, let’s create our illness table:
Let’s Pretend that field Others doesn’t Exist
CREATE TABLE illness( illcode CHAR(10), name CHAR(20) NOT NULL,
PRIMARY KEY (illcode) UNIQUE (name) );
IllCode
Name
. . . . . .
Illness Table
CIS4365: Professor Kirs Slide Number: 32
SQL
Database Definition We now need to define our Suffers fields:
Let’s Pretend that field Others doesn’t Exist
CREATE TABLE suffers( patid CHAR(9) NOT NULL, illcodeCHAR(10) NOT NULL,sdate DATE NOT NULL, stime TIME NOT NULL, PRIMARY KEY (patid, illcode), FOREIGN KEY patid
REFERENCES patient (patid), FOREIGN KEY illcode
REFERENCES illness (illcode) );
Suffers Table
Date/Time
. . . . . . .
PatID
IllCode
CIS4365: Professor Kirs Slide Number: 33
SQL
Database Definition Our Script would appear as:
CREATE SCHEMAATHORIZATION pkirs
CREATE TABLE physician( physid CHAR(9) NOT NULL,
physname CHAR(30) NOT NULL, specialty CHAR(15) NOT NULL, street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’, zip CHAR(5), PRIMARY KEY (physid) UNIQUE (specialty) );
physid CHAR(9) NOT NULL, PRIMARY KEY (patid), FOREIGN KEY (physid)
REFERENCES physician (physid) );
CREATE TABLE patient( patid CHAR(9) NOT NULL,
name CHAR(30) NOT NULL,
CREATE TABLE illness( illcode CHAR(10) NOT NULL, name CHAR(20)NOT NULL,PRIMARY KEY (illcode) UNIQUE (name) );CREATE TABLE suffers( patid CHAR(9),
illcode CHAR(10) NOT NULL, sdate DATE NOT NULL, stime TIME NOT NULL, PRIMARY KEY (patid, illcode), FOREIGN KEY (patid)
REFERENCES patient (patid), FOREIGN KEY (illcode)
REFERENCES illness (illcode) );
CIS4365: Professor Kirs Slide Number: 34
SQL
Database Definition Additional options in CREATE
CHECK• Suppose ALL of our physicians could ONLY live in
Arlington, Dallas, or Fort Worth• Our physician table could be rewritten as:
CREATE TABLE physician( physid CHAR(9) ,
physname CHAR(30) NOT NULL,specialty CHAR(15),
street CHAR(20), city CHAR(20), state CHAR(2), DEFAULT ‘TX’,
zip CHAR(5), PRIMARY KEY (physid), CHECK (city in ‘Arlington’, ‘Dallas’, Ft. Worth’) );
CIS4365: Professor Kirs Slide Number: 35
SQL
Database Definition Additional CHECK options
• If we had an integer field called salary, and salary HAD to be greater than 50000:
CREATE SCHEMA( ººººº CHECK (salary > 50000) );
• If we had an integer field called salary, and salary HAD to be greater than 50000 BUT less than 100000:
CREATE SCHEMA( ºººººCHECK (salary BETWEEN 50000 AND 100000) );
CIS4365: Professor Kirs Slide Number: 36
SQL
Database Definition Security/Privilege Options
• The owner (AUTHORIZATION pkirs) has full access
• If we wished to allow user clinton (which MUST be a registered username) full access to table physician:
CREATE SCHEMAATHORIZATION pkirsCREATE TABLE physician( ººººº )GRANT ALL ON physician TO clinton;
CIS4365: Professor Kirs Slide Number: 37
SQL
Database Definition• If we wished to allow user clinton to insert new records into
to table physician:
GRANT INSERT ON physicianTO clinton;
• If we wished to allow user clinton ONLY to edit tables physician and patient:
GRANT UPDATE ON physician, patient TO clinton;
• If we allow user clinton ONLY to view physician and patient data:
GRANT SELECT ON physician, patient TO clinton;
• If we allow everyone to view and update table physician:
GRANT SELECT, UPDATE ON physician TO PUBLIC
CIS4365: Professor Kirs Slide Number: 38
SQL
Database Modification Inserting records
INSERT INTO physician VALUES (‘123456789’, ‘Smith, John’, ‘Surgery’, ‘123Main’, ‘El Paso’, ‘TX’, ‘76019’)
• Note that this corresponds to our physician table structure:
( physid CHAR(9), physname CHAR(30), specialty CHAR(15), street CHAR(20), city CHAR(20), state CHAR(2), zip CHAR(5) );
CIS4365: Professor Kirs Slide Number: 39
SQL
Database Modification
• Any new records added (or changes made to records) will not be permanent until we enter the command:
Saving records
COMMIT;
Changing our minds
• If we decide we shouldn’t have entered the record (or made the changes), we can enter the command:
ROLLBACK;
• Which will restore the database back to how it was before the last COMMIT was entered
CIS4365: Professor Kirs Slide Number: 40
SQL
Database Modification Updating Records
• Right now, our physician table appears as:
123456789 Smith, John Surgery 123 Main El Paso TX 76019
physid physname specialty street city state zip
• If we wished to change John Smith’s specialty from surgery to OB/GYN we would enter the command:
UPDATE physician SET specialty = ‘OB/GYN’WHERE physid = ‘123456789’;
• NOTE: The changes would be applied only AFTER we COMMIT
CIS4365: Professor Kirs Slide Number: 41
SQL
Database Modification Updating Records
• Notice also that the command
UPDATE physician SET specialty = ‘OB/GYN’WHERE physid = ‘123456789’;
• Requires us to find for a specific record using the search condition:
WHERE physid = ‘123456789’;
(a TRUE/FALSE condition)
CIS4365: Professor Kirs Slide Number: 42
SQL
Database Modification Deleting Records
• To delete a record from a database, we must once again find it and issue the command:
DELETE FROM physician WHERE physid = ‘123456789’;
• Once Again, The changes would be applied only AFTER we COMMIT
CIS4365: Professor Kirs Slide Number: 43
SQL
Database Modification Deleting Records
• We could also delete multiple records:
DELETE FROM patient WHERE physid NOT IN (‘123456789’, ‘234567890’);
• This would delete all records who did not have these two physicians as their primary providers
(We can get much fancier here)
CIS4365: Professor Kirs Slide Number: 44
SQL
Database Modification Deleting Tables
• To delete a table from a database, we need only issue the command:
DROP TABLE physician;
• A DROP DOES NOT require an explicit COMMIT statement (although a ROLLBACK will undo the command)
CIS4365: Professor Kirs Slide Number: 45
SQL
Database Structure Modification Altering the database (FOR MOST RDBMS)
• Unrestricted Alterations• Adding a new column to a table• Deleting a primary key
(Foreign Key references are automatically removed)• Deleting a foreign key
• Restricted Alterations
• Changing a columns data type, size, and default value is allowed ONLY if there are NO DATA in the column being modified
CIS4365: Professor Kirs Slide Number: 46
SQL
Database Structure Modification Altering the database (FOR MOST RDBMS)
• Restricted Alterations• Adding a Primary Key, BUT only if there are no
duplicate values• Adding UNIQUE and CHECK condition ONLY if
the field matches the added condition • Adding a foreign key allowed ONLY if the values are
NOT NULL or exist in the referenced Table • Changing a column name is Not Allowed
(Continued)
• Deleting a column is NOT allowed
CIS4365: Professor Kirs Slide Number: 47
SQL
Database Structure Modification Altering the database
• To add a field to a database
ALTER TABLE physician ADD (malpracticefees DECIMAL(7,2));
• We can also specify WHERE to add it and add constraints:
ALTER TABLE physician ADD (malpracticefees DECIMAL(8,2))BEFORE streetINIT = 10000.00;
CIS4365: Professor Kirs Slide Number: 48
SQL
Database Structure Modification Altering the database
• Suppose that we find out that we need more space for our specialty field, presently:
ALTER TABLE physician, MODIFY (specialty CHAR(20));
• which would accept up to 20 characters for a physician specialty
• We might enter the command:
specialty CHAR(15),
CIS4365: Professor Kirs Slide Number: 49
SQL
Database Structure Modification Altering the database
• If, for some reason, we decided to change physid from a character to a numeric field, we might enter the command:
ALTER TABLE physician MODIFY (physid INTEGER);
• NOTE: This assumes that the field CAN be converted into a numeric Field
• If physid contained the data: 4B7876D
It could not be converted
CIS4365: Professor Kirs Slide Number: 50
SQL
Database Structure Modification Altering the database
• To remove a primary or foreign key, we might issue the command:
DROP CONSTRAINT ……. ;
• NOTE: If this sounds like a cop-out, it is because there are a number of variations
CIS4365: Professor Kirs Slide Number: 51
SQL
Database Structure Modification Altering the database
• IF we have designated a primary of foreign key (or we have removed them as above), we could now add them as:
ALTER TABLE physician ADD PRIMARY KEY (physname);
• AND
ALTER TABLE patient ADD FOREIGN KEY (physname)REFERENCES (physician);
CIS4365: Professor Kirs Slide Number: 52
SQL
Importing Data from another Database
NOTE:
• Data imported from other tables MUST be of the same data type
• IF we had a table physinfo which was IDENTICAL to our table physician, we could enter the command:
INSERT INTO physician SELECT *
FROM physinfo;
CIS4365: Professor Kirs Slide Number: 53
SQL
Importing Data from another Database• IF the table physinfo had some fields which matched
our table physician (and some which perhaps didn’t), we might enter the command:
INSERT INTO physician, (street, city, state, zip) SELECT (streetname, cityname, statename, zipcode)
FROM physinfoWHERE NOT (physid = idnum);
• NOTE: Fields in table physician had which were NOT imported from table physinfo will remain empty.
CIS4365: Professor Kirs Slide Number: 54
SQL
Database Queries Extracting information from a database Performed using high-level Query Languages Very similar across SQL platforms
(Although differences DO exist) Use of standard English commands:
• SELECT *
• FROM• WHERE
• SELECT
• GROUP BY• HAVING• ORDER BY
CIS4365: Professor Kirs Slide Number: 55
SQL
Would result in the (approximate) display:
physid physname specialty street city state zip------------- --------------------- ------------- ------------- -------- ------- --------123456789 Smith, John OB/GYN 123 Main El Paso TX 76019
Database Queries The Command:
SELECT * FROM physinfo ;
The Command:SELECT physid, physname, specialty FROM physician;
physid physname specialty ------------- -------------------- ---------------123456789 Smith, John OB/GYN
Would result in the (approximate) display:
CIS4365: Professor Kirs Slide Number: 56
SQL
Database Queries In SQL, We also have the choice of listing ALL (using
SELECT *, OR SELECT ALL) records or DISTINCT records:SELECT DISTINCT specialty FROM physician;
Might result in the (approximate) display:
specialty-------------SurgeryDermatologyOB/GYNOpthamologyENTPediatrics
CIS4365: Professor Kirs Slide Number: 57
SQL
Database Queries The Command:
SELECT physid, physname FROM physician WHERE (specialty = ‘Surgery’ OR specialty = ‘Dermatology’);
Might result in the (approximate) display:
physid physname------------- -------------------- 123456789 Smith, John 234567890 Jones, Mary345678901 Houston, Sam456789012 Bush, G.W.567890123 Clinton, Hillary
NOTE: Because we are using the OR operator, ALL records meeting the condition will be shown
CIS4365: Professor Kirs Slide Number: 58
SQL
Database Queries The Command:
SELECT physid, physname FROM physician WHERE (specialty = ‘Surgery’ AND specialty = ‘Dermatology’);
Might result in the (approximate) display:
physid physname------------- -------------------- NOTE: With the AND
operator, ONLY those records meeting BOTH conditions will be shown (in this case, None)
CIS4365: Professor Kirs Slide Number: 59
SQL
Database Queries SQL has the following built-in Operators:
Operator(s) Description* / Multiplication Division+ - Addition Subtraction
Suppose we had a table called inventory:
100 2.56 3.89 45
partnum cost price onhand
101 0.89 1.45 122102 1.76 2.99 82103 12.83 17.99 8104 4.88 7.22 28105 7.16 12.99 53
CIS4365: Professor Kirs Slide Number: 60
SQL
Database Queries Suppose we wanted to find the items where our
profit margin was 60% or more
In this case our profit is defined as:price
cost - 1
For our table inventory, our profit margins are:
100 2.56 3.89 45
partnum cost price onhand
101 0.89 1.45 122102 1.76 2.99 82103 12.83 17.99 8104 4.88 7.22 28105 7.16 12.99 53
* 100
Margin51.9562.9269.8940.2247.9581.42
CIS4365: Professor Kirs Slide Number: 61
SQL
Database Queries
SELECT partnum, price - cost FROM inventory WHERE ((price / cost - 1) * 100 => 0.60);
The Command:
Would result in the (approximate) display:
partnum price - cost------------- --------------- 101 1.33 102 1.23105 5.83
Notice we didn’t do a very good job labeling our fields
CIS4365: Professor Kirs Slide Number: 62
SQL
Database Queries
SELECT partnum AS ‘Part’, cost AS ‘Cost’, price AS ‘Price’,price - cost AS ‘Profit’, (price / cost - 1) * 100 AS ‘Margin’
FROM inventory WHERE ((price / cost - 1) * 100 => 0.60) ORDER BY ((price / cost - 1) * 100) DESC;
The Command:
Would result in the (approximate) display:
Part Cost Price Profit Margin------ -------- ------- --------- ----------105 7.19 12.99 5.83 81.42102 1.76 2.99 1.23 69.89101 0.89 1.45 1.33 62.95
CIS4365: Professor Kirs Slide Number: 63
SQL
Database Queries
SQL has a number of built-in numeric functions:
Function OutputCOUNT The number of rows containing the attributeMIN The minimum attribute encounteredMAX The maximum attribute encounteredSUM The total of all values for a selected attributeAVG The arithmetic mean for a selected attribute
CIS4365: Professor Kirs Slide Number: 64
SQL
Database Queries
SELECT COUNT (DISTINCT partnum) AS ‘No. Parts’, MIN (price) AS ‘Cheapest’, MAX(price) AS ‘Costliest’,SUM (cost * onhand) AS ‘Inv. Cost’, SUM (price * onhand) AS ‘Inv. Potential’, AVG ((price / cost - 1) * 100) AS ‘Ave. Margin’,SUM ((price * onhand) - (cost * onhand)) AS ‘Pot. Profit’,
FROM inventory;
The Command:
Would result in the (approximate) display:
No. Parts Cheapest Costliest Inv. Cost Inv. Potential Ave. Margin Pot. Profit ------------ ------------ ----------- ------------ ------------------ ----------------- ------------- 6 1.45 17.99 986.86 1631.68 59.06 644.82
CIS4365: Professor Kirs Slide Number: 65
SQL
Database Queries SQL also has a number of built-in special
functions:Function OutputBETWEEN Used to define Range LimitsIS NULL Used to check if an attribute contains
NULL ValuesLIKE Used to check similar Character
StringsIN Used to check if an attribute is
contained IN a set of ValuesEXISTS Used to check if an attribute value
exists (The opposite of IS NULL)
CIS4365: Professor Kirs Slide Number: 66
SQL
Database Queries
SELECT partnum, cost, priceFROM inventoryWHERE
partnum BETWEEN 102 AND 104;
The Command:
Would result in the (approximate) display:
partnum cost price------------- ---------- ---------102 1.76 2.99 103 12.83 17.99104 4.88 7.22
CIS4365: Professor Kirs Slide Number: 67
SQL
Database Queries
SELECT physid, physnameFROM physicianWHERE physname LIKE ‘Smi%’;
The Command:
Might result in the (approximate) display:
Physid physname------------- -------------123456789 Smithers 234567890 Smith456789012 Smickman678901234 Smiley
Where: % is a wildcard
CIS4365: Professor Kirs Slide Number: 68
SQL
Database Queries The LIKE command can take on a few forms:
Search String Pattern MatchedSm% Finds Any string starting with Sm%Sm% Finds Any string containing Sm %Sm Finds Any string ending with SmS_m Finds any 3 letter string beginning
with S and ending in m%S_m% Finds any string containing the letter S
followed by any character, followed by the character m
NOT LIKE The opposite of LIKE
CIS4365: Professor Kirs Slide Number: 69
SQL
Database Queries Often, it is necessary to JOIN tables together on
common keys (E.g., a foreign key) We Might enter the command:
SELECT physid, physname, patid, nameFROM physician, patientWHERE physician.physid = patient.physid;
This might result in the (approximate) display:Physid physname patid name------------- ------------- ------------- --------------123456789 Smith 987654321 Gore 123456789 Smith 876543210 Bradley456789012 Jones 765432109 Richardson678901234 Bush 654321098 Sanders
NOTE: If two tables have the same field names, we need to indicate which is which using DOT NOTATION
CIS4365: Professor Kirs Slide Number: 70
SQL
Database Queries We can also JOIN multiple tables together Remember our expanded relationship:
Physician PatientTreats Treatment Illness
Prescription Where we had a ternary
relationship between patient, illness, and prescription
CIS4365: Professor Kirs Slide Number: 71
In Tabular Form, this appeared as:
Patient Table
PatID
Name
Address
PhysID
Illness Table
Treatment Table
Prescription Table
IllCode
Name
Others
DrugCode
Others
Others
PatID
DrugCode
IllCode
Date/Time
SQL
Database Queries
CIS4365: Professor Kirs Slide Number: 72
SQL
Database Queries One command we might enter is:
SELECT physname, patient.name, illness.name, prescription.drugcode
FROM physician, patient, treatment, illness, prescriptionWHERE physician.physid = patient.physidAND patient.patid = treatment.patidAND treatment.illcode = illness.illcodeAND treatment.drugcode = prescription.drugcodeORDER BY physname;
(It CAN get involved)
CIS4365: Professor Kirs Slide Number: 73
SQL
Database Queries This command might yield the outcome:
physname patient.name illness.name prescription.drugcode------------- ----------------- ---------------- -----------------------------Bush Iman Beauty S228C99 Clinton Lewinski Sore throat L001H98Clinton Flowers Humiliation J897T11 Guilianni Clinton Humiliation A345B23Jones Richardson Depression J897T11Jones Vonnegut Writersblk K980F66Smith Gore Dullness A345B23 Smith Bradley Tallness S228C99Smith Beethoven Deafness A345B23Smith Aikman Sore Arm A345B23Smith Bradley Tallness A345B23Smith Gore Euphoria S228C99 Smith Astaire Brk Leg A345B23
CIS4365: Professor Kirs Slide Number: 74
SQL
Database Queries
The head administrator wants a list of all of Dr. Smith’s patients, their illnesses, and what prescriptions were given to those people.
NOWNOW, remember our original Concern:
Let’s assume that we had a field in our prescription table called drugname (for the name of the drug).
Our command might be:SELECT physname, patient.name, illness.name,
prescription.drugnameFROM physician, patient, treatment, illness, prescriptionWHERE physician.physid = patient.physidAND patient.patid = treatment.patidAND treatment.illcode = illness.illcodeAND treatment.drugcode = prescription.drugcodeAND physid = ‘123456789’;
CIS4365: Professor Kirs Slide Number: 75
SQL
Database Queries This command might yield the outcome:
physname patient.name illness.name prescription.drugname------------- ----------------- ---------------- ------------------------------Smith Gore Dullness Thorazine Smith Bradley Tallness AspirinSmith Beethoven Deafness ThorazineSmith Aikman Sore Arm Thorazine Smith Bradley Tallness ThorazineSmith Gore Euphoria Aspirin Smith Astaire Brk Leg Thorazine
And Maybe the Administrator DOESDOES have a valid concern
CIS4365: Professor Kirs Slide Number: 76
SQL
Database Queries If we wanted to get fancier, we might issue the
command:
SELECT physname, patient.name, illness.name, prescription.drugname
FROM physician, patient, treatment, illness, prescriptionWHERE physician.physid = patient.physidAND patient.patid = treatment.patidAND treatment.illcode = illness.illcodeAND treatment.drugcode = prescription.drugcodeAND physid = ‘123456789’ORDER BY COUNT (prescription.drugname, patient.name);
CIS4365: Professor Kirs Slide Number: 77
SQL
Database Queries This command might yield the outcome:
physname patient.name illness.name prescription.drugname------------- ----------------- ---------------- ------------------------------Smith Aikman Sore Arm Thorazine Smith Astaire Brk Leg Thorazine Smith Beethoven Deafness Thorazine Smith Bradley Tallness ThorazineSmith Gore Dullness Thorazine Smith Bradley Tallness AspirinSmith Gore Euphoria Aspirin
CIS4365: Professor Kirs Slide Number: 78
SQL
Database Queries Notice that our queries can become complex, and that
reentering the command each time becomes tedious
We can create permanent VIEWS• A VIEW is a logical table (NOT physical) which
contains a query
• A VIEW holds the query commands and is run each time it is called
• A VIEW must be CREATEd and selected when to be run
CIS4365: Professor Kirs Slide Number: 79
SQL
Database Queries To create our view:
CREATE VIEW drugs_given ASSELECT physname, patient.name, illness.name,
prescription.drugcodeFROM physician, patient, treatment, illness, prescriptionWHERE physician.physid = patient.physidAND patient.patid = treatment.patidAND treatment.illcode = illness.illcodeAND treatment.drugcode = prescription.drugcodeORDER BY physname;
CIS4365: Professor Kirs Slide Number: 80
SQL
Database Queries To run our view:
SELECT *FROM drugs_given WHERE physid = ‘123456789’ORDER BY COUNT (prescription.drugname), patient.name;
physname patient.name illness.name prescription.drugname------------- ----------------- ---------------- ------------------------------Smith Aikman Sore Arm Thorazine Smith Astaire Brk Leg Thorazine Smith Beethoven Deafness Thorazine Smith Bradley Tallness ThorazineSmith Gore Dullness Thorazine Smith Bradley Tallness AspirinSmith Gore Euphoria Aspirin
This might again result in the (approximate) display:
Recommended