Академический Документы
Профессиональный Документы
Культура Документы
SQL - (pronounced
"sequel")
SQL stands for Structured Query Language, and it is
a very powerful and diverse language used to create
and query databases. Its loose syntax makes it easy to
learn, but mastering its intricate architecture may
take a bit longer.
SQL - Fundamentals
Some of the basic functions of SQL are inputting,
modifying, and dropping data from databases. In this
tutorial, we use command line examples to give you
an idea of what SQL is capable of. Coupled with the
use of web languages such as HTML and PHP, SQL
becomes an even greater tool for building dynamic
web applications.
SQL - Databases
What's a Database? A SQL database is nothing
more than an empty shell, like a vacant warehouse. It
offers no real functionality whatsoever, but does
provide a virtual space to store data. Data is stored
inside of database objects called tables, and tables
are the containers that actually hold specific types of
data, such as numbers, files, strings, and dates.
SQL - Creating a
Database
Creating a database inside of SQL Express has its
advantages. After launching Microsoft's SQL Server
Management Studio Express application, simply
right-clicking on the Databases folder of the Object
Explorer gives you the option to create a New
Database. After selecting the New Database...
option, name your database "MyDatabase" and press
"OK".
Now is the time to press the New Query button
located toward the top of the screen, just above the
Object Explorer pane.
Pressing this button offers an empty tab. All SQL
query statements (code) that we will be exploring
will be entered here and executed against the SQL
Express database.
SQL - Tables
Data is stored inside SQL tables which are contained
within SQL databases. A single database can house
hundreds of tables, each playing its own unique role
in the database schema. While database architecture
and schema are concepts far above the scope of this
tutorial, we plan on diving in just past the surface to
give you a glimpse of database architecture that
begins with a thorough understanding of SQL Tables.
SQL tables are comprised of table rows and
columns. Table columns are responsible for storing
many different types of data, like numbers, texts,
dates, and even files. There are many different types
of table columns and these data types vary,
depending on how the SQL table has been created by
the SQL developer. A table row is a horizontal record
of values that fit into each different table column.
SQL - Queries
SQL coins the term query as the name for its
commands. Basically, all SQL code is written in the
form of a query statement and then executed against
a database. All SQL queries perform some type of
data operation such as selecting data,
inserting/updating data, or creating data objects such
as SQL databases and SQL tables. Each query
statement begins with a clause such as
SELECT,UPDATE, CREATE or DELETE.
SELECT queries are the most commonly used SQL
commands, so let's take a look at a SELECT query
that will return records from the orders table that we
created previously in the SQL Tables lesson.
SQL - Select
SQL SELECT may be the most commonly used
command by SQL programmers. It is used to extract
data from databases and to present data in a user-
friendly table called the result set.
SELECT *
FROM orders;
SQL - Where
The WHERE clause sets a conditional statement,
and it can be used with any type of SQL query. As
the select query executes, SQL processes one row at
a time. Each time the conditional statement is met
(returns true), a row is returned as a result. SQL
WHERE is essentially, a filtering mechanism for
SQL queries and is a tremendous asset to any
aspiring SQL developer.
SELECT *
FROM orders
WHERE customer = 'Tizag'
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
2008-07-25
6 Tizag HP Printer 2
00:00:00.000
SELECT *
FROM orders
WHERE day_of_order > '7/31/08'
SQL Results:
i day_of_orde quantit
customer product
d r y
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
A+Maintenanc 2008-08-16 Hangin
3 12
e 00:00:00.000 g Files
19"
2008-08-15
4 Gerald Garner LCD 3
00:00:00.000
Screen
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
SQL - As
SQL AS temporarily assigns a table column a new
name. This grants the SQL developer the ability to
make adjustments to the presentation of query results
and allow the developer to label results more
accurately without permanently renaming table
columns.
SELECT customer,day_of_order
FROM orders
WHERE day_of_order > '7/31/08'
SQL - Mathematical
Operators
SQL mathematical operations are performed using
mathematical operators (+, -, *, /, and %). We can
use SQL like a calculator to get a feel for how these
operators work.
SQL Results:
Additio Subtractio Multiplicati Divisio Modulu
n n on n s
19 11 60 3 3
Modulus Example:
USE mydatabase;
SELECT (5 / 2) -- = 2.5
SELECT (5 % 2) -- = 1 is the value that
will be returned
SQL - Create
SQL CREATE is the command used to create data
objects, including everything from new databases
and tables to views and stored procedures. In this
lesson, we will be taking a closer look at how table
creation is executed in the SQL world and offer some
examples of the different types of data a SQL table
can hold, such as dates, number values, and texts.
To accomplish this, it is best to first take a look at the
entire CREATE TABLE query and then review each
line individually.
SQL Code:
USE mydatabase;
SELECT *
FROM inventory;
SQL Results:
id product quantity price
1 19" LCD Screen 25 179.99
2 HP Printer 9 89.99
3 Pen 78 0.99
4 Stapler 3 7.99
5 Hanging Files 33 14.99
6 Laptop 16 499.99
id - (identity, integer)
customer - (customer name, character string)
day_of_order - (date value)
product - (name of product, character string)
quantity - (quantity, integer)
You may notice that the id column has been left out
of the query statement. The reason behind this is that
when we created the orders table, we gave the id
column a unique attribute called identity. SQL
handles identity columns automatically for us and
therefore, we do not need to manually insert data into
this column.
Verification Query:
USE mydatabase;
SELECT *
FROM orders;
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
SQL Results:
i day_of_orde quantit
customer product
d r y
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
A+Maintenanc 2008-08-16 Hangin
3 12
e 00:00:00.000 g Files
Final Results:
i day_of_orde quantit
customer product
d r y
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
A+Maintenanc 2008-08-16 Hangin
3 12
e 00:00:00.000 g Files
19"
2008-08-15
4 Gerald Garner LCD 3
00:00:00.000
Screen
19"
2008-07-25
5 Tizag LCD 3
00:00:00.000
Screen
2008-07-25 HP
6 Tizag 2
00:00:00.000 Printer
SQL - And
SQL AND links together two or more conditional
statements for increased filtering when running SQL
commands. AND helps the developer query for very
specific records while answering questions like, "I
want to view all orders made by a certain customer
AND made on a special date." There is no limit to
the number of AND/OR conditions that can be
applied to a query utilizing the WHERE clause. This
makes it possible for the developer to be as precise as
needed when querying for results.
SELECT *
FROM orders
WHERE customer = 'Tizag'
AND day_of_order = '08/01/08'
AND product = 'Pen';
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
SQL - Or
SQL OR also applies logic to help filter results. The
difference is that instead of linking together
conditional statements, an OR condition just asks
SQL to look for 2 separate conditions within the
same query and return any records/rows matching
either of the conditions.
SQL Or Code:
USE mydatabase;
SELECT *
FROM orders
WHERE product = 'Pen'
OR product = '19" LCD Screen';
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
Gerald 2008-08-15 19" LCD
4 3
Garner 00:00:00.000 Screen
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
SQL - And / Or
Combination
Conditional statements can be grouped together using
parentheses (). Doing so links together conditions
and provides robust solutions for data querying.
SELECT *
FROM orders
WHERE (quantity > 2 AND customer = 'Tizag')
OR (quantity > 0 AND customer = 'Gerald
Garner')
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
Gerald 2008-08-15 19" LCD
4 3
Garner 00:00:00.000 Screen
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
SQL - Between
BETWEEN is a conditional statement found in the
WHERE clause. It is used to query for table rows
that meet a condition falling between a specified
range of numeric values. It would be used to answer
questions like, "How many orders did we receive
BETWEEN July 20th and August 5th?"
SELECT *
FROM orders
WHERE day_of_order BETWEEN '7/20/08' AND
'8/05/08';
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
2008-07-25
6 Tizag HP Printer 2
00:00:00.000
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
2008-07-25
6 Tizag HP Printer 2
00:00:00.000
SQL - Order By
ORDER BY is the SQL command used to sort rows
as they are returned from a SELECT query. SQL
order by command may be added to the end of any
select query and it requires at least one table column
to be specified in order for SQL to sort the results.
SELECT *
FROM orders
WHERE customer = 'Tizag'
ORDER BY day_of_order;
Executing this query should offer a list of orders
made by Tizag and you may noticed that the result
set has now been sorted (low to high) according to
the date value. In other words, the oldest order to the
newest order.
SQL Results:
id customer day_of_order product quantity
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
2008-07-25
6 Tizag HP Printer 2
00:00:00.000
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
SQL - Ascending
Descending
The default sort order for ORDER BY is an
ascending list, [a - z] for characters or [0 - 9] for
numbers. As an alternative to the default sorting for
our results, which is ASCENDING (ASC), we can
instead tell SQL to order the table columns in a
DESCENDING (DESC) fashion [z-a].
SELECT *
FROM orders
WHERE customer = 'Tizag'
ORDER BY day_of_order DESC
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
2008-07-25 19" LCD
5 Tizag 3
00:00:00.000 Screen
2008-07-25
6 Tizag HP Printer 2
00:00:00.000
SQL - Sorting on
Multiple Columns
Results may be sorted on more than one column by
listing multiple column names in the ORDER BY
clause, similar to how we would list column names in
each SELECT statement.
SELECT *
FROM orders
ORDER BY customer, day_of_order;
SQL Results:
i day_of_orde quantit
customer product
d r y
A+Maintenanc 2008-08-16 Hangin
3 12
e 00:00:00.000 g Files
19"
2008-08-15
4 Gerald Garner LCD 3
00:00:00.000
Screen
19"
2008-07-25
5 Tizag LCD 3
00:00:00.000
Screen
2008-07-25 HP
6 Tizag 2
00:00:00.000 Printer
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 1
00:00:00.000
SQL - Update
SQL UPDATE is the command used to update
existing table rows with new data values. UPDATE
is a very powerful command in the SQL world. It has
the ability to update every single row in a database
with the execution of only a single query. Due to
UPDATE's supreme authority, it is in your best
interest to always include a WHERE clause when
working with UPDATE query statements. That way,
you will not accidentally update more rows than you
intend to.
SQL Results:
(1 row(s) affected)
SELECT *
FROM orders
WHERE id = '1'
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 6
00:00:00.000
SQL - Update
Incrementing a Value
In the previous example, an order quantity was
updated from 4 to 6. Say what we really wanted to do
was not necessarily change it to 6, but to add 2 to the
original order quantity. Updating the order quantity
from 4 to 6 might have gotten the job done in that
scenario, but that solution doesn't scale well. In the
long run, we wouldn't get very much "bang for our
buck," as they say.
UPDATE orders
SET quantity = (quantity + 2)
WHERE id = '1'
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 8
00:00:00.000
UPDATE orders
SET quantity = (quantity + 2)
SQL Results:
(6 row(s) affected)
SQL Results:
i customer day_of_orde product quantit
d r y
2008-08-01
1 Tizag Pen 10
00:00:00.000
2008-08-01
2 Tizag Stapler 3
00:00:00.000
A+Maintenanc 2008-08-16 Hangin
3 14
e 00:00:00.000 g Files
19"
2008-08-15
4 Gerald Garner LCD 5
00:00:00.000
Screen
19"
2008-07-25
5 Tizag LCD 5
00:00:00.000
Screen
2008-07-25 HP
6 Tizag 4
00:00:00.000 Printer
UPDATE orders
SET quantity = '11',
Product = 'Hanging Files'
WHERE id = '1'
SQL Results:
id customer day_of_order product quantity
2008-08-01 Hanging
1 Tizag 11
00:00:00.000 Files
The results show that we have successfully updated
an order (order id 1). Notice that after the SET
keyword, the column and value sets are listed with
each column/value pair being separated with a
comma (,).
SQL - Alter
SQL ALTER is the command used to add, edit, and
modify data objects like tables, databases, and views.
ALTER is the command responsible for making table
column adjustments or renaming table columns. New
table columns can also be added and dropped from
existing SQL tables.
SQL Add:
USE mydatabase;
SQL Results:
i day_of_or produ quanti discou
customer
d der ct ty nt
2008-08-01
1 Tizag 00:00:00.0 Pen 8 NULL
00
2008-08-01
2 Tizag 00:00:00.0 Stapler 3 NULL
00
2008-08-16 Hangi
A+Maintena
3 00:00:00.0 ng 14 NULL
nce
00 Files
2008-08-15 19"
Gerald
4 00:00:00.0 LCD 5 NULL
Garner
00 Screen
2008-07-25 19"
5 Tizag 00:00:00.0 LCD 5 NULL
00 Screen
2008-07-25
HP
6 Tizag 00:00:00.0 4 NULL
Printer
00
SQL - Distinct
SQL SELECT DISTINCT is a very useful way to
eliminate retrieving duplicate data reserved for very
specific situations. To understand when to use the
DISTINCT command, let's look at a real world
example where this tool will certainly come in
handy.
SQL Results:
customer
A+Maintenance
Gerald Garner
Tizag
SQL - Subqueries
Subqueries are query statements tucked inside of
query statements. Like the order of operations from
your high school Algebra class, order of operations
also come into play when you start to embed SQL
commands inside of other SQL commands
(subqueries). Let's take a look at a real world
example involving the orders table and figure out
how to select only the most recent order(s) in our
orders table.
To accomplish this, we are first going to introduce a
built-in SQL function, MAX(). This function wraps
around a table column and quickly returns the current
highest (max) value for the specified column. We are
going to use this function to return the current
"highest", aka most recent date value in the orders
table.
SELECT MAX(day_of_order)
FROM orders
SQL Results:
day_of_order
2008-08-16 00:00:00.000
Now we can throw this query into the WHERE
clause of another SELECT query and obtain the
results to our little dilemma.
SELECT *
FROM orders
WHERE day_of_order = (SELECT
MAX(day_of_order) FROM orders)
:
i day_of_orde quantit
customer product
d r y
A+Maintenanc 2008-08-16 Hangin
3 14
e 00:00:00.000 g Files
SQL - Join
SQL JOIN joins together two tables on a matching
table column, ultimately forming one single
temporary table. The key word here is temporary.
The tables themselves remain intact, and running a
JOIN query does not in any way change the data or
table structure. JOIN is another way to select
specific data from two or more relational tables.
SELECT *
FROM orders
JOIN inventory
ON orders.product = inventory.product;
SQL Join:
USE mydatabase;
SELECT orders.customer,
orders.day_of_order,
orders.product,
orders.quantity as number_ordered,
inventory.quantity as number_instock,
inventory.price
FROM orders
JOIN inventory
ON orders.product = inventory.product
SQL Results:
custome day_of_ prod number_ number_i pri
r order uct ordered nstock ce
2008-
Han
08-01 14.
Tizag ging 11 33
00:00:0 99
Files
0.000
2008-
08-01 Stapl 7.9
Tizag 3 3
00:00:0 er 9
0.000
A+Maint 2008- Han 14.
14 33
enance 08-16 ging 99
00:00:0 Files
0.000
2008- 19"
Gerald 08-15 LCD 179
5 25
Garner 00:00:0 Scre .99
0.000 en
2008- 19"
07-25 LCD 179
Tizag 5 25
00:00:0 Scre .99
0.000 en
2008-
HP
07-25 89.
Tizag Print 4 9
00:00:0 99
er
0.000
SELECT *
FROM orders
RIGHT JOIN inventory
ON orders.product = inventory.product
SQL Results:
id custome day_of pro qua i pro qua pri
r _order duct ntity d duct ntity ce
19" 19"
2008-
LC LC
Gerald 08-15 179
4 D 5 1D 25
Garner 00:00:0 .99
Scre Scre
0.000
en en
19" 19"
2008-
LC LC
07-25 179
5 Tizag D 5 1D 25
00:00:0 .99
Scre Scre
0.000
en en
2008-
HP HP
07-25 89.
6 Tizag Print 4 2 Print 9
00:00:0 99
er er
0.000
NU NU NU 0.9
NULL NULL 3 Pen 78
LL LL LL 9
2008-
08-01 Stap Stap 7.9
2 Tizag 3 4 3
00:00:0 ler ler 9
0.000
2008-
Han Han
08-01 14.
1 Tizag ging 11 5 ging 33
00:00:0 99
Files Files
0.000
2008-
Han Han
A+Main 08-16 14.
3 ging 14 5 ging 33
tenance 00:00:0 99
Files Files
0.000
NU NU NU Lapt 499
NULL NULL 6 16
LL LL LL op .99
SELECT *
FROM orders
LEFT JOIN inventory
ON orders.product = inventory.product
SQL - In
SQL IN is an operator used to pull data matching a
list of values. A scenario where this proves useful
would be if we wanted to retrieve customer data for
two or more customers. We can use the IN operator
to specify a list of customer names, and SQL will
retrieve rows reflecting every customer in the list.
SQL In:
USE mydatabase;
SELECT *
FROM orders
WHERE customer IN ('Gerald
Garner','A+Maintenance');
SQL Results:
i day_of_orde quantit
customer product
d r y
A+Maintenanc 2008-08-16 Hangin
3 14
e 00:00:00.000 g Files
19"
2008-08-15
4 Gerald Garner LCD 5
00:00:00.000
Screen
SQL In:
USE mydatabase;
SELECT product
FROM orders
WHERE customer IN ('Gerald
Garner','A+Maintenance');
Results:
product
Hanging Files
19" LCD Screen
Our results represent a query run to achieve a list of
products sold to two of our customers. Now let's
convert this query to a subquery and use this query as
an input list to check the inventory table to see if we
have any of these items in stock.
SQL In:
USE mydatabase;
SELECT *
FROM inventory
WHERE product in
(SELECT product
FROM orders
WHERE customer IN ('Gerald
Garner','A+Maintenance'));
SQL Results:
id product inventory price
1 19" LCD Screen 25 179.99
5 Hanging Files 33 14.99
By specifying a sub query as our list of values we
were able to take advantage of the relationship our
tables have with each other and create a very
dynamic query. This query saves us the time of
scrolling through the entire inventory table and
checking the stock of each item purchased by any of
our recent customers.
SQL - Not In
SQL NOT IN, as you may have guessed, allows the
developer to eliminate a list of specific values from
the result set.
SELECT *
FROM inventory
WHERE product NOT IN
(SELECT product
FROM orders
WHERE customer IN ('Gerald
Garner','A+Maintenance'));
SQL Results:
id product quantity price
2 HP Printer 9 89.99
3 Pen 78 0.99
4 Stapler 3 7.99
6 Laptop 16 499.99
SQL - Case
SQL CASE is a very unique conditional statement
providing if/then/else logic for any ordinary SQL
command, such as SELECT or UPDATE. It then
provides when-then-else functionality (WHEN this
condition is met THEN do_this).
This functionality provides the developer the ability
to manipulate the presentation of the data without
actually updating or changing the data as it exists
inside the SQL table.
SELECT product,
'Status' = CASE
WHEN quantity > 0 THEN 'in stock'
ELSE 'out of stock'
END
FROM dbo.inventory;
SQL Results:
product Status
19" LCD Screen in stock
HP Printer in stock
Pen in stock
Stapler in stock
Hanging Files in stock
Laptop in stock
SELECT dbo.orders.id,
dbo.orders.customer,
dbo.orders.quantity,
dbo.inventory.product,
dbo.inventory.price
FROM orders
JOIN inventory
ON orders.product = inventory.product
In order to provide results that are much clearer,
we've moved away from selecting every column with
(*). Instead, we've listed each column that will be of
use for the next few steps. Also, let's plan on offering
a 25% off sale on these items.
SQL Results:
id customer quantity product price
1 Tizag 11 Hanging Files 14.99
2 Tizag 3 Stapler 7.99
3 A+Maintenance 14 Hanging Files 14.99
19" LCD
4 Gerald Garner 5 179.99
Screen
19" LCD
5 Tizag 5 179.99
Screen
6 Tizag 4 HP Printer 89.99
SELECT dbo.orders.id,
dbo.orders.customer,
dbo.orders.quantity,
dbo.inventory.product,
dbo.inventory.price,
'SALE_PRICE' = CASE
WHEN price > 0 THEN (price * .75)
END
FROM orders
JOIN inventory
ON orders.product = inventory.product
SQL Results:
i quanti produ SALE_PRI
customer price
d ty ct CE
Hangi
1 Tizag 11 ng 14.99 11.2425
Files
2 Tizag 3 Stapler 7.99 5.9925
Hangi
A+Maintena
3 14 ng 14.99 11.2425
nce
Files
19"
Gerald 179.9
4 5 LCD 134.9925
Garner 9
Screen
19"
179.9
5 Tizag 5 LCD 134.9925
9
Screen
HP
6 Tizag 4 89.99 67.4925
Printer
SQL Results:
USE mydatabase;
SELECT dbo.orders.id,
dbo.orders.customer,
dbo.orders.quantity,
dbo.inventory.product,
dbo.inventory.price,
'SALE_PRICE' = CASE
WHEN (orders.quantity * price) >
100 THEN (price * .65)
ELSE (price * .75)
END
FROM orders
JOIN inventory
ON orders.product = inventory.product
:
i quanti produ SALE_PRI
customer price
d ty ct CE
Hangi
1 Tizag 11 ng 14.99 9.7435
Files
Staple
2 Tizag 3 7.99 5.9925
r
Hangi
A+Maintena
3 14 ng 14.99 9.7435
nce
Files
4 Gerald 5 19" 116.99 134.9925
Garner LCD 35
Screen
19"
5 Tizag 5 LCD 179.99 116.9935
Screen
HP
6 Tizag 4 89.99 58.4935
Printer
SQL - Group By
SQL GROUP BY aggregates (consolidates and
calculates) column values into a single record value.
GROUP BY requires a list of table columns on which
to run the calculations. At first, this behavior will
resemble the SELECT DISTINCT command we
toyed with earlier.
SELECT customer
FROM orders
GROUP BY customer;
SQL Results:
customer
A+Maintenance
Gerald Garner
Tizag
Here, SQL has consolidated like values and returned
those that are unique. In this case, we have actually
duplicated the behavior of SELECT DISTINCT, but
you have also seen firsthand how GROUP BY
accepts a table column as a list and consolidates like
customer values.
SQL Code:
USE mydatabase;
SQL Results:
customer Total Items
A+Maintenance 14
Gerald Garner 5
Tizag 23
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SELECT customer,
SUM((orders.quantity * inventory.price))
AS "COST"
FROM orders
JOIN inventory
ON orders.product = inventory.product
GROUP BY customer;
SQL Results:
product COST
A+Maintenance 209.86
Gerals Garner 899.95
Tizag 1448.77
SQL - Grouping By
Multiple Columns
Like the ORDER BY clause, GROUP BY can accept
a list of table columns on which to group by.
SQL Code:
USE mydatabase;
SELECT day_of_order,
product,
SUM(quantity) as "Total"
FROM orders
GROUP BY day_of_order,product
ORDER BY day_of_order;
SQL Results:
day_of_order product Total
2008-07-25 00:00:00.000 19" LCD Screen 5
2008-07-25 00:00:00.000 HP Printer 4
2008-08-01 00:00:00.000 Hanging Files 11
2008-08-01 00:00:00.000 Stapler 3
2008-08-15 00:00:00.000 19" LCD Screen 5
2008-08-16 00:00:00.000 Hanging Files 14
SQL Having:
USE mydatabase;
SELECT day_of_order,
product,
SUM(quantity) as "Total"
FROM orders
GROUP BY day_of_order,product,quantity
HAVING quantity > 7
ORDER BY day_of_order;
SQL Results:
day_of_order product Total
2008-08-01 00:00:00.000 Hanging Files 11
2008-08-16 00:00:00.000 Hanging Files 14
SQL - Views
SQL VIEWS are data objects, and like SQL Tables,
they can be queried, updated, and dropped. A SQL
VIEW is a virtual table containing columns and rows
except that the data contained inside a view is
generated dynamically from SQL tables and does not
physically exist inside the view itself.
SQL Create View Code:
CREATE VIEW virtualInventory
AS
SELECT * FROM inventory;
SELECT *
FROM virtualInventory;
SQL Results:
id product quantity price
1 19" LCD Screen 25 179.99
2 HP Printer 9 89.99
3 Pen 78 0.99
4 Stapler 3 7.99
5 Hanging Files 33 14.99
6 Laptop 16 499.99
SQL Code:
USE mydatabase;
UPDATE inventory
SET price = '1.29'
WHERE product = 'Pen';
Execute the following query to verify the results:
SELECT *
FROM virtualInventory
WHERE product = 'Pen';
SQL Results:
id product quantity price
3 Pen 78 1.29
SQL - Dates
Date values are stored in date table columns in the
form of a timestamp. A SQL timestamp is a record
containing date/time data, such as the month, day,
year, hour, and minutes/seconds. It's not much
different from the standard date format.
Date Columns:
Column Type Format
time HH:MM:SS
date YYYY-MM-DD
datetime YYYY-MM-DD HH:MM:SS
Date values are stored in the form of a timestamp,
and SQL offers a built-in function called
GETDATE() that returns the current date in the form
of a SQL timestamp.
SELECT GETDATE();
Timestamp Result:
2004-06-22 10:33:11.840
SQL Code:
USE mydatabase;
SELECT
ISDATE('8/24/08') AS "MM/DD/YY",
ISDATE('2004-12-01') AS "YYYY/MM/DD";
SQL Month():
USE mydatabase;
SQL Day():
USE mydatabase;
SQL - Datepart
DATEPART() is a SQL function used to extract all
kinds of date information from timestamps, and it is a
function that is unique to Microsoft's SQL Server
Application.
SQL Datepart:
USE mydatabase;
SQL Results:
Year
2007
SQL Datepart:
USE mydatabase;
SQL Results:
Year Month Day DayofYear Weekday
2007 6 1 152 6
SQL - DateAdd()
DATEADD() is the SQL function used to add and
increment date values. Hours, minutes, months, and
days can be added to any date value. In fact, dates
can be added based on any type of date part
discussed in the SQL DATEPART() lesson.
SQL Code:
USE mydatabase;
SQL Results:
+1 Year
2009-06-31 00:00:00.000
SQL Code:
USE mydatabase;
SELECT DATEADD(day,-1, '2006-06-01') AS "-1
Day";
SQL Results:
-1 Day
2006-05-31 00:00:00.000
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SELECT *
FROM orders
WHERE day_of_order >
(SELECT DATEADD(day,-30, (SELECT
MAX(day_of_order) FROM orders)) AS "-30
Days");
SQL Results:
i day_of_orde quantit
customer product
d r y
2008-08-01 Hangin
1 Tizag 11
00:00:00.000 g Files
2008-08-01
2 Tizag Stapler 3
00:00:00.000
A+Maintenanc 2008-08-16 Hangin
3 14
e 00:00:00.000 g Files
19"
2008-08-15
4 Gerald Garner LCD 5
00:00:00.000
Screen
19"
2008-07-25
5 Tizag LCD 5
00:00:00.000
Screen
6 Tizag 2008-07-25 HP 4
00:00:00.000 Printer
SQL - Delete
Command(s)
In the SQL world, databases, rows, and columns all
have one thing in common: once a DELETE
statement has been executed successfully against
them, the data they once contained is lost forever! Be
very careful with these commands and be sure to
properly backup all data before proceeding with any
type of DELETE command(s).
SQL offers several ways to tackle data deletion. Here
are the differences.
SQL - Delete
DELETE queries work much like UPDATE queries
and like UPDATE, it is much advised to always use
a WHERE condition when running any delete query
or else you risk deleting too much data.
DELETE
FROM orders
WHERE customer = 'A+Maintenance';
SQL Results:
1 Row(s) affected
SQL - Truncate
SQL TRUNCATE is the fastest way to remove all
data from a SQL table, leaving nothing but an empty
shell. You might choose to use this command when
all the data inside of a table needs to be removed but
you'd like the table column definitions to remain
intact.
SQL - Drop
SQL DROP is another command that removes data
from the data store. The DROP command must be
performed on SQL objects including databases,
tables, table columns, and SQL views. Dropping any
of these objects removes them completely from your
SQL application and all data contained in any of the
data objects dropped are lost forever.
SQL - Union
SQL UNION combines two separate SQL queries
into one result set. A JOIN statement adds additional
table columns to a result set (horizontally), UNION
combines row results from one table with rows of
another table (vertically).
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
2 Hively Jessica crew
9 Hicks Freddy crew
10 Harris Joel crew
11 Davis Julie manager
101 Yazzow Jim crew
102 Anderson Craig crew
103 Carlson Kevin crew
104 Maines Brad crew
SQL Code:
SELECT employees.Lastname,
employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
INNER JOIN invoices
ON employees.id = invoices.EmployeeID
UNION
SELECT employees2.Lastname,
employees2.Firstname, invoices.Sale,
invoices.Price
FROM employees2
INNER JOIN invoices
ON employees2.id = invoices.EmployeeID;
SQL Table:
Lastname Firstname Sale Price
Johnson David HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
Davis Julie CK SLD 3.99
Yazzow Jim HOT DOG 1.99
Carlson Kevin LG SFT DRK 1.49
Here we combined a join query with the union clause
to create one table.
SQL Code:
SELECT * FROM employees
UNION ALL
SELECT * FROM employees2;
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
2 Hively Jessica crew
9 Hicks Freddy crew
10 Harris Joel crew
11 Davis Julie manager
101 Yazzow Jim crew
102 Anderson Craig crew
103 Carlson Kevin crew
11 Davis Julie manager
104 Maines Brad crew
SQL Code:
SELECT employees.Lastname,
employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
INNER JOIN invoices
ON employees.id = invoices.EmployeeID
UNION ALL
SELECT employees2.Lastname,
employees2.Firstname, invoices.Sale,
invoices.Price
FROM employees2
INNER JOIN invoices
ON employees2.id = invoices.EmployeeID;
SQL Table:
Lastname Firstname Sale Price
Johnson David HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
Davis Julie CK SLD 3.99
11 Davis Julie manager
Yazzow Jim HOT DOG 1.99
Carlson Kevin LG SFT DRK 1.49
11 Davis Julie manager
11 Davis Julie manager
SQL - Syntax -
(Speaking SQL)
Syntax, by definition, means the study of linguistic
rules and patterns. Every programming language,
including SQL, must follow a unique set of
guidelines termed syntax. Punctuation, spaces,
mathematical operators, and special characters have
special meaning when used inside of SQL commands
and query statements. For example, each and every
SQL command will end with a semi colon (;).
SQL - Syntax:
Capitalization and
Spacing
In some programming languages, capitalizing
commands or excessive spacing may or may not
cause syntax code errors and cause the command to
fail. SQL syntax is very loose when it comes to
capitalization and spacing, allowing a lot of room for
the developer to decide on his/her own preference in
regards to capitalization and spacing.
mydatabase;
Consitency
Clean and Concise
Use of Comments (more on this later)
Scalability
Coding in any language is as much of an art form as
authoring best selling novels and stories. Take pride
in doing so and always do your best to follow good
coding habits.
SQL - Numbers,
Decimals, and Dates
Data Types:
Integers - (3, -17)
Point(Decimal) - (3.23415)
Date - (2004-06-22 10:33:11.840)
SQL - Expressions
SQL Expressions are the pieces of a SQL query that
compare values against other values or perform
arithmetic calculations. Expressions can be found
inside of any SQL command usually in the form of a
conditional statement. In the SQL world,
conditional statements and expressions test or
compare values against other values.
SQL - Boolean
Expressions
Boolean expressions return rows (results) when a
single value is matched.
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
SQL - Numeric
Expression
Numeric Expressions return a single numeric value
instead of an entire row and usually perform
calculations.
SQL Code:
USE mydatabase;
SELECT 15 + 4;
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SELECT COUNT(*) AS "Number of Orders"
FROM orders;
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SQL Code:
USE mydatabase;
SELECT Current_Timestamp;
SELECT GETDATE();
SQL - Historical
Information
In the '60's database software required the use of
complex mainframe machines that were difficult to
maintain and run. Information technologists worked
around the clock monitoring, updating, and manually
uncorrupting these machines.
SQL - Under
Development
Software at the time was still underdeveloped and
several continuous problems plagued database
storage. Transactions happening at the same time
were often combined, mixed together, or even lost
altogether. For instance, say two individuals made a
deposit at exactly the same time from two different
locations. The software was unable to cope with this,
and their bank transactions were completely
switched. Suzy deposited $10,000 while Joe
withdrew $15. Because of the faulty software Joe's
withdrawal was posted on Suzy's account and Suzy's
deposit was posted to Joe's account.
SQL - Platforms
Applications
There are many, many different SQL applications in
existence. A handful of platforms are available for
free and are the preferred choice among individuals
and small businesses. Other SQL platforms are
designed with enterprise level customers in mind and
are much more expensive.
SQL Applications:
IBM's DB2
MySQL
PostgreSQL
Oracle
Microsoft's SQL Server
SQL - Commands
SQL commands are lines of SQL code that ask the
SQL application to perform simple tasks against with
data inside of a database. Often we refer to
commands as query statements or scripts; all of these
terms are synonymous. Most of the commands and
statements you will see in this tutorial are fairly
standard and will work across multiple database
applications despite the fact this tutorial is aimed for
the SQL Server Express user.
SQL commands are declarative sentences or 'orders'
executed against a SQL database. The typical
command is comprised of several different
components including clauses, functions,
expressions, or objects but the only required
components are a SQL Clause and the data object (a
database or a database table).
SQL - Clauses
A SQL clause is the word or phrase that begins each
SQL command statement and the single most
important component to any SQL command.
Looking at the clause of any given SQL command
usually tells the SQL programmer what that
particular command intends to do to the database.
For instance, a SELECT command begins with the
SELECT clause and any level of SQL programmer
will recognize the SELECT query as a command
selecting data from the database.
SQL - Sample
Commands
SQL Code:
SELECT getdate(); -- Selects the current
(server) date and time.
SQL - Structure
The importance of building your tables correctly
could be considered its own form of art.
Psychologists have even gone as far to say that those
with the ability to organize their thoughts and
concepts well tend to be absolutely brilliant (ie
Mozart, Einstein, DaVinci). A database is only
slightly different from the human brain and clear
organization is a must, especially if large quantities
of people will be using the same database.
SQL - Table
Relationships
The key to a large database is having tables with
material that can relate to one another. A great
example is the employee ID. Ever wonder or joke
about being just another number to the company. A
lot of that has to do with the way they set up their
database. A large company is going to have a weekly
payroll and a personal information table. They might
be set up like the following:
personal_info
emp_id last_name first_name
0056 Mynce George
0097 Jenkins Fred
weekly_payroll
emp_id hours rateofpay
0056 37.5 27.00
0097 44.5 22.25
SQL - Predicates
SQL Predicates are found on the tail end of clauses,
functions, and SQL expression inside of existing
query statements. We've actually already covered a
few SQL predicates already and most on this list
should be familiar to you.
SQL Predicates:
AND
OR
LIKE
BETWEEN
AS
TOP(LIMIT)
SQL - Top
SQL Top is used to limit the number of results
returned by a query. The top command is generally
followed by a number that indicates the maximum
number of results to return for a given query.
SQL Code:
use mydatabase;
SELECT TOP 2 *
FROM orders
SQL Results:
id customer day_of_order product quantity
2008-08-01
1 Tizag Pen 4
00:00:00.000
2008-08-01
2 Tizag Stapler 3
00:00:00.000
SQL - Literals
Literal is a term for data types such as strings,
numbers, or boolean values in SQL. These values are
not named by you the programmer; they just exist.
Literal Breakdown:
string literals
'This is a string value'
'5893 Moon River Dr.'
number literals
823
-4.5
3.387920
boolean literals
TRUE
FALSE
1
0