Introduction To Structured Query Language (SQL) - Part 1 PDF
Introduction To Structured Query Language (SQL) - Part 1 PDF
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html 1/14
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
Topics
SQL commands:
References:
Online tutorials:
– SQL Tutorial: http://www.w3schools.com/sql/default.asp (No exercises but includes a quiz; quite a few
and animated text.)
General, online:
– Learning Guide: SQL: http://searchdatabase.techtarget.com/orginalContent/0,289142,sid13_gci950920,00.
(Eight chapters, from basic to advanced; may have to register (free) to use - and receive e-mail newslet
)
General, books:
– The Practical SQL Handbook, 4th Ed., Judith Bowman, Sandra Emerson, and Marcy Darnovsky; Addison
Wesley
– SQL in a Nutshell, Kevin Kline; O’Reilly
– SQL for Smarties, 2nd Ed., Joe Celko; Morgan Kaufmann
Database-specific:
– Oracle: http://otn.oracle.com
– MySQL: http://www.mysql.com/documentation/mysql/bychapter/
Tutorial: http://www.mysql.com/documentation/mysql/bychapter/manual_Tutorial.html#Tutorial
Online glossary
:
– http://www.prenhall.com/divisions/bp/app/mcfadden/student/glossaryfull.html
Relational databases
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html
Example: 2/14
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
(NOTE: For practice on your own computer, make a copy of the Northwind database before starting; or start
blank new database and import the Northwind tables you need.)
Referential integrity constraints: Primary / foreign key relationships or rules defined using SQL or vendor extensions t
ensure data integrity and consistency throughout all tables in the database.
– Used by the database system internally and by users to manipulate and query the data.
– Uses set theory (as opposed to row processing) to process requests.
– Limited but flexible set of commands.
– Free-form, uses semi-colon as statement terminator in most databases.
CREATE
ALTER
DROP
INSERT
UPDATE
DELETE
SELECT
– Data control language (DCL) - control user access (e.g., GRANT, REVOKE)
One of the DML commands, used for retrieving specific data from one or more tables, reporting calculated results bas
on the data retrieved, or displaying the results of “what if?” type calculations.
Example:
SELECT *
FROM Categories
2. View the results without saving by clicking the View button (switches to Datasheet view).
3. Change back to SQL view and run the statement by clicking the Run ( ! ) button.
Exercise: Create a phone list of customer contacts (just company and contact names with phone and FAX numbers)
sorted by company name.
2. View the results; then run and save the query as AllCustomers. You should see 91 customers.
3. Modify the list to include only customers from the United Kingdom and at the same time, change the first two colum
headers to Company and Customer:
4. View the results; then run and save the query as UKCustomers (7 customers)
SELECT: Syntax
In (list)
WHERE State IN (“OR”, “WA”, “CA”)
Is [not] null
Exercise: Create alphabetically sorted product lists showing product name (ProductName), supplier (SupplierID), an
price (UnitPrice) for the following:
Exercise: Modify the AllCustomers phone list to make separate lists for customers with and without an assigned reg
(two separate queries). Use is null or is not null to make the distinction.
SELECT: Syntax
In (list)
WHERE State IN (“OR”, “WA”, “CA”)
Exercise: Create alphabetically sorted product lists showing product name (ProductName), supplier (SupplierID), an
price (UnitPrice) for the following:
Exercise: Modify the AllCustomers phone list to make separate lists for customers with and without an assigned reg
(two separate queries). Use is null or is not null to make the distinction.
CREATE
Also available in other database systems: CREATE trigger, procedure, function, role, user)
CREATE TABLE
=========
Example:
Timestamp
Interval
Enum
Set
3. Select each field and notice its properties in the Field Properties grid.
describe tablename
and select [properties] from [system tables]
Exercise: Create a table to store personnel data, with a StaffID column as primary key
2. Execute the statement. If Access reports syntax errors, find and correct them.
The query returns one blank record (in other databases: 0 rows). Close the query.
4. Open the new table in datasheet view – it is empty and ready for data entry.
6. Choose View / Indexes and compare with the constraint created on StaffID.
3. Change to SQL view (not Design view) and execute the statement. Click Yes when asked whether you want to
continue (only Access gives this kind of warning!).
5. Compare the new table with the original in Datasheet and Design view. What, if any, differences do you find?
Exercise: Create an extract of the Categories table without pictures and call it CategoriesNoPix.
(1. Optional: Open the Categories table in design view and note the field names. Close the table before running the
SELECT ... INTO ... FROM query.)
3. Switch to Datasheet View to see the results without executing the statement.
4. Switch to SQL view (not Design view) and execute the statement. Click Yes when asked about continuing.
Single-field constraint:
CONSTRAINT constraintname {
PRIMARY KEY |
UNIQUE |
NOT NULL |
REFERENCES foreigntablename [(foreigncol1, foreigncol2), ...]
}
Multifield constraint:
CONSTRAINT constraintname (
PRIMARY KEY (primary1, primary2 , ...) |
UNIQUE (unique1, unique2 , ...) |
NOT NULL (notnull1, notnull2 , ...) |
FOREIGN KEY (ref1, ref2 , ...) REFERENCES foreigntable (foreigncol1, foreigncol2, ...)
}
Used to create an index on an existing table. The ALTER TABLE statement can also be used to create (or drop) an in
on a table.
Uses (apart from speeding up searches in large tables and in multitable queries):
– PRIMARY uniquely identifies the row (UNIQUE and NOT NULL by definition)
– UNIQUE prevents entry of duplicate values
– DISALLOW NULLS prevents null values in the indexed field
Syntax
Exercise: Add a column to CategoriesNoPix for a short description and then remove it.
2. Execute the statement.. Open the table in Datasheet or Design view to check the results; close the table.
4. Save as "AddColCategoriesNoPix".
4. Without closing the SQL design window, change the statement to read
6. Save as "DropColCategoriesNoPix".
Exercise: Drop the referential integrity constraint on the Products table that does not allow a product to be added if it
not in an existing category; then
add the constraint back again.
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html 9/14
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
1. Open the Relationships window and note the relationship between Categories and Products. Close the Relationsh
window.
3. Execute the statement. Open the Relationships window and check the result.
6. Execute the statement. Open the Relationships window and check the result.
7. Save as “AddProductConstraint”.
Syntax:
DDL - DROP
Use DROP objectname to remove from the database any object that was CREATEd.
In MS Access, can only DROP tables and indexes.
Exercise: Remove the CategoriesNoPix table from the database - we no longer need it.
Syntax
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html 10/14
Data modification language statements (DML) INSERT, UPDATE, and DELETE
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
DML - INSERT
Use the INSERT command to enter data into a table. You may insert one row at a time, or select several rows from a
existing table and insert them all at once.
NOTE: Be sure to save the next three queries - you may need them again!
Exercise: Add two records to the Personnel table, one with all the data, the other with required columns only (two
separate queries). Try to add a third record using one of the StaffIDs already in the table. What happens? Use these
SQL statements for the first two staff members:
NOTE: Date/time data type delimited with # in Access; with quotes in other databases.
Exercise: Add several employees from the Northwind database to the Personnel table. Here is an SQL statement th
should add 5 staff members:
Syntax
Single-row INSERT:
Multi-row INSERT:
DML – UPDATE
Use the UPDATE statement to change data values in one or more columns, usually based on specific criteria.
Exercise: Assign suppliers from London and Manchester in the MySuppliers table to the UK region. Check the table
before and after running this update query:
UPDATE MySuppliers
SET Region = "UK"
WHERE City IN ("London", "Manchester");
Exercise: Where no region has been entered in the MySuppliers table, change the value to “Unassigned”. Check th
table before and after running the query:
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html 11/14
UPDATE MySuppliers
SET Region = "Unassigned"
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
Syntax
UPDATE tablename
SET col1 = value1, col2 = value2, ...
WHERE criteria
DML - DELETE
Check the Personnel table before and after running each of the following DELETE statements.
Exercise: Delete the Chemistry staff member from the Personnel table:
Syntax
NOTE: MS Access requires the * to designate all columns; other databases use DELETE FROM ...
– Click the SQL view button (leftmost button under the menu bar) or choose View / SQL View from the menu b
– In the window called "Query1: Select Query", type the SQL statement, replacing SELECT with the appropria
SQL
command. Be sure to keep the semi-colon statement terminator.
– To execute the command, click the Run button (!) or by choosing Query / Run from the menu bar. (Note: Fo
queries that modify data, you can usually see which records or how many records will be modified without act
executing the query by changing the "view" to Datasheet View: Use the View button or choose View / Datash
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html
============================================================================== 12/14
MS Access denotes DML statements as "action queries" and warns the user any time data will be modified.
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
Access may change the SQL in non-standard ways when you leave the SQL window.
This does not change how the statement works.
==============================================================================
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html 13/14
10/16/2020 Introduction To Structured Query Language (SQL) – Part 1
www1.udel.edu/evelyn/SQL-Class1/oSQLclass1All.html 14/14