23
An Introduction to An Introduction to Structured Query Structured Query Language Language (SQL) (SQL) John H. Porter John H. Porter University of Virginia University of Virginia Department of Environmental Sciences Department of Environmental Sciences

An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Embed Size (px)

Citation preview

Page 1: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

An Introduction to An Introduction to Structured Query LanguageStructured Query Language

(SQL)(SQL)John H. Porter John H. Porter University of VirginiaUniversity of Virginia

Department of Environmental SciencesDepartment of Environmental Sciences

Page 2: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Why use SQL?Why use SQL?

Provides the tools needed to manage Provides the tools needed to manage relational databases including:relational databases including:• Creating TablesCreating Tables• Adding DataAdding Data• Queries / SearchesQueries / Searches

It’s a STANDARD! – multiple vendors It’s a STANDARD! – multiple vendors produce products that support SQL produce products that support SQL queriesqueries

Page 3: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Standards – A CaveatStandards – A Caveat

Just because there are standards for Just because there are standards for SQL implementations does not mean SQL implementations does not mean that all databases will have all the that all databases will have all the capabilities in the SQL standard.capabilities in the SQL standard.

Most relational databases implement Most relational databases implement some non-standard extensions or lack some non-standard extensions or lack some features of the full standardsome features of the full standard

Page 4: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Examples of VariationExamples of Variation

MiniSQL - implements only a critical MiniSQL - implements only a critical subset of SQL commandssubset of SQL commands

MySQL – fairly compatible - no sub-MySQL – fairly compatible - no sub-selects (nested selects)selects (nested selects)

Postgres – not fully standardized, object Postgres – not fully standardized, object extensionsextensions

““The wonderful thing about standards is The wonderful thing about standards is that there are so many of them to that there are so many of them to choose from”choose from” - anonymous- anonymous

Page 5: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Critical SQL CommandsCritical SQL Commands

Table ManagementTable Management• Create TableCreate Table• Drop TableDrop Table

EditingEditing• InsertInsert• UpdateUpdate• DeleteDelete

QueryQuery• SelectSelect

Page 6: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Create TableCreate Table

CREATE TABLE mytable (CREATE TABLE mytable (name CHAR(40) NOT NULL, name CHAR(40) NOT NULL, age INTage INT)) Creates a table named “mytable” with Creates a table named “mytable” with

two fields two fields • A required character field called “name”A required character field called “name”• An optional numeric (integer) field called An optional numeric (integer) field called

“age”“age”

Page 7: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

InsertInsert

INSERT INTO mytable (name, age)INSERT INTO mytable (name, age)

VALUES (’George’,20) VALUES (’George’,20) Inserts a data row into the table Inserts a data row into the table

• ““name” is set to “George”name” is set to “George”• ““age” is set to 20age” is set to 20

Page 8: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

SelectSelect

SELECT name,age FROM mytable WHERE SELECT name,age FROM mytable WHERE

age = 20 age = 20 Searches the table for rows where “age” is 20 Searches the table for rows where “age” is 20

and returns the associated name and age. and returns the associated name and age. This query resulted in: This query resulted in:

+--------+------++--------+------+

| name | age || name | age |

+--------+------++--------+------+

| George | 20 || George | 20 |

+--------+------++--------+------+

1 row in set (0.02 sec)1 row in set (0.02 sec)

Page 9: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

UpdateUpdate

UPDATE mytable SET age=21 WHERE UPDATE mytable SET age=21 WHERE name LIKE ’George’ name LIKE ’George’

Searches the table for rows where “name” is Searches the table for rows where “name” is “George” and sets age to 21. “George” and sets age to 21. Note: if we had more Note: if we had more than one row with name “George” than one row with name “George” all all would be set to age=21. would be set to age=21.

+--------+------++--------+------+

| name | age || name | age |

+--------+------++--------+------+

| George | 21 || George | 21 |

+--------+------++--------+------+

1 row in set (0.02 sec)1 row in set (0.02 sec)

Page 10: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Delete (a row from a table)Delete (a row from a table)

DELETE FROM mytable WHERE name DELETE FROM mytable WHERE name LIKE ’George’AND age = 21 LIKE ’George’AND age = 21

Searches the table for rows where Searches the table for rows where “name” is “George” and age is 21 and “name” is “George” and age is 21 and deletes themdeletes them

Page 11: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Drop Table (delete a table)Drop Table (delete a table)

DROP TABLE mytableDROP TABLE mytable Completely eliminates table “mytable.” Completely eliminates table “mytable.”

All data in the table is lost. All data in the table is lost.

Page 12: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Putting the Relations in Putting the Relations in Relational DatabaseRelational Database

SELECT statements are not restricted to SELECT statements are not restricted to single tables. For example:single tables. For example:

SELECT DISTINCTSELECT DISTINCT

mytable.age, yourtable.address mytable.age, yourtable.address

FROM mytable, yourtable FROM mytable, yourtable

WHERE mytable.name LIKE WHERE mytable.name LIKE yourtable.nameyourtable.name

Page 13: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Relational SELECTRelational SELECT

SELECT DISTINCTSELECT DISTINCTmytable.age, yourtable.address mytable.age, yourtable.address FROM mytable, yourtable FROM mytable, yourtable WHERE mytable.name LIKE yourtable.nameWHERE mytable.name LIKE yourtable.name Accesses two different tables: “mytable” and Accesses two different tables: “mytable” and

“yourtable”“yourtable” Returns “age” from mytable, and “address” Returns “age” from mytable, and “address”

from yourtable where the “name” field in the from yourtable where the “name” field in the two tables match. two tables match.

DISTINCT means that if the same age and DISTINCT means that if the same age and address shows up in multiple rows, only the address shows up in multiple rows, only the first instance will be displayed.first instance will be displayed.

Page 14: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Why SQL?Why SQL?

Despite its power to manipulate data, Despite its power to manipulate data, SQL makes a poor user interfaceSQL makes a poor user interface• Few ecologists will want to take the time to Few ecologists will want to take the time to

learn SQLlearn SQL• Effective use also requires knowledge of Effective use also requires knowledge of

the underlying fields and tablesthe underlying fields and tables For this reason, most SQL is imbedded For this reason, most SQL is imbedded

into programs where it is hidden from into programs where it is hidden from the usersthe users

Page 15: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Example ProgramExample Program

This example program uses PHP to talk This example program uses PHP to talk to a MYSQL relational databaseto a MYSQL relational database

The details of each step will differ The details of each step will differ between databases and languages, but between databases and languages, but will share many similaritieswill share many similarities

Here we insert information from a web Here we insert information from a web form into a database and retrieve an form into a database and retrieve an observation number for later use. observation number for later use.

Page 16: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Steps in a PHP ProgramSteps in a PHP Program

Make a Connection to the database serverMake a Connection to the database server

$link = $link = mysql_connect("data.vcrlter.virginia.edu“, mysql_connect("data.vcrlter.virginia.edu“, “myID") or die("Could not connect");“myID") or die("Could not connect");

Select the Database on that server to useSelect the Database on that server to use

mysql_select_db("www") or die("Could not mysql_select_db("www") or die("Could not select database");select database");

Page 17: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Steps in a ProgramSteps in a Program Prepare a query (here an INSERT Prepare a query (here an INSERT

statement) for execution:statement) for execution:$query = "insert into waiver $query = "insert into waiver (date_req,station,name,isVert,healthtype) (date_req,station,name,isVert,healthtype)

values('" . date("Y-m-d") . ”’, values('" . date("Y-m-d") . ”’, ‘ ‘$_REQUEST[station]',$_REQUEST[station]', ‘ ‘$_REQUEST[fullname]',$_REQUEST[fullname]', 'Y', 'Y', $_REQUEST[health])"; $_REQUEST[health])";

Note: Note: $_REQUEST[]$_REQUEST[] is a PHP function that gives you access is a PHP function that gives you access to fields from a WWW form. to fields from a WWW form. DateDate is a function that returns is a function that returns the current date in the format specifiedthe current date in the format specified

Page 18: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Steps in a ProgramSteps in a Program

Run the query we stored earlier:Run the query we stored earlier:

$result = mysql_query($query) or $result = mysql_query($query) or die("Unable to log waiver creation, die("Unable to log waiver creation, Query failed");Query failed");

Page 19: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Steps in a ProgramSteps in a Program

Prepare and run a query to get a copy Prepare and run a query to get a copy of the “waiver_num” value. Here we use of the “waiver_num” value. Here we use the MYSQL “max” function to return the the MYSQL “max” function to return the highest value of waiver_numhighest value of waiver_num

$query = "select max(waiver_num) as $query = "select max(waiver_num) as waiver_num from waiver";waiver_num from waiver";

$result = mysql_query($query) or die("Unable $result = mysql_query($query) or die("Unable to get waiver number, Query failed");to get waiver number, Query failed");

Page 20: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Steps in a ProgramSteps in a Program

Convert the $result of the query into Convert the $result of the query into variables that PHP can usevariables that PHP can use

This creates the variable $waiver_num This creates the variable $waiver_num for use in PHP programsfor use in PHP programs

extract(mysql_fetch_assoc($result));extract(mysql_fetch_assoc($result));

Page 21: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

Steps in ProgramSteps in Program

Close our link to the MYSQL serverClose our link to the MYSQL server

mysql_close($link);mysql_close($link);

Page 22: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

/* Connecting, selecting database *//* Connecting, selecting database */ $link = mysql_connect("data.vcrlter.virginia.edu", “myID")$link = mysql_connect("data.vcrlter.virginia.edu", “myID") or die("Could not connect");or die("Could not connect"); mysql_select_db("www") or die("Could not select mysql_select_db("www") or die("Could not select database");database");

/* Performing SQL query *//* Performing SQL query */$query = "insert into waiver $query = "insert into waiver (date_req,station,name,isVert,healthtype) (date_req,station,name,isVert,healthtype) values('" . date("Y-m-d") . ','$_REQUEST[station]', values('" . date("Y-m-d") . ','$_REQUEST[station]', ‘$_REQUEST[fullname]','Y', $_REQUEST[health])"; ‘$_REQUEST[fullname]','Y', $_REQUEST[health])";

$result = mysql_query($query) or die("Unable to log waiver $result = mysql_query($query) or die("Unable to log waiver creation, Query failed");creation, Query failed");

$query = "select max(waiver_num) as waiver_num from $query = "select max(waiver_num) as waiver_num from waiver";waiver";$result = mysql_query($query) or die("Unable to get waiver $result = mysql_query($query) or die("Unable to get waiver number, Query failed");number, Query failed");extract(mysql_fetch_assoc($result));extract(mysql_fetch_assoc($result)); mysql_close($link);mysql_close($link);

Open Open connectionconnection

Set up Set up insertinsert

Store result Store result as PHP as PHP variablevariable

Select Select databasedatabase

Run Insert Run Insert QueryQuery

Set up querySet up query

Run QueryRun Query

Page 23: An Introduction to Structured Query Language (SQL) John H. Porter University of Virginia Department of Environmental Sciences

SQL ExerciseSQL Exercise

Now it’s time for you to try out your SQL Now it’s time for you to try out your SQL skills using the web pages:skills using the web pages:

http://www.sqlcourse.com/http://www.sqlcourse.com/• Do allDo all

http://www.sqlcourse2.comhttp://www.sqlcourse2.com• Do part 10 (table joins)Do part 10 (table joins)