Sunteți pe pagina 1din 10

Kimberley Poirier

MIS 3550 Database Programming-SQL


Final Assignment Paper/Tutorial Rough Draft
April 13, 2016
INTRODUCTION
SQL is short for Structured Query Language and is used to allow
users to communicate with databases. This is completed through the use of
queries. In addition, queries can be used to answer questions about the data
and potentially make business decisions based on what is found. Data is
uninterpreted information within a table. Depending on the commands used
in a query, you can show the data contained within database in a variety of
useful ways from showing all the data to showing when a specific piece of
data occurs to counting the number of occurrences of the data. SQL can also
be used to enter data into databases. This tutorial will cover the following
major topics: how to create tables and insert data, how to create basic
queries, how to join tables, how to sort data, how to count occurrences and
perform math, and how to use conditional statements.
CREATING TABLES AND INSERTING DATA
Before queries can be made, the database needs to contain data.
Related data is stored together on tables. Each table consists of both fields
and records. Records contain information about a specific item or person; for

Poirier 2
example, a record could contain information about Stevie Wonder. Fields are
a brief description of the data contained in each section of a record; for
example, a field from the example record could be last_name which refers to
Stevie Wonders last name. The unique field in a record is called a primary
key; some tables contain multiple keys. In keeping with the previous
examples, an example of a primary key would be last_name. If a table
shares a unique field with another table, it is called a foreign key. Foreign
keys will be covered more in the JOINING TABLES section.
The first step in inserting data is to create tables. When creating
tables, the following items must be included: CREATE TABLE (which instructs
the database to create a table), the name of the table, the field names, and
the type of data the field contains. The possible types of data are listed in
the table below.
Data Type
INT
VARCHAR

DATETIME
NUMERIC

Definition of the Data Type


Integer also known as a number
Various Characters; can contain both
numbers and letters; the number of
characters allowed in the field can be
limited (see example code below for
how to do so)
Date and time
Numbers; used for writing phone
numbers

An example of code to insert a table would be:


CREATE TABLE CD_LABELS
(LABEL_ID INT,
COMPANY_NAME VARCHAR (100))
Where CD_LABELS is the name of the table, LABEL_ID is the first field which
can only contain numbers, and COMPANY_NAME is the second field which can
contain up to 100 numbers and letters.
The second, and last, step in inserting data is to actually insert the
data. This should be completed after all tables have been inserted into the
database. Data is inserted into the table one record at a time. When
inserting data into tables, the following items must be included: INSERT
INTO TABLE (which instructs the database to insert the data into the table),
the table name, VALUE (which informs that database that the data is to

Poirier 3
follow directly after), and the data/value in order of the fields. It is optional
into include the names of the fields. If many records are being inserted at
the same time, it is helpful to list the names of the fields being used in the
first record being inserted to keep track of the types of data being entered in.
If the data is considered a string, then it is required to have single quotes
before and after it. Strings are composed of data that includes letters of the
alphabet (regardless of if it contains numbers or not). An example of a string
would be Stevie Wonder and Greatest Hits of 1970.
An example of code to insert data into a table would be:
INSERT INTO CD_LABELS
(LABEL_ID, COMPANY_NAME)
VALUES (826, ANTI Records)
Where CD_LABELS is the table name, LABEL_ID is the first field,
COMPANY_NAME is the second field, 826 is the LABEL_ID in the first record,
and ANTI Records is the COMPANY_NAME in the first record.
BASIC QUERIES
There is a minimum of two components in every query, which are
SELECT and FROM. SELECT is used to select the fields to be displayed. If the
user wants all fields to be displayed, then * should be used. When referring
to fields within a table, it is required to also refer to the table the field
belongs to. An example of this would be CD_LABELS.LABEL_ID; this refers to
the LABEL_ID field within the CD_LABELS table. FROM is used to select the
table(s) to be used in the query. The use of multiple tables in queries will be
covered in the JOINING TABLES section. It is possible to abbreviate the table
name, which is done within the FROM line of a query. (An example of this will
be within the example a show all fields query.) There are no requirements or
limitations for abbreviations other than it be at least one character long.
One of the simplest queries to create is one that shows all fields (and data) in
a table. This query requires the following components: SELECT and FROM.
An example of code to show all fields (and data) would be:
SELECT *
FROM CD_LABELS cd
Where * means that all fields (and data will be shown), CD_LABELS is the
table, and cd is the abbreviation for the table CD_LABELS.
The result of the example query would look like this:

Poirier 4

An example of code to show one field would be:


SELECT cd.LABEL_ID
FROM CD_LABELS cd
Where cd.LABEL_ID refers to the LABEL_ID field within the CD_LABELS table,
CD_LABELS is the table, and cd is the abbreviation for the table CD_LABELS
An example of code to show two fields would be:
SELECT cd.LABEL_ID,
cd.COMPANY_NAME
FROM CD_LABELS cd
Where cd.LABEL_ID refers to the LABEL_ID field within the CD_LABELS table,
cd.COMPANY_NAME refers to the COMPANY_NAME within the CD_LABELS
table, CD_LABELS is the table, and cd is the abbreviation for the table
CD_LABELS
JOINING TABLES
In order to complete queries involving multiple tables, the tables must
be joined. In order for tables to be joined there must at least one field in
common; usually the fields in common are primary or foreign keys. To be
able to connect two tables that do not have one field in common, other
tables must be used. For example, if the user wants to join table_1 and
table_3 together but there are no fields in common, then table_2 should be
looked at. (Please refer to the sample tables below for this example.) After
looking at the sample tables, the user can see that both table_1 and table_2
have the field Field_a in common so they can be joined. It can also been
seen that both table_2 and table_3 have the field Field_e in common so they
can be joined. Since table_1 and table_2 can be joined and table_3 has a
field in common with table_2, table_3 can be joined to the other tables.
table_1
Field_a

Field_c

Field_d

Poirier 5
table_2
Field_a

Field_e

Field_f

table_3
Field_e

Field_g

Field_h

There are four different ways to join tables; they are as follows: LEFT
JOIN, RIGHT JOIN, INNER JOIN, and OUTER JOIN. LEFT JOINs are the most
common type and are also known as an OUTER LEFT JOIN or just JOIN. In a
LEFT JOIN, records from the left table are taken into account first and then
right table; all records are used even if creates null fields. Null fields are
fields which contain no data. RIGHT JOINs are also referred to as an OUTER
RIGHT JOIN and are the same as LEFT JOINs except the records from the right
table are taken into account first instead of the left table. An INNER JOIN
combines records from another table but only if there is related data in the
other table. An OUTER JOIN combines records from another table puts NULL
in the where the related records have no corresponding data. All ways to join
tables use the same components in the same order and the same way with
the only difference being which type of join is listed. The components which
are: SELECT (which selects the fields to be displayed), FROM (which selects
the first table to be used in the query), JOIN (which informs that database
that another table will be combined with the previous table(s) follows directly
after), the second tables name, ON (which states that the shared/equivalent
fields will be defined directly after), and the two equivalent fields.
An example of code to complete a LEFT JOIN would be:
SELECT *
FROM CD_LABELS cl JOIN COMPACT_DISCS cd ON cl.LABEL_ID = cd.LABEL_ID
Where * means that all fields (and data will be shown), CD_LABELS is the
table, cl is the abbreviation for the table CD_LABELS, COMPACT_DISCS is the
table to be combined with CD_LABELS, cd is the abbreviation for the table
COMPACT_DISCS, and cl.LABEL_ID = cd.LABEL_ID means that the field
LABEL_ID from the table CD_LABELS is equivalent to the field LABEL_ID on
the table COMPACT_DISCS.
The result of the example query would look like this:

Poirier 6

An example of code to complete a RIGHT JOIN would be:


SELECT *
FROM CD_LABELS cl RIGHT JOIN COMPACT_DISCS cd ON cl.LABEL_ID =
cd.LABEL_ID
An example of code to complete an OUTER JOIN would be:
SELECT *
FROM CD_LABELS cl OUTER JOIN COMPACT_DISCS cd ON cl.LABEL_ID =
cd.LABEL_ID
An example of code to complete an INNER JOIN would be:
SELECT *
FROM CD_LABELS cl INNER JOIN COMPACT_DISCS cd ON cl.LABEL_ID =
cd.LABEL_ID
SORTING DATA
When a query result produces many records, it can be difficult to
understand the data without sorting. The records can be sorted by selecting
a field to be sorted in ascending (ASEC) or descending (DESC) order. If it is
not specified, the records will be automatically be sorted in ascending order.
The unique component in sorting is ORDER BY (which tells the database that
the records will be sorted according to the field to follow). The other required
components are: SELECT and FROM.
An example of code to ORDER BY in ascending order would be:
SELECT *
FROM CD_LABELS cd
ORDER BY cd.LABEL_ID ASC
Where * means that all fields (and data will be shown), CD_LABELS is the
table, cd is the abbreviation for the table CD_LABELS, and the results will be
sorted in ascending order based on the LABEL_ID in the CD_LABELS table.
USE CONDITIONAL STATEMENTS
In order to find records that fit a certain criteria, the user can use
conditional statements. There are types of conditional statements; one is

Poirier 7
used to compare data (WHEN) and the other is used in all other occasions
(WHERE). When using the WHERE component, the user must chose a field;
define whether it is equal to, greater than, less than, equal to or greater
than, equal to or less than a value that must also be chosen. If there are
multiple specifications, LIKE (or NOT LIKE) or IN can be used instead of the
math operators, or AND and OR. LIKE and NOT LIKE should be used when
there are wild card values and IN should be used when there are not wild
card values. Wild card can be used as an unknown/undefined value. It can
be used as part of a word (before or after) or as a separate word located
before or after the defined word. (Please see example later in this section for
more explanation.) If a wild card is being used then LIKE should be used and
not, then IN should be used. If there is no data in a record for a specific field,
then it is considered to be NULL; sometimes the field with no data is
considered to be blank and therefore is not considered to be NULL. Because
of this this, if the user is trying to find all fields that do not have any data it is
best to search for both NULL and blank fields. If most records have fields
that are either blank or NULL, the user can have the query search for all
records WHERE the field is NOT NULL. The components AND and OR can also
be used in this case. When using the component OR, only one of the values
must be met in order for (a) records to be displayed in the results of the
query. When using the component AND, all of the values must be met in
order for (a) records to be displayed in the results of the query. The value
chosen must be contained within the field selected.
An example of code using WHERE to select records would be:
SELECT cdl.COMPANY_NAME
FROM CD_LABELS cdl JOIN COMPACT_DISCS cd ON cdl.LABEL_ID =
cd.LABEL_ID
WHERE cd.CD_TITLE = 'Man Against Machine'
The result of the example query would look like this:

An example of code using WHERE, LIKE, and a wild card to select records
would be:
SELECT a.PLACE_OF_BIRTH
FROM ARTISTS a
WHERE a.PLACE_OF_BIRTH LIKE '%USA'
Where the field to be displayed is PLACE_OF_BIRTH from the ARTISTS table
(which is abbreviated by the letter a) and only data that ends with USA in the
PLACE_OF_BIRTH field should be in the results.
There are added requirements to use when searching by phone number.

Poirier 8
An example of code to search for a phone number would be:
SELECT c.Customer_Name,
Customer_Phone = ( + SUBSTRING(str(c.Customer_Phone), 1, 3) +
) +
SUBSTRING(str(c.Customer_Phone), 4, 3)
+ - +
SUBSTRING(str(c.Customer_Phone),74, 3)
FROM customer c
WHERE c.Customer_Phone = 333333333
Where the field displayed is the Customer_Name and Customer_Phone
(displayed in the following format: 123-456-7891) from the customer table
and the phone number is written in the Customer_Phone field as 333333333.
Another type of conditional statement is a CASE statement. CASE
statements can use all of the following components: WHEN, THEN, and ELSE.
It is required to use the CASE component to start this type of conditional
statement and the END component to finish it. When the component WHEN
is used, at least one of the following components must also be used THEN
and ELSE. It is easiest to define the WHEN component in reference to an
example. Using the example below, the first line that contains WHEN means
that when the value in field species is human, THEN the sound is talk. The
second line that contains WHEN means that when the value in field species is
cat, THEN the sound is meow. The ELSE statement means that the sound for
all other species is bark in this case this works as the only other species
from the database is dog.
An example of code that uses WHEN, THEN, and ELSE would be:
SELECT *,
CASE
WHEN species = 'human'
THEN 'talk'
WHEN species = 'cat'
THEN 'meow'
ELSE 'bark'
END AS sound
FROM friends_of_pickles;
An example of code that uses AND would be:
SELECT cd.CD_TITLE,
cd.IN_STOCK
FROM COMPACT_DISCS cd
WHERE cd.CD_TITLE = 'Drive All Night'

Poirier 9
and cd.IN_STOCK > 0
Where the fields to be displayed, all from the COMPACT_DISCS table, are
CD_TITLE and IN_STOCK and both the CD_TITLE field is Drive All Night and
the IN_STOCK value is greater than zero.
COUNTING OCCURRENCES AND PERFORM MATH
If the user is trying to count the number of times that a certain value
occurs under the certain conditions (or throughout the data), then it is
recommended that they use the COUNT component. It displays the number
of times a value appears within the selected field (and is written in the
SELECT line). To display the number of times a distinct value appears with in
the selected field, the COUNT(DISTINCT) component. If the user only wants
number value to display that is equal to, greater than, less than, equal to or
greater than, equal to or less than a certain number, the component HAVING
COUNT should be used after grouping the data.
An example of code that uses COUNT(DISTINCT) would be:
SELECT COUNT(DISTINCT a.ARTIST_ID)
FROM ARTISTS a JOIN ARTIST_CDS ac ON a.ARTIST_ID = ac.ARTIST_ID
JOIN COMPACT_DISCS cd ON ac.CD_ID = ac.CD_ID
JOIN CD_LABELS cl ON cl.LABEL_ID = cd.LABEL_ID
WHERE cl.COMPANY_NAME = 'Motown / Universal'
Where the number of times there is a different value in the ARTIST_ID field
from the ARTISTS table and the COMPANY_NAME field from the
COMPACT_DISCS table is Motown / Universal. In the end, this query will show
how many artists work for the company Motown / Universal.
An example of code that uses HAVING COUNT would be:
SELECT a.ARTIST_NAME
FROM ARTIST_CDS ac JOIN ARTISTS a ON a.ARTIST_ID = ac.ARTIST_ID
GROUP BY a.ARTIST_NAME,
ac.ARTIST_ID
HAVING COUNT(ac.ARTIST_ID) > 1
Where the ARTIST_NAME field from the ARTISTS table will be in the results as
long as the ARTIST_ID is greater than 1 and the data will be grouped by both
the ARTIST_NAME field from the ARTISTS table and the ARTIST_ID from the
ARTIST_CDS table.
In order to complete math problems, the SUM component can be used
or a new field can be created that is defined by adding, subtracting,
multiplying, and dividing two or more fields together. In addition, the lowest
value (MIN), highest value (MAX), and average (AVG) in the set of data

Poirier 10
and/or parameters set by the query can be found as well. To have a new
field diplay, the user must name the field and define what it equals (see
example for specifics). The new field does not create new field in the table
or affect it in any way. It is merely a way to display additional information
created using data from a table like the result of a math problem.
Example of code using SUM would be:
SELECT
SUM(cd.IN_STOCK)
FROM COMPACT_DISCS cd
WHERE cd.CD_TITLE = 'Drive All Night'
Where the sum of all the values in the field IN_STOCK from the
COMPACT_DISCS field that has the title Drive All Night will be displayed in the
results.
Example of finding the minimum value would be:
SELECT t.Truck_Number,
t.Truck_Type,
MIN(t.Purchase_Date)
FROM truck t
Where the fields to be displayed, all from the truck table, are Truck_Number,
Truck_Type, and Purchase_Date and the record to be shown is the lowest
date/earliest date in the Purchase_Date.
Example of multiplying two fields together and creating a new field would
be:
SELECT OrderItem.Id,
OrderItem.OrderId,
OrderItem.productId,
OrderItem.unitprice,
OrderItem.quantity,
Value = OrderItem.UnitPrice * OrderItem.quantity
FROM OrderItem
Where the following fields from the OrderItem table will be displayed: Id,
OrderId, productId unitprice, and quantity; also the created field, value, will
appear in the results of the query.

S-ar putea să vă placă și