What Is SQL?
What Is SQL?
SQL Syntax
Statement Syntax
AND / OR SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE (add column) ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE (drop column) ALTER TABLE table_name
DROP COLUMN column_name
AS (alias for column) SELECT column_name AS column_alias
FROM table_name
AS (alias for table) SELECT column_name
FROM table_name AS table_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
.......
)
CREATE UNIQUE INDEX CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE VIEW CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
DELETE FROM DELETE FROM table_name
(Note: Deletes the entire table!!)
or
Distinct
SELECT DISTINCT "column_name"
FROM "table_name"
Where
SELECT "column_name"
FROM "table_name"
WHERE "condition"
And/Or
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+
In
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)
Between
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
Like
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN}
Order By
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC]
Count
SELECT COUNT("column_name")
FROM "table_name"
Group By
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
Having
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithematic function condition)
Update Statement
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}
Unfortunately, there are many different versions of the SQL language, but to be in compliance with the ANSI standard, they
must support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and
others).
Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
SQL Queries
With SQL, we can query a database and have a result set returned.
CREATE TABLE
Tables are the basic structure where data is stored in the database. Given that in most cases,
there is no way for the database vendor to know ahead of time what your data storage needs are,
chances are that you will need to create tables in the database yourself. Many database tools
allow you to create tables without writing SQL, but given that tables are the container of all the
data, it is important to include the CREATE TABLE syntax in this tutorial.
Before we dive into the SQL syntax for CREATE TABLE, it is a good idea to understand what
goes into a table. Tables are divided into rows and columns. Each row represents one piece of
data, and each column can be thought of as representing a component of that piece of data. So,
for example, if we have a table for recording customer information, then the columns may include
information such as First Name, Last Name, Address, City, Country, Birth Date, and so on. As a
result, when we specify a table, we include the column headers and the data types for that
particular column.
So what are data types? Typically, data comes in a variety of forms. It could be an integer (such
as 1), a real number (such as 0.55), a string (such as 'sql'), a date/time expression (such as
'2000-JAN-25 03:22:22'), or even in binary format. When we specify a table, we need to specify
the data type associated with each column (i.e., we will specify that 'First Name' is of type char
(50) - meaning it is a string with 50 characters). One thing to note is that different relational
databases allow for different data types, so it is wise to consult with a database-specific reference
first.
Sometimes, we want to provide a default value for each column. A default value is used when
you do not specify a column's value when inserting data into the table. To specify a default value,
add "Default [value]" after the data type declaration. In the above example, if we want to default
column "Address" to "Unknown" and City to "Mumbai", we would type in
You can also limit the type of information a table / a column can hold. This is done through the
CONSTRAINT keyword, which is discussed next.
CONSTRAIN
NOT NULL
By default, a column can hold NULL. If you not want to allow NULL value in a column, you will
want to place a constraint on this column specifying that NULL is now not an allowable value.
Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can include NULL.
UNIQUE
The UNIQUE constraint ensures that all values in a column are distinct.
Column "SID" cannot include duplicate values, while such constraint does not hold for columns
"Last_Name" and "First_Name".
Please note that a column that is specified as a primary key must also be unique. At the same
time, a column that's unique may or may not be a primary key.
CHECK
The CHECK constraint ensures that all values in a column satisfy certain conditions.
Create a Database
To create a database:
CREATE DATABASE database_name
Example
This example demonstrates how you can create a table named "Person", with four columns. The column names will be
"LastName", "FirstName", "Address", and "Age":
CREATE TABLE Person
(
LastName varchar,
FirstName varchar,
Address varchar,
Age int
)
This example demonstrates how you can specify a maximum length for some columns:
CREATE TABLE Person
(
LastName varchar(30),
FirstName varchar,
Address varchar,
Age int(3)
)
Schema for Relation S: (S#,SNAME,CITY,STATUS)
SQL> @e:\studymat\sqlcomm.sql;
Instance of Relation S:
12 rows selected.
SQL>
P is a 5-tuple Table
SQL> @e:\sqlcomm.sql;
Instance of Relation P:
SQL> SELECT * FROM P;
11 rows selected.
SQL>
CREATE TABLE SP
(
S# CHAR(5) NOT NULL,
P# CHAR(5) NOT NULL,
QTY DEC(10,2) CHECK (QTY>0),
FOREIGN KEY (S#) REFERENCES S ON DELETE
CASCADE,
FOREIGN KEY (P#) REFERENCES P ON DELETE
CASCADE,
PRIMARY KEY(S#,P#)
);
SP is a 3-tuple Table
SQL>
S# P# QTY
----- ----- ----------
S1 P1 200
S1 P2 300
S1 P3 100
S1 P0 400
S1 P4 600
S1 P5 200
S1 P6 700
S2 P1 200
S3 P1 400
S4 P2 100
10 rows selected.
SQL>
Creates a unique index on a table. A unique index means that two rows cannot have the same index value.
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
The "column_name" specifies the column you want indexed.
A Simple Index
Creates a simple index on a table. When the UNIQUE keyword is omitted, duplicate values are allowed.
CREATE INDEX index_name
ON table_name (column_name)
The "column_name" specifies the column you want indexed.
Example
This example creates a simple index, named "PersonIndex", on the LastName field of the Person table:
CREATE INDEX PersonIndex
ON Person (LastName)
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column
name:
CREATE INDEX PersonIndex
ON Person (LastName DESC)
If you want to index more than one column you can list the column names within the parentheses, separated by commas:
CREATE INDEX PersonIndex
ON Person (LastName, FirstName)
Drop Index
You can delete an existing index in a table with the DROP INDEX statement.
Truncate a Table
What if we only want to get rid of the data inside a table, and not the table itself? Use the TRUNCATE TABLE command
(deletes only the data inside the table):
TRUNCATE TABLE table_name
ALTER TABLE
The SQL syntax for ALTER TABLE is
[alter specification] is dependent on the type of alteration we wish to perform. For the uses cited
above, the [alter specification] statements are:
Add a column: ADD "column 1" "data type for column 1"
Change a column name: CHANGE "old column name" "new column name" "data type for
new column name"
Change the data type for a column: MODIFY "column 1" "new data type"
The ALTER TABLE statement is used to add or drop columns in an existing table.
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name
Note: Some database systems don't allow the dropping of a column in a database table (DROP COLUMN column_name).
Person:
LastName FirstName Address
Pettersen Kari Storgt 20
Example
To add a column named "City" in the "Person" table:
ALTER TABLE Person ADD City varchar(30)
Result:
LastName FirstName Address City
Pettersen Kari Storgt 20
Example
To drop the "Address" column in the "Person" table:
ALTER TABLE Person DROP COLUMN Address
Result:
LastName FirstName City
Pettersen Kari
These query and update commands together form the Data Manipulation Language (DML) part of SQL:
Other Keywords
ALL - Used to select all records.
DISTINCT - Used to select unique records. Only unique values are returned.
The ORDER BY keyword is used to sort the result.
Orders:
Company OrderNumber
Sega 3412
ABC Shop 5678
W3Schools 6798
W3Schools 2312
Example
To display the company names in alphabetical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company
Result:
Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 6798
W3Schools 2312
Example
To display the company names in alphabetical order AND the OrderNumber in numerical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company, OrderNumber
Result:
Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 2312
W3Schools 6798
Example
To display the company names in reverse alphabetical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC
Result:
Company OrderNumber
W3Schools 6798
W3Schools 2312
Sega 3412
ABC Shop 5678
Example
To display the company names in reverse alphabetical order AND the OrderNumber in numerical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC, OrderNumber ASC
Result:
Company OrderNumber
W3Schools 2312
W3Schools 6798
Sega 3412
ABC Shop 5678
Notice that there are two equal company names (W3Schools) in the result above. The only time you will see the second
column in ASC order would be when there are duplicated values in the first sort column, or a handful of nulls.
CONCAT
Sometimes it is necessary to combine together (concatenate) the results from several different
fields. Each database provides a way to do this:
MySQL: CONCAT()
Oracle: CONCAT(), ||
SQL Server: +
CONCAT(str1, str2, str3, ...): Concatenate str1, str2, str3, and any other strings together. Please
note the Oracle CONCAT() function only allows two arguments -- only two strings can be put
together at a time using this function. However, it is possible to concatenate more than two
strings at a time in Oracle using '||'.
Let's look at some examples. Assume we have the following table:
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
Example 1:
MySQL/Oracle:
SELECT CONCAT(region_name,store_name) FROM Geography
WHERE store_name = 'Boston';
Result:
'EastBoston'
Example 2:
Oracle:
SELECT region_name || ' ' || store_name FROM Geography
WHERE store_name = 'Boston';
Result:
'East Boston'
Example 3:
SQL Server:
SELECT region_name + ' ' + store_name FROM Geography
WHERE store_name = 'Boston';
Result:
'East Boston'
SUBSTR
The Substring function in SQL is used to grab a portion of the stored data. This function is called
differently for the different databases:
Oracle: SUBSTR()
SUBSTR(str,pos,len): Starting with the <pos>th character in string <str> and select the next
<len> characters.
SELECT SUBSTR(store_name, 3)
FROM Geography
WHERE store_name = 'Los Angeles';
Result:
's Angeles'
Example 2:
SELECT SUBSTR(store_name,2,4)
FROM Geography
WHERE store_name = 'San Diego';
Result:
'an D'
Retrieve all vendors with a current balance between 500 and 1000 dollars.
Select VendId, Name, CurrBal [ZZ,ZZZ.99]
from TrnVendor
where CurrBal between 500 and 1000
order by CurrBal;
Retrieve all vendors who are not located in Chicago. Order the results by city.
Select City, Name, VendId
from TrnVendor
where City <> 'Chicago'
order by City;
Retrieve all vendors whose city ends with the letters "do."
Select Name, City, VendId
from TrnVendor
where City like '%do'
order by City;
Retrieve all vendors whose expense account is 4110 or who have a current balance over
1200. The vendor must be located in Chicago.
It is possible to embed a SQL statement within another. When this is done on the WHERE or the
HAVING statements, we have a subquery construct.
SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE [Condition])
[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a text
operator such as "LIKE". The portion in red is considered as the "inner query", while the portion
in green is considered as the "outer query".
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
and we want to use a subquery to find the sales of all stores in the West region. To do so, we use
the following SQL statement:
In the above example, the inner query is first executed, and the result is then fed into the outer
query. This type of subquery is called a simple subquery. If the inner query is dependent on the
outer query, we will have a correlated subquery. An example of a correlated subquery is
shown below:
Notice the WHERE clause in the inner query, where the condition involves a table from the outer
query
EXISTS
In the previous section, we used IN to link the inner query and the outer query in a subquery
statement. IN is not the only way to do so -- one can use many operators such as >, <, or =.
EXISTS is a special operator that we will discuss in this section.
EXISTS simply tests whether the inner query returns any row. If it does, then the outer query
proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing.
SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
(SELECT *
FROM "table_name2"
WHERE [Condition])
Please note that instead of *, you can select one or more columns in the inner query. The effect
will be identical.
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
and we issue the following SQL query:
CASE:
CASE is used to provide if-then-else type of logic to SQL. Its syntax is:
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999
if we want to multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San
Diego' by 1.5, we key in,
"New Sales" is the name given to the column with the CASE statement.
Result:
store_name New Sales Date
Los Angeles $3000 Jan-05-1999
San Diego $375 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999
RUNNING TOTALS
Displaying running totals is a common request, and there is no straightforward way to do so in
SQL. The idea for using SQL to display running totals similar to that for displaying rank: first do a
self-join, then, list out the results in order. Where as finding the rank requires doing a count on
the number of records that's listed ahead of (and including) the record of interest, finding the
running total requires summing the values for the records that's listed ahead of (and including)
the record of interest.
Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20
we would type,
Result:
Name Sales Running_Total
Greg 50 50
Sophia 40 90
Stella 20 110
Jeff 20 130
Jennifer 15 145
John 10 155
The combination of the WHERE clause and the ORDER BY clause ensure that the proper
running totals are tabulated when there are duplicate values.
RANK
Displaying the rank associated with each row is a common request, and there is no
straightforward way to do so in SQL. To display rank in SQL, the idea is to do a self-join, list out
the results in order, and do a count on the number of records that's listed ahead of (and
including) the record of interest. Let's use an example to illustrate. Say we have the following
table,
Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20
we would type,
Result:
Name Sales Sales_Rank
Greg 50 1
Sophia 40 2
Stella 20 3
Jeff 20 3
Jennifer 15 5
John 10 6
PERCENTAGE
To display percent to total in SQL, we want to leverage the ideas we used for rank/running total
plus subquery. Different from what we saw in the SQL Subquery section, here we want to use
the subquery as part of the SELECT. Let's use an example to illustrate. Say we have the
following table,
Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20
we would type,
Result:
Name Sales Pct_To_Total
Greg 50 0.3226
Sophia 40 0.2581
Stella 20 0.1290
Jeff 20 0.1290
Jennifer 15 0.0968
John 10 0.0645
The subquery "SELECT SUM(Sales) FROM Total_Sales" calculates the sum. We can then divide
the individual values by this sum to obtain the percent to total for each row.
CUMULATIVE PERCENT
To display cumulative percent to total in SQL, we use the same idea as we saw in the Percent
To Total section. The difference is that we want the cumulative percent to total, not the
percentage contribution of each individual row. Let's use the following example to illuatrate:
Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20
we would type,
Result:
Name Sales Pct_To_Total
Greg 50 0.3226
Sophia 40 0.5806
Stella 20 0.7097
Jeff 20 0.8387
Jennifer 15 0.9355
John 10 1.0000
The subquery "SELECT SUM(Sales) FROM Total_Sales" calculates the sum. We can then divide
the running total, "SUM(a2.Sales)", by this sum to obtain the cumulative percent to total for each
row.
MEDIAN
To get the median, we need to be able to accomplish the following:
Sort the rows in order and find the rank for each row.
Determine what is the "middle" rank. For example, if there are 9 rows, the middle rank
would be 5.
Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20
we would type,
Result:
Median
20
You will find that Lines 2-6 are the same as how we find the rank of each row. Line 7 finds the
"middle" rank. DIV is the way to find the quotient in MySQL, the exact way to obtain the quotient
may be different with other databases. Finally, Line 1 obtains the value for the middle-ranked row.
Joining Tables
Explanation:
When you join two or more tables, a good idea is to precede the field names with the
table names. This is not mandatory unless the same field name is found in more than one
table.
If you precede the field name with a table name, place a period between the two names.
For example, tablename.fieldname.
You must specify which fields are being joined.
If you do not specify which fields are being joined, the result is what is commonly
referred to as a "Cartesian join" in which all rows in the first table are joined with all
rows in the second table.
You can give each table name an alias, or alternative table name. When you assign an
alias, you can then refer to the table by using its alias.
Employees:
Employee_ID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
Orders:
Prod_ID Product Employee_ID
234 Printer 01
657 Table 03
865 Chair 03
Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Printer'
Result
Name
Hansen, Ola
Using Joins
OR we can select data from two tables with the JOIN keyword, like this:
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair
Result
Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari
OUTER JOIN
Previously, we had looked at left join, or inner join, where we select rows common to the
participating tables to a join. What about the cases where we are interested in selecting elements
in a table regardless of whether they are present in the second table? We will now need to use
the SQL OUTER JOIN command.
The syntax for performing an outer join in SQL is database-dependent. For example, in Oracle,
we will place an "(+)" in the WHERE clause on the other side of the table for which we want to
include all the rows.
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
and we want to find out the sales amount for all of the stores. If we do a regular join, we will not
be able to get what we want because we will have missed "New York," since it does not appear
in the Store_Information table. Therefore, we need to perform an outer join on the two tables
above:
Note that in this case, we are using the Oracle syntax for outer join.
Result:
store_name SALES
Boston $700
New York
Los Angeles $1800
San Diego $250
Note: NULL is returned when there is no match on the second table. In this case, "New York"
does not appear in the table Store_Information, thus its corresponding "SALES" column is
NULL.
Examples:
Retrieve the vendor ID, the vendor name, and the original document amount from the
TrnAPDoc and TrnVendor tables.
Retrieve the vendor ID, vendor name, and the original document amount from the
TrnAPDoc and TrnVendor tables, using a table alias.
Retrieve the vendor ID, vendor name, reference number, and original document amount
from the APDoc and Vendor tables for Vendor V00104. Order the results by RefNbr.
Updating Tables
The UPDATE statement is used to modify the data in a table.
Syntax:
Start transaction;
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
Rollback work;
Commit work;
Explanation:
Issue a Start Transaction command before updating your table. This will allow you to roll
back the changes, if necessary. If you do not issue a Start Transaction command, you will
not be able the roll back your work.
If you find that you have updated a row in error, execute the Rollback Work command.
When you are satisfied with your changes, issue the Commit Work command.
Use a Where clause to specify which rows will be updated. If you do not include a Where
clause, all rows will be updated.
Remember to end each command with a semicolon.
Person:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67
Example:
Change the name of vendor "TV001" to Genie R. Corp., and then roll back the change.
Then change the name of vendor "TV001" to Vanix and commit your work.
To check the vendor name to see that it has reverted to the original, type:
Select VendId, Name
from TrnVendor
where VendId = 'TV001';
Deleting Rows
The DELETE statement is used to delete rows in a table.
Syntax:
Delete from tablename
where fieldname =/<>/ ... value
and/or ...
fieldname =/<>/ ... value
and/or
fieldname =/<>/ ... value
Explanation:
If you do not include a Where clause, all of the rows in the table will be
deleted.
Every table has a primary key -- a field or combination of fields that uniquely
identify each row in the table. VendId is the primary key for the vendor table.
Each vendor is uniquely identified by the vendor Id. RefNbr is the primary key
for APDoc.
If you want to delete a single row of data, you can refer to the row in the Where
clause by using the primary key.
When deleting data, use the Start Transaction command so that any errors can be
rolled back.
Use the Rollback Work command to undo changes.
Use the Commit Work command to finalize changes.
Syntax
DELETE FROM table_name
WHERE column_name = some_value
Person:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
Delete a Row
"Nina Rasmussen" is going to be deleted:
DELETE FROM Person WHERE LastName = 'Rasmussen'
Result
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Examples:
Delete vendor TV011 by executing the following commands.
1. To view the record, type:
Select *
from TrnVendor
where VendId = 'TV011';
2. To start the transaction, type:
Start transaction;
3. To delete the record, type:
Delete from TrnVendor
where VendId = 'TV011 ';
4. To check to make sure the records have been deleted, type:
Select *
from TrnVendor
where VendId = 'TV011';
5. To roll back the deletion, type:
Rollback work;
Delete all vendors with a current balance over 2000 dollars.
1. To view the records, type:
Select Name, CurrBal [-ZZZ,ZZZ.99]
from TrnVendor
where CurrBal > 2000;
2. To start the transaction, type:
Start transaction;
3. To delete the records, type:
Delete from TrnVendor
where CurrBal > 2000;
4. To check to make sure the records have been deleted, type:
Select Name, CurrBal [-ZZZ,ZZZ.99]
from TrnVendor
where CurrBal > 2000;
5. To roll back the deletion, type:
Rollback work;
Inserting Rows
You can insert new rows into a table by using Scalable SQL.
Syntax:
Syntax
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
Example:
Insert the following vendor into the TrnVendor table.
Vendor Id: TV055
Name: Party Games
Address: PO Box 136
City: Chicago
State: IL
Current Balance: 2498.62
1. To start the transaction, type:
Start transaction;
2. To insert the records, type:
Insert into TrnVendor (VendId, Name, Addr1, City, State,
CurrBal )
values ( 'TV055', 'Party Games', 'PO Box 136', 'Chicago', 'IL',
2498.62);
3. To view the record, type:
Select VendId, Name, Addr1, City, State, CurrBal [-ZZZ,ZZZ.99]
from TrnVendor
where VendId = 'TV055';
4. To roll back your work, type:
Rollback work;
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when
using the UNION command all selected columns need to be of the same data type.
Employees_Norway:
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
Employees_USA:
E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Svendson, Stephen
04 Scott, Stephen
Using the UNION Command
Example
List all different employee names in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees
with equal names, and only one of them is listed. The UNION command only selects distinct values.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
SQL Statement 1
UNION ALL
SQL Statement 2
Example
List all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
INTERSECT
Similar to the UNION command, INTERSECT also operates on two SQL statements. The
difference is that, while UNION essentially acts as an OR operator (value is selected if it appears
in either the first or the second statement), the INTERSECT command acts as an AND operator
(value is selected only if it appears in both statements).
[SQL Statement 1]
INTERSECT
[SQL Statement 2]
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there are both store sales and internet sales. To do
so, we use the following SQL statement:
Result:
Date
Jan-07-1999
Please note that the INTERSECT command will only return distinct values.
MINUS
The MINUS operates on two SQL statements. It takes all the results from the first SQL statement,
and then subtract out the ones that are present in the second SQL statement to get the final
answer. If the second SQL statement includes results not present in the first SQL statement,
such results are ignored.
[SQL Statement 1]
MINUS
[SQL Statement 2]
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there are store sales, but no internet sales. To do so,
we use the following SQL statement:
Result:
Date
Jan-05-1999
Jan-08-1999
"Jan-05-1999", "Jan-07-1999", and "Jan-08-1999" are the distinct values returned from "SELECT
Date FROM Store_Information." "Jan-07-1999" is also returned from the second SQL
statement, "SELECT Date FROM Internet_Sales," so it is excluded from the final result set.
Please note that the MINUS command will only return distinct values.
Some databases may use EXCEPT instead of MINUS. Please check the documentation
for your specific database for the correct usage.
What is a View?
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the
database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were
coming from a single table.
Note: The database design and structure will NOT be affected by the functions, where, or join statements in a view.
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: The database does not store the view data! The database engine recreates the data, using the view's SELECT statement,
every time a user queries a view.
Using Views
A view could be used from inside a query, a stored procedure, or from inside another view. By adding functions, joins, etc., to
a view, it allows you to present exactly the data you want to the user.
The sample database Northwind has some views installed by default. The view "Current Product List" lists all active products
(products that are not discontinued) from the Products table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
We can query the view above as follows:
SELECT * FROM [Current Product List]
Another view from the Northwind sample database selects every product in the Products table that has a unit price that is
higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
SELECT * FROM [Products Above Average Price]
Another example view from the Northwind database calculates the total sale for each category in 1997. Note that this view
selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997]