Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Introduction to SQL
Description: The uses of SQL include modifying database table and index structures; adding, updating and deleting rows of data; and retrieving subsets of information from within a database for transaction processing and analytics applications. Queries and other SQL operations take the form of commands written as statements -- commonly used SQL statements include select, add, insert, update, delete, create, alter and truncate.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Introduction to Structured Query Language
This page is a introductory tutorial of the Structured Query Language (also known as SQL) and is a
pioneering effort on the World Wide Web, as this is the first comprehensive SQL tutorial available on the
Internet
...
SQL also allows users to define the data in a database, and manipulate that data
...
The SQL used in this document is "ANSI", or
standard SQL, and no SQL features of specific database management systems will be discussed until the
"Nonstandard SQL" section
...

Also, you may be interested in joining the new SQL Club on Yahoo!, where you can read or enter
messages in a SQL forum
...
An example table would relate Social Security Number,
Name, and Address:
EmployeeAddressTable
SSN

FirstName LastName Address

City

State

512687458 Joe

Smith

83 First Street Howard

Ohio

758420012 Mary

Scott

842 Vine Ave
...


876512563 Sarah

Ackerman 440 U
...
110

Paris

New York

Upton

Michigan

Now, let's say you want to see the address of each employee
...
Losantiville Ohio

Sam

Jones

33 Elm St
...
S
...
Note that column names
and table names do not have spaces
...
The general form for a SELECT statement, retrieving all of the rows in the table is:
SELECT ColumnName, ColumnName,
...


Conditional Selection
To further discuss the SELECT statement, let's look at a new example table (for hypothetical purposes
only):
EmployeeStatisticsTable
EmployeeIDNo

Salary

Benefits

Position

010

75000

15000

Manager

105

65000

15000

Manager

152

60000

15000

Manager

215

60000

12500

Manager

244

50000

12000

Staff

300

45000

10000

Staff

335

40000

10000

Staff

400

32000

7500

Entry-Level

441

28000

7500

Entry-Level

Relational Operators
There are six Relational Operators in SQL, and after introducing them, we'll see how they're used:
=

Equal

< or != (see
manual)

Not Equal

<

Less Than

>

Greater Than

<=

Less Than or Equal To

>=

Greater Than or Equal To

The WHERE clause is used to specify that only certain rows of the table are displayed, based on the
criteria described in that WHERE clause
...

If you wanted to see the EMPLOYEEIDNO's of those making at or over $50,000, use the following:
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY >= 50000;
Notice that the >= (greater than or equal to) sign is used, as we wanted to see those who made greater than
$50,000, or equal to $50,000, listed together
...
The same can be done for text columns:
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE

WHERE POSITION = 'Manager';
This displays the ID Numbers of all Managers
...
Note:
Position is now an illegal identifier because it is now an unused, but reserved, keyword in the SQL-92
standard
...
e
...
For example, to display all staff making over $40,000, use:
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY > 40000 AND POSITION = 'Staff';
The OR operator joins two or more conditions, but returns a row if ANY of the conditions listed hold true
...
Subsequently, SQL only
displays this second new list of rows, keeping in mind that anyone with Benefits over $12,000 will be
included as the OR operator includes a row if either resulting condition is True
...

To generalize this process, SQL performs the AND operation(s) to determine the rows where the AND
operation(s) hold true (remember: all of the conditions are true), then these results are used to compare
with the OR conditions, and only display those remaining rows where any of the conditions joined by the
OR operator hold true (where a condition or result from an AND is paired with another condition or AND

result to use to evaluate the OR, which evaluates to true if either value is true)
...

To look at an example, for a given row for which the DBMS is evaluating the SQL statement Where
clause to determine whether to include the row in the query result (the whole Where clause evaluates to
True), the DBMS has evaluated all of the conditions, and is ready to do the logical comparisons on this
result:
True AND False OR True AND True OR False AND False
First simplify the AND pairs:
False OR True OR False
Now do the OR's, left to right:
True OR False
True
The result is True, and the row passes the query conditions
...
I hope that this section has helped you understand AND's or OR's, as it's a
difficult subject to explain briefly
...
For example, if you wanted to list
all managers and staff:
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION IN ('Manager', 'Staff');

or to list those making greater than or equal to $30,000, but less than or equal to $50,000, use:
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY BETWEEN 30000 AND 50000;
To list everyone not in this range, try:
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY NOT BETWEEN 30000 AND 50000;
Similarly, NOT IN lists all rows excluded from the IN list
...

SQL Order of Logical Operations (each operates from left to right)
1
...
AND
3
...
To find those people with LastName's ending in "S", use '%S',
or if you wanted the "S" in the middle of the word, try '%S%'
...
NOT LIKE displays rows not fitting the given
description
...
This disclaimer holds for the features of SQL that will be discussed below
...


Joins
In this section, we will only discuss inner joins, and equijoins, as in general, they are the most useful
...

Good database design suggests that each table lists data only about a single entity, and detailed
information can be obtained in a relational database, by using additional tables, and by using a join
...
A primary key is a column or set of columns that uniquely
identifies the rest of the data in any given row
...
This means two things: no two rows can have the same OwnerID,
and, even if two owners have the same first and last names, the OwnerID column ensures that the two
owners will not be confused with each other, because the unique OwnerID column will be used
throughout the database to track the owners, rather than the names
...
In DBMS-speak, this correspondence is known as referential integrity
...
In other words, all of this "ID" data is used to
refer to the owners, buyers, or sellers of antiques, themselves, without having to use the actual names
...
For example, you can find the names of those who
bought a chair without having to list the full name of the buyer in the Antiques table
...
To find the names of those who bought a chair, use
the following query:
SELECT OWNERLASTNAME, OWNERFIRSTNAME
FROM ANTIQUEOWNERS, ANTIQUES
WHERE BUYERID = OWNERID AND ITEM = 'Chair';
Note the following about this query
...
In the WHERE clause, first notice that the ITEM = 'Chair' part restricts the
listing to those who have bought (and in this example, thereby own) a chair
...
Only where
ID's match across tables and the item purchased is a chair (because of the AND), will the names from the
AntiqueOwners table be listed
...
The result of this query is two names: Smith, Bob & Fowler, Sam
...
OWNERLASTNAME, ANTIQUEOWNERS
...
BUYERID = ANTIQUEOWNERS
...
ITEM =
'Chair';
As the column names are different in each table, however, this wasn't necessary
...

Obviously, you want a list where each seller is only listed once--you don't want to know how many
antiques a person sold, just the fact that this person sold one (for counts, see the Aggregate Function
section below)
...
To do this, use the DISTINCT keyword
...
However, keep in mind that since the SellerID column in the Antiques table is a foreign
key to the AntiqueOwners table, a seller will only be listed if there is a row in the AntiqueOwners table
listing the ID and names
...

To throw in one more twist, we will also want the list alphabetized by LastName, then by FirstName (on a
LastName tie)
...
For future reference (and in case anyone asks), this type of join is considered to be in
the category of inner joins
...
First, look at this query which prints the last name of those owners who have placed an
order and what the order is, only listing those orders which can be filled (that is, there is a buyer who
owns that ordered item):
SELECT OWN
...
ITEMDESIRED Item Ordered
FROM ORDERS ORD, ANTIQUEOWNERS OWN
WHERE ORD
...
OWNERID
AND ORD
...
First, the "Last Name" and "Item Ordered" in the Select lines gives the headers on the report
...
The OWN & ORD are aliases; these are new names for the two tables listed in the FROM clause
that are used as prefixes for all dot notations of column names in the query (see above)
...

3
...

4
...
What this does is, the subquery is performed,
returning all of the Items owned from the Antiques table, as there is no WHERE clause
...

You can think of it this way: the subquery returns a set of Items from which each ItemDesired in
the Orders table is compared; the In condition is true only if the ItemDesired is in that returned set
from the Antiques table
...
Also notice, that in this case, that there happened to be an antique available for each one desired
...
In addition, notice that when the IN, "= ANY", or "=
SOME" is used, that these keywords refer to any possible row matches, not column matches
...

Whew! That's enough on the topic of complex SELECT queries for now
...


Miscellaneous SQL Statements
Aggregate Functions
I will discuss five important aggregate functions: SUM, AVG, MAX, MIN, and COUNT
...

SUM () gives the total of all the rows, satisfying any conditions, of the given column, where the
given column is numeric
...

MAX () gives the largest figure in the given column
...

COUNT(*) gives the number of rows satisfying the conditions
...

SELECT MIN(BENEFITS)
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION = 'Manager';
This query gives the smallest figure of the Benefits column, of the employees who are Managers, which is
12500
...


Views
In SQL, you might (check your DBA) have access to create views for yourself
...
When you access a view, the query that is
defined in your view creation statement is performed (generally), and the results of that query look just
like another table in the query that you wrote invoking the view
...
The listing is generated by
going through the Antique Items one-by-one until there's a match with the Antview view
...


Creating New Tables

All tables within a database must be created at some point in time
...
Please note that
this statement uses generic data types, and that the data types might be different, depending on what
DBMS you are using
...
Some common generic data types are:
Char(x) - A column of characters, where x is a number designating the maximum number of
characters allowed (maximum length) in the column
...

Decimal(x, y) - A column of decimal numbers, where x is the maximum length in digits of the
decimal numbers in this column, and y is the maximum number of digits allowed after the decimal
point
...
99
...

Logical - A column that can hold only two values: TRUE or FALSE
...
If NULL was
used, that column may be left empty in a given row
...


Adding Data
To insert rows into a table, do the following:
INSERT INTO ANTIQUES VALUES (21, 01, 'Ottoman', 200
...
Instead,
let's change the order and leave Price blank:

INSERT INTO ANTIQUES (BUYERID, SELLERID, ITEM)
VALUES (01, 21, 'Ottoman');

Deleting Data
Let's delete this new row back out of the database:
DELETE FROM ANTIQUES
WHERE ITEM = 'Ottoman';
But if there is another row that contains 'Ottoman', that row will be deleted also
...
00 WHERE ITEM = 'Chair';
This sets all Chair's Prices to 500
...
As shown above, more WHERE conditionals, using AND, must be
used to limit the updating to more specific rows
...


Miscellaneous Topics
Indexes
Indexes allow a DBMS to access data quicker (please note: this feature is nonstandard/not available on all
systems)
...
This index tells the DBMS where a certain row
is in the table given an indexed-column value, much like a book index tells you what page a given word
appears
...
In the
second example, the index is kept on the two columns, aggregated together--strange behavior might occur
in this situation
...

Some DBMS's do not enforce primary keys; in other words, the uniqueness of a column is not enforced
automatically
...
One way to
get around that is to create a unique index on the column that we want to be a primary key, to force the
system to enforce prohibition of duplicates:
CREATE UNIQUE INDEX OID_IDX ON ANTIQUEOWNERS (OWNERID);

GROUP BY & HAVING
One special use of GROUP BY is to associate an aggregate function (especially COUNT; counting the
number of rows in each group) with groups of rows
...
We want to see the price of the most expensive item
bought by each owner
...
First, list the buyers who purchased an expensive item (the Price of the
item is $100 greater than the average price of all items purchased):
SELECT BUYERID
FROM ANTIQUES
WHERE PRICE >
(SELECT AVG(PRICE) + 100
FROM ANTIQUES);
The subquery calculates the average Price, plus $100, and using that figure, an OwnerID is printed for
every item costing over that figure
...

List the Last Names of those in the AntiqueOwners table, ONLY if they have bought an item:
SELECT OWNERLASTNAME
FROM ANTIQUEOWNERS
WHERE OWNERID IN
(SELECT DISTINCT BUYERID
FROM ANTIQUES);
The subquery returns a list of buyers, and the Last Name is printed for an Antique Owner if and only if the
Owner's ID appears in the subquery list (sometimes called a candidate list)
...

For an Update example, we know that the gentleman who bought the bookcase has the wrong First Name
in the database
...

Remember this rule about subqueries: when you have a subquery as part of a WHERE condition, the
Select clause in the subquery must have columns that match in number and type to those in the Where
clause of the outer query
...
);", the
Select must have only one column in it, to match the ColumnName in the outer Where clause, and they
must match in type (both being integers, both being character strings, etc
...

However, if a prospective customer wanted to see the list of Owners only if the shop dealt in Chairs, try:
SELECT OWNERFIRSTNAME, OWNERLASTNAME
FROM ANTIQUEOWNERS
WHERE EXISTS
(SELECT *
FROM ANTIQUES
WHERE ITEM = 'Chair');
If there are any Chairs in the Antiques column, the subquery would return a row or rows, making the
EXISTS clause true, causing SQL to list the Antique Owners
...

ALL is another unusual feature, as ALL queries can usually be done with different, and possibly simpler
methods; let's take a look at an example query:
SELECT BUYERID, ITEM
FROM ANTIQUES
WHERE PRICE >= ALL
(SELECT PRICE
FROM ANTIQUES);

This will return the largest priced item (or more than one item if there is a tie), and its buyer
...
The reason "=" must be used is that the highest priced item will be equal to
the highest price on the list, because this Item is in the Price list
...
To merge the output of the following two queries, displaying the ID's of all Buyers,
plus all those who have an Order placed:
SELECT BUYERID
FROM ANTIQUES
UNION
SELECT OWNERID
FROM ORDERS;
Notice that SQL requires that the Select list (of columns) must match, column-by-column, in data type
...
Also notice that SQL does automatic
duplicate elimination when using UNION (as if they were two "sets"); in single queries, you have to use
DISTINCT
...
First, look at the query:
SELECT OWNERID, 'is in both Orders & Antiques'
FROM ORDERS, ANTIQUES
WHERE OWNERID = BUYERID
UNION
SELECT BUYERID, 'is in Antiques only'
FROM ANTIQUES
WHERE BUYERID NOT IN
(SELECT OWNERID
FROM ORDERS);
The first query does a join to list any owners who are in both tables, and putting a tag line after the ID
repeating the quote
...
The second list is generated by first
listing those ID's not in the Orders table, thus generating a list of ID's excluded from the join query
...
There might be an easier way to make this list, but it's difficult to generate the
informational quoted strings of text
...
For example, in one table, the primary key is a salesperson, and in
another table is customers, with their salesperson listed in the same row
...
The outer join is used if the listing of all
salespersons is to be printed, listed with their customers, whether the salesperson has a customer or not-that is, no customer is printed (a logical NULL value) if the salesperson has no customers, but is in the
salespersons table
...

Another important related point about Nulls having to do with joins: the order of tables listed in the From
clause is very important
...
This is another occasion (should you wish that data included in the result) where an
outer join is commonly used
...

ENOUGH QUERIES!!! you say?
...


Embedded SQL--an ugly example (do not write a program like this
...
Embedded SQL allows programmers to connect to a database and
include SQL code right in the program, so that their programs can
use, manipulate, and process data from a database
...

-This program will have to be precompiled for the SQL statements,
before regular compilation
...

-Embedded SQL changes from system to system, so, once again, check
local documentation, especially variable declarations and logging
in procedures, in which network, DBMS, and operating system
considerations are crucial
...
h>
/* This section declares the host variables; these will be the
variables your program uses, but also the variable SQL will put
values in or take values out
...
*/
EXEC SQL INCLUDE SQLCA;
main() {
/* This is a possible way to log into the database */
EXEC SQL CONNECT UserID/Password;
/* This code either says that you are connected or checks if an error
code was generated, meaning log in was incorrect or not possible
...
sqlcode) {
printf(Printer, "Error connecting to database server
...
\n");
/* This declares a "Cursor"
...
With each row established by this query,
I'm going to use it in the report
...
The "Declare" just
establishes the query
...
However, a "priming fetch" (programming
technique) must first be done
...
Notice
that, for simplicity's sake, the loop will leave on any sqlcode,
even if it is an error code
...
*/
EXEC SQL FETCH ItemCursor INTO :Item, :BuyerID;
while(!sqlca
...
First, bump the
price up by $5 (dealer's fee) and get the buyer's name to put in
the report
...
The update assumes however, that
a given buyer has only bought one of any given item, or else the
price will be increased too many times
...
Also notice the colon
before host variable names when used inside of SQL statements
...
*/
EXEC SQL FETCH ItemCursor INTO :Item, :BuyerID;
}
/* Close the cursor, commit the changes (see below), and exit the
program
...
Why can't I just ask for the first three rows in a table? --Because in relational databases, rows are
inserted in no particular order, that is, the system inserts them in an arbitrary order; so, you can
only request rows using valid SQL features, like ORDER BY, etc
...
What is this DDL and DML I hear about? --DDL (Data Definition Language) refers to (in SQL)
the Create Table statement
...
Also, QML, referring to Select statements, stands for Query
Manipulation Language
...
Aren't database tables just files? --Well, DBMS's store data in files declared by system managers
before new tables are created (on large systems), but the system stores the data in a special format,
and may spread data from one table over several files
...
In general, on small systems, everything about a database
(definitions and all table data) is kept in one file
...
(Related question) Aren't database tables just like spreadsheets? --No, for two reasons
...

Depending on your spreadsheet software, a cell might also contain formulas and formatting, which
database tables cannot have (currently)
...
In databases, "cells" are independent, except that columns are logically related
(hopefully; together a row of columns describe an entity), and, other than primary key and foreign
key constraints, each row in a table is independent from one another
...
How do I import a text file of data into a database? --Well, you can't do it directly
...
A
program to do this would simply go through each record of a text file, break it up into columns,
and do an Insert into the database
...
What web sites and computer books would you recommend for more information about SQL and
databases? --First, look at the sites at the bottom of this page
...

Also, if you wish to practice SQL on an interactive site (using Java technologies), I highly
recommend Frank Torres' (torresf@uswest
...
com and its new sequel (so
to speak) site at http://sqlcourse2
...
Frank did an outstanding job with his site, and if you have
a recent release browser, it's definitely worth a visit
...

topica
...
they are outstanding; Tim Quinlan
goes into topics that I can't even begin to go into here, such index data structures (B-trees and B+trees) and join algorithms, so advanced IT RDBMS pros will get a daily insight into these data
management tools
...
As far as books are concerned, I would suggest
(for beginners to intermediate-level) "Oracle: The Complete Reference" (multiple versions) from
Oracle and "Understanding SQL" from Sybex for general SQL information
...
For specific
DBMS info (especially in the Access area), I recommend Que's "Using" series, and the books of
Alison Balter
...
What is a schema? --A schema is a logical set of tables, such as the Antiques database above
...

For example, a star schema is a set of tables where one large, central table holds all of the
important information, and is linked, via foreign keys, to dimension tables which hold detail
information, and can be used in a join to create detailed reports
...
I understand that Oracle offers a special keyword, Decode, that allows for some "if-then" logic
...
The syntax looks like this (from the Oracle: Complete Reference series):
Select
...
,]
Else)
...
;
The Value is the name of a column, or a function (conceivably based on a column or columns), and
for each If included in the statement, the corresponding Then clause is the output if the condition is
true
...
Let's look at an example:
Select Distinct City,
DECODE (City, 'Cincinnati', 'Queen City', 'New York', 'Big
Apple', 'Chicago',
'City of Broad Shoulders', City) AS Nickname
From Cities;
The output might look like this:
City
-----------Boston
Cincinnati
Cleveland
New York

Nickname
-----------------------------Boston
Queen City
Cleveland
Big Apple

'City' in the first argument denotes the column name used for the test
...

arguments are the individual equality tests (taken in the order given) against each value in the City
column
...
arguments are the corresponding outputs if the corresponding test is
true
...


TIP: If you want nothing to be output for a given condition, such as the default "Else" value, enter
the value Null for that value, such as:
Select Distinct City,
DECODE (City, 'Cincinnati', 'Queen City', 'New York', 'Big
Apple', 'Chicago',
'City of Broad Shoulders', Null) AS Nickname
From Cities;
If the City column value is not one of the ones mentioned, nothing is outputted, rather than the city
name itself
...
You mentioned Referential Integrity before, but what does that have to do with this concept I've
heard about, Cascading Updates and Deletes? --This is a difficult topic to talk about, because it's
covered differently in different DBMS's
...
0 & below) requires that you write "triggers" (see the
Yahoo SQL Club link to find links that discuss this topic--I may include that topic in a future
version of this page) to implement this
...
) Microsoft Access (believe it or not) will perform this if you define it
in the Relationships screen, but it will still burden you with a prompt
...

So, I'll just discuss the concept
...

Concept: If a row from the primary key column is deleted/updated, if "Cascading" is activated, the
value of the foreign key in those other tables will be deleted (the whole row)/updated
...
As usual, see your DBMS's documentation
...

Of course, assuming the proper DB definition, if you just updated '01' to another value, those Seller
ID values would be updated to that new value too
...
Show me an example of an outer join
...

Think of the following Employee table (the employees are given numbers, for simplicity):
Name Department
1

10

2

10

3

20

4

30

5

30

Now think of a department table:
Department
10
20
30
40
Now suppose you want to join the tables, seeing all of the employees and all of the departments
together
...
40
...
So, in Oracle, try this query (the + goes on Employee, which adds the null row on no
match):
Select E
...
Department

From Department D, Employee E
Where E
...
Department;
This is a left (outer) join, in Access:
SELECT DISTINCTROW Employee
...
Department
FROM Department LEFT JOIN Employee ON Department
...
Department;
And you get this result:
Name Department
1

10

2

10

3

20

4

30

5

30
40

11
...
The query optimizer of the database, the portion of the DBMS that
determines the best way to get the required data out of the database itself, handles
expressions in such a way that would normally require more time to retrieve the data than if
columns were normally selected, and the expression itself handled programmatically
...

If you are using a join, try to have the columns joined on (from both tables) indexed
...

Unless doing multiple counts or a complex query, use COUNT(*) (the number of rows
generated by the query) rather than COUNT(Column_Name)
...
What is a Cartesian product? --Simply, it is a join without a Where clause
...
This is best shown by example:
SELECT *
FROM AntiqueOwners, Orders;
This gives:

AntiqueOwners
...
AntiqueOwners
...
Orders
...

If you think about it, you can see how joins work
...

Of course, this is not how DBMS's actually perform joins because loading this result can take too
much memory; instead, comparisons are performed in nested loops, or by comparing values in
indexes, and then loading result rows
...
What is normalization? --Normalization is a technique of database design that suggests that certain
criteria be used when constructing a table layout (deciding what columns each table will have, and
creating the key structure), where the idea is to eliminate redundancy of non-key data across tables
...

First Normal Form refers to moving data into separate tables where the data in each table is of a
similar type, and by giving each table a primary key
...
For example, if I had left the names of the Antique Owners in the items table,
that would not be in Second Normal Form because that data would be redundant; the name would
be repeated for each item owned; as such, the names were placed in their own table
...

Third Normal Form involves getting rid of anything in the tables that doesn't depend solely on the
primary key
...

There is some redundancy to each form, and if data is in 3NF (shorthand for 3rd normal form), it is
already in 1NF and 2NF
...
If you take a look at the sample database,
you will see that the way then to navigate through the database is through joins using common key
columns
...
On the last point, my
database is lacking, as I use numeric codes for identification
...

14
...
Whether a query returns one row or more than one row is entirely dependent on the
design (or schema) of the tables of the database
...
For example, if you wanted to be
sure that a query of the AntiqueOwners table returned only one row, consider an equal condition of
the primary key column, OwnerID
...
First, getting multiple rows
when you were expecting only one, or vice-versa, may mean that the query is erroneous, that the
database is incomplete, or simply, you learned something new about your data
...
or else, you might be deleting or updating
more rows than you intend
...
If you write a single-row query, only one SQL statement
may need to be performed to complete the programming logic required
...

15
...
--This was sent to me via a news
posting; it was submitted by John Frame ( jframe@jframe
...
com ); I offer a shortened version as advice, but I'm not responsible for it, and
some of the concepts are readdressed in the next question
...
Second, draw a line between any two entities that have any connection
whatsoever; except that no two entities can connect without a 'rule'; e
...
: families have children,
employees work for a department
...
Third, your picture should now have many squares (entities) connected to other entities
through diamonds (a square enclosing an entity, with a line to a diamond describing the
relationship, and then another line to the other entity)
...
Fifth, give each diamond and square any
attributes it may have (a person has a name, an invoice has a number), but some relationships have
none (a parent just owns a child)
...
Seventh, in general you want to make tables not repeat data
...
So, record Name in one table, and
put all his addresses in another
...
Freedman suggests a 'auto-increment number' primary key, where a new, unique number is
generated for each new inserted row
...

first and last name together are good as a 'composite' key
...

16
...
the term "relationships" (often termed
"relation") usually refers to the relationships among primary and foreign keys between tables
...
You may have heard of an Entity-Relationship Diagram, which is a graphical view
of tables in a database schema, with lines connecting related columns across tables
...
But first, let's look at each kind of relationship
...
For example, in
the first example, the EmployeeAddressTable, we add an EmployeeIDNo column
...
Specifically, each employee in the EmployeeAddressTable has statistics
(one row of data) in the EmployeeStatisticsTable
...
Also notice the "has" in bold
...

The other two kinds of relationships may or may not use logical primary key and foreign key
constraints
...
The first of these is the one-to-many relationship ("1M")
...
Key constraints may be added to the design, or possibly just the use of some sort of
identifier column may be used to establish the relationship
...

Finally, the many-to-many relationship ("M-M") does not involve keys generally, and usually
involves identifying columns
...
A [bad] example of the more common situation would be
if you had a job assignment database, where one table held one row for each employee and a job
assignment, and another table held one row for each job with one of the assigned employees
...

These tables have a M-M: each employee in the first table has many job assignments from the
second table, and each job has many employees assigned to it from the first table
...
see the links below for more information and see the diagram below for a
simplified example of an E-R diagram
...
What are some important nonstandard SQL features (extremely common question)? --Well, see the
next section
...
"check local listings"
INTERSECT and MINUS are like the UNION statement, except that INTERSECT produces rows
that appear in both queries, and MINUS produces rows that result from the first query, but not the
second
...
Then, to produce a result after the listing of a group, use
COMPUTE SUM OF PRICE ON BUYERID
...

In addition to the above listed aggregate functions, some DBMS's allow more functions to be used
in Select lists, except that these functions (some character functions allow multiple-row results) are
to be used with an individual value (not groups), on single-row queries
...
Here are some Mathematical Functions:
ABS(X)

Absolute value-converts negative numbers to positive, or leaves positive numbers
alone

CEIL(X)

X is a decimal value that will be rounded up
...


GREATEST(X,Y) Returns the largest of the two values
...


MOD(X,Y)

Returns the remainder of X / Y
...


ROUND(X,Y)

Rounds X to Y decimal places
...


SIGN(X)

Returns a minus if X < 0, else a plus
...


Character Functions
LEFT(,X)

Returns the leftmost X characters of the string
...


UPPER()

Converts the string to all uppercase letters
...


INITCAP()

Converts the string to initial caps
...


||

Combines the two strings of text into one, concatenated string, where the
first string is immediately followed by the second
...


RPAD(,X,'*')

Pads the string on the right with the * (or whatever character is inside the
quotes), to make the string X characters long
...


The Null value function will substitute for any NULLs for in the
NVL(,)
...


Syntax Summary--For Advanced Users Only
Here are the general forms of the statements discussed in this tutorial, plus some extra important ones
(explanations given)
...

see Create Table); --allows you to add or delete a column or columns from a table, or change the

specification (data type, etc
...
), but these definitions are DBMS-specific, so read the
documentation
...
In addition, only one option can be performed per Alter Table statement --either add, drop,
OR modify in a single statement
...

CREATE TABLE
( [()] ,

...
NULL or NOT NULL (see above)
2
...
PRIMARY KEY tells the database that this column is the primary key column (only used if the
key is a one column key, otherwise a PRIMARY KEY (column, column,
...

4
...
sometimes implemented as the CONSTRAINT statement
...
DEFAULT inserts the default value into the database if a row is inserted without that column's data
being inserted; for example, BENEFITS INTEGER DEFAULT = 10000
6
...

CREATE VIEW
AS ;
DELETE FROM
WHERE ;
INSERT INTO
[()]
VALUES ();
ROLLBACK; --Takes back any changes to the database that you have made, back to the last time you gave
a Commit command
...

SELECT [DISTINCT|ALL] ...


Exercises
Queries
Using the example tables in the tutorial, write a SQL statement to:
1
...

2
...

3
...

4
...

5
...

6
...

7
...

8
...

9
...

10
...

Databases
11
...
If you do not have a primary key in a table, the addition of what type of column is preferred to give
the table a primary key?
13
...
When using Embedded SQL, what do you need to create in order to iterate through the results of a
multi-row query, one row at a time?
15
...
What term is used to describe the event of a database system automatically updating the values of
foreign keys in other tables, when the value of a primary key is updated?
17
...
What type of SQL statement is used to change the attributes of a column?
19
...
If you wish to write a query that is based on other queries, rather than tables, what do these other
queries need to be created as?
Answers (Queries may have more than one correct answer):
1
...
OwnerLastName, AntiqueOwners
...
ItemDesired
FROM AntiqueOwners, Orders
WHERE AntiqueOwners
...
OwnerID;
or
SELECT AntiqueOwners
...
OwnerFirstName,
Orders
...
OwnerID = Orders
...
SELECT *
FROM EmployeeStatisticsTable
ORDER BY Position, EmployeeIDNo;
3
...
SELECT OwnerLastName, OwnerFirstName
FROM AntiqueOwners, Antiques
WHERE Item In ('Chair')
AND AntiqueOwners
...
BuyerID;
5
...
SELECT DISTINCT OwnerLastName, OwnerFirstName
FROM Orders, AntiqueOwners
WHERE AntiqueOwners
...
OwnerID;
or to use JOIN notation:
SELECT DISTINCT AntiqueOwners
...

OwnerFirstName
FROM AntiqueOwners RIGHT JOIN Orders ON AntiqueOwners
...

OwnerID;
7
...
INSERT INTO ORDERS VALUES (21, 'Rocking Chair');
9
...
SELECT Position, Sum(Salary)
FROM EmployeeStatisticsTable
GROUP BY Position;
11
...

12
...

13
...

14
...

15
...

16
...

17
...

18
...

19
...

20
...


Important Computing & SQL/Database Links
SQL Reference Page
Programmer's Source
DevX
DB Ingredients
SQL Trainer S/W
Web Authoring
DBMS Lab/Links
SQL FAQ
Query List
SQL Practice Site
SQL Course II
Database Jump Site
Programming Tutorials on the Web
PostgreSQL
Adobe Acrobat
A Good DB Course
Tutorial Page
Intelligent Enterprise Magazine
miniSQL

SQL for DB2 Book
SQL Server 7
SQL Reference/Examples
SQL Topics
Lee's SQL Tutorial
Data Warehousing Homepage
MIT SQL for Web Nerds
RDBMS Server Feature Comparison Matrix
Oracle FAQ
Oracle Developer (2000)
Intro to Relational Database Design
SQL Sam, the SQL Server Detective
ZDNet's SQL Introduction
Baycon Group's SQL Tutorial
Dragonlee's SQL Tutorial
A good, but anonymous SQL Tutorial
UC Davis' Oracle PDF's
About
...
com
A Gentle Introduction to SQL
SQL (News) Wire
I strongly urge you to visit some of the database links shown above, especially if you're interested in
advanced topics, such as the SQL-92 standard, different relational DBMS's, and advanced query
processing
...



Title: Introduction to SQL
Description: The uses of SQL include modifying database table and index structures; adding, updating and deleting rows of data; and retrieving subsets of information from within a database for transaction processing and analytics applications. Queries and other SQL operations take the form of commands written as statements -- commonly used SQL statements include select, add, insert, update, delete, create, alter and truncate.