SQL (Structured Query Language)
SQL (Structured Query Language)
SQL is a language designed to work with relational databases In the mid 1970s, SQL was developed under the name SEQUEL (for Structured English Query Language?) at the IBM San Jose research facilities to be the data manipulation language for IBM's prototype relational model DBMS called "System R". In 1980, the language was renamed SQL to avoid confusion with an unrelated hardware product called SEQUEL. SQL is currently used (and has been for quite some time) as the data manipulation language for most relational database management products on the market today. This includes IBM's DB2, Oracle, XBase (dBase, FoxPro, etc.), MS SQL Server, and Access.
Mwangi H. 1
SQL
On its own, SQL is a "non-procedural" language, meaning a program is not typically written in "straight SQL". SQL accomplishes many powerful tasks with a mere seven statements: SELECT, UPDATE, INSERT, DELETE, CREATE, ALTER, and DROP. Each of these seven statements fall into one of two categories: DML (Data Manipulation Language) statements or DDL (Data Definition Language) statements. These statements are summarized as follows:
Mwangi H. 2
DML Statements
SELECT Enables you to select one or more columns from one or more tables in the database. The results can be simply viewed, or can be used as the basis for a form or report, or, in the case of embedded SQL, can be processed as a temporary table (called a "recordset" in Access, called a "cursor" in other DBMSs).
UPDATE Enables you to update the data in one or more columns of one or more rows in a table.
DDL Statements
CREATE Enables you to create a new table, or to create a new index on an existing table.
ALTER Enables you to modify the structure of an existing table (by adding or deleting columns). DROP Enables you to delete a table
Mwangi H.
Example
Mwangi H.
The SELECT query retrieves one or more columns (fields) from a table. The basic syntax is:
SELECT field1 [, field2, ... fieldn] FROM tablename Notes: If more than one field is specified, each field must be separated with a comma. If you want to select ALL fields from a table, you can use an asterisk (*) instead of a list of all the fields.
Mwangi H. 6
Example 1:
Retrieve all columns and all rows from the Employees table.
SELECT * FROM EMPLOPYEES
Mwangi H.
Example 2:
Retrieve the Product ID, product name, and unit price from all rows of the Products table: SELECT ProductID, ProductName, UnitPrice FROM Products
Mwangi H.
By adding an appropriate WHERE clause to a SELECT statement, you can limit the number of rows (records) returned by the query. The WHERE clause specifies a condition that must be met in order for that row be returned.
Note: In the WHERE clause, numeric literals have no delimiters, string literals are delimited by single quotes (') (although Access will also accept double quotes(")), and date delimiters are delimited by the number sign (#). Delimiting dates with the number sign is specific to Access; most other DBMS' use the single quote as the date delimiter.
Mwangi H. 9
Example 3:
Mwangi H.
10
Example 4:
Which customers are from Mexico? (Show Customer ID, company name, contact name, and contact title in the results.) SELECT CustomerID, CompanyName, ContactName, ContactTitle FROM Customers WHERE Country = 'Mexico'
Mwangi H.
11
Example 5:
Which employees were hired on October 17, 1993? (Show employee first and last name, and title in the results.)
Mwangi H.
12
Which meat/poultry products (CategoryID = 6) have less than 10 units in stock? (Show product ID, product name, category ID, and units in stock in the results.)
SELECT ProductID, ProductName,CategoryID, UnitsInStock FROM Products WHERE CategoryID = 6 AND UnitsInStock < 10
Mwangi H. 13
Example 7:
Which items in the Product table are classified as meat/poultry or have less than 10 units in stock? (Show product ID, product name, category ID, and units in stock in the results.)
SELECT ProductID, ProductName, CategoryID, UnitsInStock FROM Products WHERE CategoryID = 6 OR UnitsInStock < 10
Mwangi H.
14
Example 8:
Show the product name, units in stock, category ID, and unit price for seafood products (category ID = 8) that have at least 100 units in stock, or for any item whose unit price is greater than $50.
SELECT ProductName, UnitsInStock, CategoryID, UnitPrice FROM Products WHERE UnitsInStock >= 100 AND CategoryID = 8 OR UnitPrice > 50
Mwangi H. 15
Example 9:
Show the part product name, units in stock, category ID, and unit price for products that have at least 100 units in stock, and that are either classified as seafood (category ID = 8) or have a unit price greater than $50.
SELECT ProductName, UnitsInStock, CategoryID, UnitPrice FROM Products WHERE UnitsInStock >= 100 AND (CategoryID = 8 OR UnitPrice > 50)
Mwangi H. 16
Example 10:
Show the company name, contact name, and country for all non-US suppliers.
Mwangi H.
17
Show the Product ID, product name, and unit price for all products that have a unit price between $10 and $15 (inclusive):
SELECT ProductID, ProductName,UnitPrice FROM Products WHERE UnitPrice BETWEEN 10 AND 15 This query could also be coded as:
SELECT ProductID, ProductName, UnitPrice FROM Products WHERE UnitPrice >= 10 AND UnitPrice <= 15
Tuesday, June 05, 2007 Mwangi H. 18
Example 12:
Show the Order ID, Customer ID, and order date for orders that occurred between February 1 and February 7, 1995.
SELECT OrderID, CustomerID, OrderDate FROM Orders WHERE OrderDate BETWEEN #2/1/1995# AND #2/7/1995#
Mwangi H.
19
Reminder:
In Access SQL, Date literals must be delimited by pound signs (#). In most other database systems, dates are delimited with single quotes (same as strings). Also: Queries based on dates become slighltly more involved if the dates have a time component to them (the dates in this database do not have a time component, but they could, because Date/Time fields can store both date and time together). If the OrderDate field contained a time component, you would have to write the WHERE clause of the above query like this:
WHERE OrderDate BETWEEN #2/1/1995# AND #2/7/1995 11:59:59PM# - or WHERE OrderDate >= #2/1/1995# AND OrderDate < #2/8/1995#
Tuesday, June 05, 2007 Mwangi H. 20
Show the OrderID, ProductID, UnitPrice, Quantity, Discount, and line item total for order line items that total at least $300. SELECT OrderID, ProductID, UnitPrice, Quantity, Discount, (UnitPrice * Quantity * (1 - Discount)) as TotalPrice FROM [Order Details] WHERE (UnitPrice * Quantity * (1 Discount)) >= 300
Mwangi H. 21
Mwangi H.
22
Show company name, contact name, and title for customers whose contact person is considered a "manager".
SELECT CompanyName, ContactName, ContactTitle FROM Customers WHERE ContactTitle LIKE %Manager%'
Mwangi H.
23
Mwangi H.
24
Show company name and address information for all suppliers located in France, Germany, and Italy.
SELECT CompanyName, Address, City, Country, PostalCode FROM Suppliers WHERE Country IN ('France', 'Germany', 'Italy')
Mwangi H. 25
Mwangi H.
26
or
SELECT CompanyName, Address, City, Country, PostalCode FROM Suppliers WHERE Country = 'France' OR Country = 'Germany' OR Country = 'Italy'
Mwangi H.
27
Show the category ID, unit price, and product name for all products, sorted by unit price (low to high).
Mwangi H.
28
Mwangi H.
29
Example 17
Show the category ID, unit price, and product name for all products, sorted by unit price (high to low).
Mwangi H.
30
The COUNT function in a SELECT statement returns a count of the number of records in a table (if the statement has a WHERE clause, it returns only the number of records that meet the specified condition).
How many products are classified as beverages (category ID 1)? SELECT COUNT(*) AS BeverageCount FROM Products WHERE CategoryID = 1
Mwangi H. 31
The SUM function in a SELECT statement returns the sum of a numeric field or expression for all of records in a table (if the statement has a WHERE clause, it sums that field only for the records that meet the specified condition).
How many order lines do we have, and what is their total value? SELECT COUNT(*) AS OrderLineCount, SUM(UnitPrice * Quantity * (1 + Discount)) AS OrderLineTotal FROM [Order Details]
Mwangi H.
32
Using DISTINCT
Use the DISTINCT keyword to show each customer in the ORDERS table only once
SELECT DISTINCT CustomerID FROM Orders
Mwangi H.
33
When you group data, you create a query that produces one record for each unique value of a field (or combination of fields) in a table (limited by the WHERE clause, if there is one). Any of the SQL functions discussed earlier (COUNT, SUM, AVG, etc.) apply to the grouped record.
Show the order ID and order total for each order. SELECT OrderID, SUM(UnitPrice * Quantity * (1 + Discount)) AS OrderTotal FROM [Order Details] GROUP BY OrderID
Mwangi H.
34
Mwangi H.
35