You are on page 1of 4

SQL CHEAT SHEET SQL is a universal programming language for interaction with databases.

All statements here are designed to comply with SQL-89 and SQL-92, the 2 most common standards. Not all databases entirely comply with all standards, so be prepared to check for differences in the reference material for the DB you are using. These statements are an attempt to provide quick reference to common statements needed in web programming. All control words (SQL specific) are capitalized for your reference. In general, SQL is not case sensitive for the control words (SELECT, DROP, UPDATE, etc.) and many DBs are not case sensitive for the table and field names, but your results may vary. A good convention is to upper case all control words, and match the case of all field names and table names, etc. Note that the cheat sheet is designed after a single database, and uses an apparel model, so we can work in more complicated issues like sizes, colors and quantities in stock. Where more than one table is involved in an SQL statement, you may see the dot convention used. This means if I have a table tblCustomers and I want to access the last name for that field specifically, I would call out: tblCustomers.FirstName This is optional when you are working with only one table. String values all are contained in single quotes. Numbers that are DECLARED as numbers in the database cannot have quotes. The databases are ENTIRELY unforgiving on this point! All statements use the following tables and field names. All items are of string type, except as noted: tblCustomers CustomerID LastName FirstName Gender Address City State ZipCode Email CustPW tblClothing ClothingID Item Description Price (float) Colors Sizes Category Stock(int) tblOrders OrderID CustomerID DetailID Total OFirstName OLastName OAddress OCity OState OZipCode tblDetail DetailID OrderID ClothingID Size Color Quantity Dprice (float)

SELECT STATEMENTS Select statements enable us to view tables or selected records and selected fields in a table or tables. To show all fields in a table, all Customers: SELECT * FROM tblCustomers To show only particular fields from a table, but all Customers:

SELECT FirstName, LastName FROM tblCustomers To show only particular fields from a table, one customer: SELECT FirstName, LastName FROM tblCustomers WHERE CustomerID = 4 To show all items in a particular clothing category: SELECT * FROM tblClothing WHERE Category = 'Shoes' To select all BUT shoes: SELECT * FROM tblClothing WHERE NOT Category = 'Shoes' To select from a number of categories, (but not every category, use the "in" statement: SELECT * FROM tblClothing WHERE Category IN ('Shoes', 'Shirts', 'Shorts','Jeans') To select each category INDIVIDUALLY from a "Categories" field, use DISTINCT. (NOTE: This is good for creating a drop down box populated with one instance of each category) SELECT DISTINCT Category FROM tblClothing To show the clothing items that are critically low in stock: SELECT ClothingID FROM tblClothing WHERE Stock < 10 To show clothing items where there are between 20 and 200 in stock: SELECT ClothingID, Item FROM tblClothing WHERE (Stock >= 20) AND (Stock <=200) The previous statement can be done also with the BETWEEN statement: SELECT Stock, ClothingID, Item FROM tblClothing WHERE Stock BETWEEN 19 AND 201 The BETWEEN statement can also be used with non-numerical data, for example, a zip code: SELECT ZipCode, CustomerID, FirstName, LastName FROM tblCustomers WHERE ZipCode BETWEEN '60000' AND '99999' Where statements can string together different requirements. Here is for a listing of all male customers in WA: SELECT CustomerID, FirstName, LastName FROM tblCustomers WHERE State = 'WA' AND Gender = "M" Here is a statement using OR. It will pick up all customers in Seattle or Bellevue: SELECT CustomerID, FirstName, LastName FROM tblCustomers WHERE City = "Seattle" OR City = "Bellevue" When AND combines with OR, AND always takes precedence. Therefore, it is best to separate your logic with parens. Here is the previous statement for a customer in Seattle or Bellevue, but only Female:

SELECT CustomerID, FirstName, LastName FROM tblCustomers WHERE (City = "Seattle" OR City = "Bellevue") AND Gender = 'F' Use LIKE to find all values that have a partial match. Here is how to search for all customers whose last names begin with "new". Note the percent sign represents any number of characters SELECT FirstName, LastName FROM tblCustomers WHERE LastName LIKE 'new%' Use the UNDERSCORE symbol to search for a value that has only one character to match. Here is a search for an order To find a maximum value, for example, the highest priced item for sale: SELECT MAX(Price) FROM tblClothing Similarly, here is how to find the lowest priced item: SELECT MIN(Price) FROM tblClothing We could limit our search to find the highest priced shoe: SELECT MAX(Price) FROM tblClothing WHERE Category = 'Shoes' NOTE: This does not allow us to get the ClothingID, just the actual value. To get the ClothingID we would have to nest another query inside of the first query. Here is an example where we want to find out the ClothingID of the highest priced shoe. First the nested query returns the price of the highest priced shoe. Then the outer query returns the Clothing ID. The process of nesting queries is called using a SUBQUERY. Since this is in effect 2 queries, it could be slower to get the data then to do your work in just one query. ORDER BY You can choose how the items displayed are ordered by using the SQL statement ORDER BY: SELECT FirstName, LastName FROM tblCustomers ORDER BY LastName ASC This will display the first and last name of customers ordered by the last name. ASC (ascending) is the default, so if you did not put ASC, it would work the same way. To find the most recently added piece of clothing in the clothing table, you would sort the table in a descending manner: SELECT ClothingID from tblClothing ORDER BY ClothingID DESC Note that since the clothing ID last created MUST be the most recent one, this will pull up the most recent item entered into this table. SORTING BY MORE THAN ONE FIELD If You have a number of items you are sorting for that are spelled the same, you can sort the matching items by the second field named on the ORDER BY: SELECT Clothing, Category from tblClothing ORDER BY Category, Clothing DESC This will group all the same category items, and then sub-sort them on the second field, Clothing. COMPOUND SELECT STATEMENTS

We can combine all the SQL statements we have learned into complicated statements. What if I want Shoes costing Less than $35, sorted by the price ascending, then the category: SELECT Clothing, Category Price from tblClothing WHERE PRICE < 35 ORDER BY Price, Category DESC ADDING ARITHMETIC TO YOUR STATEMENTS We can perform rudimentary arithmetic right in our SQL statements. To do so, we need to create an ALIAS, for the new column so created, since it is not exactly the same column as it was before we performed our math. This can be useful if we want to add sales tax to a Price right out of the database: SELECT Price * 1.086 AS TaxPrice FROM tblClothing "TaxPrice" in this case is the ALIAS for the new field created. Be careful that math can only be performed on numeric values. The alias TaxPrice is now the field name we need to reference. Note that this does not change the data in the database, just the info that is presented! JOINING TABLES If you connect your like keys (Foreign and Primarys) you are said to be joining tables. With Joins, you can get at the data you need across multiple tables, and just narrow it down to the data you need. To show all orders (and some order details) for Customer whose ID is number 1: SELECT tblOrders.OrderID, Color, Size, Item, FirstName, LastName FROM tblOrders, tblDetail, tblCustomers, tblClothing where tblDetail.OrderID=tblOrders.OrderID and tblClothing.ClothingID=tblDetail.ClothingID and tblOrders.CustomerID=tblCustomers.CustomerID and tblCustomers.CustomerID = 1 Here is the same customer, only narrowing the field further to only the single order: SELECT tblOrders.OrderID, Color, Size, Item, FirstName, LastName FROM tblOrders, tblDetail, tblCustomers, tblClothing where tblDetail.OrderID=tblOrders.OrderID and tblClothing.ClothingID=tblDetail.ClothingID and tblOrders.CustomerID=tblCustomers.CustomerID and tblCustomers.CustomerID = 1 and tblOrders.OrderID = 1 While this is complicated, you can use this as a template to get similar data from your tables. Try out the SQL tester online at: http://zephir.seattlecentral.edu/~bnewman/examples/editTable8.php

You might also like