SQL by Example

This page presents simple examples that illustrate major features of SQL. Please report any errors that you encounter.

Using Access to build SQL statements

Writing SQL statements is difficult for the beginner. A fairly easy way to get started is to use MS Access to build the query in design mode and then to switch to SQL mode to see the actual statement. Sometimes it is necessary to simplify the resulting SQL statement by removing unnecessary parentheses before using the statement in an ODBC context. Other minor adjustments are sometimes necessary as well, such as replacing the word "LIKE" with "=". Finally, SQL statements built in Access are usually overqualified in the sense that every field name is preceded by a table name, even when doing so is unnecessary.

Common operators

=   <>   <   <=   >   >=
AND   OR   NOT

The database tables

Products (ProductID, ProductName, UnitPrice, CategoryID, LastPurchaseDate)

ProductID text (key) 
ProductName text
UnitPrice currency
CategoryID integer
LastPurchaseDate date

Orders (OrderID, ProductID, CustomerID, Quantity, PurchaseDate)

OrderID auto number (key)
ProductID text (foreign key)
CustomerID text (foreign key)
Quantity integer
PurchaseDate date

SELECT statements

SELECT * FROM Products;
SELECT ProductID, UnitPrice FROM Products;

WHERE clause

SELECT * FROM Products WHERE CategoryID = 1;
SELECT * FROM Products WHERE LastPurchaseDate > #01/01/2000#;
SELECT * FROM Products WHERE ProductName = 'Potato Chips';
SELECT * FROM Products WHERE CategoryID = 1 AND UnitPrice < 5.00;

ORDER BY clause

SELECT * FROM Products ORDER BY UnitPrice ASC;
SELECT * FROM Products ORDER BY CategoryID ASC, UnitPrice DESC;
SELECT * FROM Products WHERE UnitPrice > 5.00 
                       ORDER BY CategoryID ASC, UnitPrice DESC;

Joining tables

SELECT * FROM Products, Orders;
SELECT Products.ProductID, Products.ProductName, Orders.Quantity 
       FROM Products, Orders WHERE Products.ProductID = Orders.ProductID;

INSERT statement

INSERT INTO 
    Products (ProductID, ProductName, UnitPrice, CategoryID, LastPurchaseDate)
    VALUES ('PC101, 'Potato Chips', 1.79, 1, #02/17/2000#);
INSERT INTO 
    Orders (ProductID, CustomerID, Quantity, PurchaseDate)
    VALUES ('PC101', 'BS451', 20, #02/17/2000#);

UPDATE statement

UPDATE Products 
    SET ProductName = 'Big Potato Chips', UnitPrice = 2.69
    WHERE ProductID = 'PC101';
UPDATE Products 
    SET UnitPrice = UnitPrice * 1.1
    WHERE UnitPrice > 5.00;

DELETE statement

DELETE * FROM Products WHERE LastPurchaseDate <= #12/25/1999#;

Aggregation functions

SELECT COUNT(ProductID) AS CountOfProductID
    FROM Products
    WHERE UnitPric > 5.00;
SELECT ProductID, Sum(Quantity) AS SumOfQuantity
    FROM Orders
    GROUP BY ProductID;