Download cos346day3 - Ecom and COS classes

Document related concepts

Serializability wikipedia , lookup

Tandem Computers wikipedia , lookup

DBase wikipedia , lookup

IMDb wikipedia , lookup

Relational algebra wikipedia , lookup

Microsoft Access wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Btrieve wikipedia , lookup

Oracle Database wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Concurrency control wikipedia , lookup

Functional Database Model wikipedia , lookup

Ingres (database) wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

ContactPoint wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

SQL wikipedia , lookup

Clusterpoint wikipedia , lookup

PL/SQL wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
COS 346
Day 3
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-1
Agenda
• Questions?
• Assignment 1 is posted in BlackBoard
– Due TODAY (like RIGHT NOW!)
• Finish Intro to SQL
• Begin discussions on the relational model
and normalization
– Make sure you read ahead
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-2
David M. Kroenke’s
Database Processing:
Fundamentals, Design, and Implementation
Chapter Two:
Introduction to
Structured Query Language
Part Two
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-3
Using MS Access - Results
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-4
Using Access 2007
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-5
Using MS SQL Server
[SQL Query Analyzer]
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-6
Using Oracle
[SQL*Plus]
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-7
Using Oracle
[Quest Software’s TOAD]
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-8
Using MySQL
[MySQL Command Line Client]
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-9
Using MySQL
[MySQL Query Browser]
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-10
Connecting SQL server 2005
• Start Microsoft SQL server management Studio
•Select Littleblack\”lastname” If you are connecting from outside the UMFK
network use littleblack.umfk.maine.edu\”lastname”
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-11
SQL 2005
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-12
Executing SQL
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-13
Sorting the Results: ORDER BY
SELECT *
FROM
ORDER BY
Chapter_2.ORDER_ITEM
OrderNumber, Price;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-14
Sort Order:
Ascending and Descending
SELECT
*
FROM
Chapter_2.ORDER_ITEM
ORDER BY Price DESC, OrderNumber ASC;
NOTE: The default sort order is ASC – does not have to be specified.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-15
WHERE Clause Options: AND
SELECT
FROM
WHERE
AND
*
Chapter_2.SKU_DATA
Department = 'Water Sports'
Buyer = 'Nancy Meyers';
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-16
WHERE Clause Options: OR
SELECT
FROM
WHERE
OR
*
Chapter_2.SKU_DATA
Department = 'Camping'
Department = 'Climbing';
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-17
WHERE Clause Options:- IN
SELECT
FROM
WHERE
*
Chapter_2.SKU_DATA
Buyer IN ('Nancy Meyers',
'Cindy Lo', 'Jerry Martin');
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-18
WHERE Clause Options: NOT IN
SELECT
FROM
WHERE
*
Chapter_2.SKU_DATA
Buyer NOT IN ('Nancy Meyers',
'Cindy Lo', 'Jerry Martin');
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-19
WHERE Clause Options:
Ranges with BETWEEN
SELECT
FROM
WHERE
*
Chapter_2.ORDER_ITEM
ExtendedPrice
BETWEEN 100 AND 200;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-20
WHERE Clause Options:
Ranges with Math Symbols
SELECT
FROM
WHERE
AND
*
Chapter_2.ORDER_ITEM
ExtendedPrice >= 100
ExtendedPrice <= 200;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-21
WHERE Clause Options:
LIKE and Wildcards
• The SQL keyword LIKE can be combined
with wildcard symbols:
– SQL 92 Standard (SQL Server, Oracle, etc.):
• _ = Exactly one character
• % = Any set of one or more characters
– MS Access (based on MS DOS)
•?
•*
= Exactly one character
= Any set of one or more characters
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-22
WHERE Clause Options:
LIKE and Wildcards (Continued)
SELECT
*
FROM Chapter_2.SKU_DATA
WHERE
Buyer LIKE 'Pete%';
MS ACCESS Buyer LIKE ‘Pete*’;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-23
WHERE Clause Options:
LIKE and Wildcards (Continued)
SELECT
FROM
WHERE
*
Chapter_2.SKU_DATA
SKU_Description LIKE '%Tent%';
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-24
WHERE Clause Options:
LIKE and Wildcards
SELECT
*
FROM Chapter_2.SKU_DATA
WHERE
SKU LIKE '%2_ _';
MS ACCESS SKU LIKE ‘*2??’;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-25
SQL Built-in Functions
• There are five SQL Built-in Functions:
– COUNT
– SUM
– AVG
– MIN
– MAX
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-26
SQL Built-in Functions (Continued)
SELECT SUM (ExtendedPrice)
AS Order3000Sum
FROM
ORDER_ITEM
WHERE OrderNumber = 3000;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-27
SQL Built-in Functions (Continued)
SELECT
FROM
SUM (ExtendedPrice) AS
AVG (ExtendedPrice) AS
MIN (ExtendedPrice) AS
MAX (ExtendedPrice) AS
Chapter_2.ORDER_ITEM;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
OrderItemSum,
OrderItemAvg,
OrderItemMin,
OrderItemMax
1-28
SQL Built-in Functions (Continued)
SELECT COUNT(*) AS NumRows
FROM
ORDER_ITEM;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-29
SQL Built-in Functions (Continued)
SELECT COUNT
(DISTINCT Department)
AS DeptCount
FROM
Chapter_2.SKU_DATA;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-30
Arithmetic in SELECT Statements
SELECT Quantity * Price AS EP,
ExtendedPrice
FROM
Chapter_2.ORDER_ITEM;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-31
String Functions in SELECT
Statements
SELECT
FROM
DISTINCT RTRIM (Buyer)
+ ' in ' + RTRIM (Department)
AS Sponsor
Chapter_2.SKU_DATA;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-32
The SQL keyword GROUP BY
SELECT
FROM
GROUP BY
Department, Buyer,
COUNT(*) AS
Dept_Buyer_SKU_Count
Chapter_2.SKU_DATA
Department, Buyer;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-33
The SQL keyword GROUP BY
(Continued)
• In general, place WHERE before GROUP BY.
Some DBMS products do not require that
placement, but to be safe, always put WHERE
before GROUP BY.
• The HAVING operator restricts the groups that
are presented in the result.
• There is an ambiguity in statements that include
both WHERE and HAVING clauses. The results
can vary, so to eliminate this ambiguity SQL
always applies WHERE before HAVING.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-34
The SQL keyword GROUP BY
(Continued)
SELECT
FROM
WHERE
GROUP BY
ORDER BY
Department, COUNT(*) AS
Dept_SKU_Count
SKU_DATA
SKU <> 302000
Department
Dept_SKU_Count;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-35
The SQL keyword GROUP BY
(Continued)
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
Department, COUNT(*) AS
Dept_SKU_Count
Chapter_2.SKU_DATA
SKU <> 302000
Department
COUNT (*) > 1
Dept_SKU_Count;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-36
Querying Multiple Tables:
Subqueries
SELECT SUM (ExtendedPrice)
FROM
ORDER_ITEM
WHERE
SKU IN
(SELECT
FROM
WHERE
AS Revenue
SKU
SKU_DATA
Department = 'Water Sports');
Note: The second SELECT statement is a subquery.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-37
Querying Multiple Tables:
Subqueries (Continued)
SELECT Buyer
FROM
SKU_DATA
WHERE SKU IN
(SELECT
FROM
WHERE
SKU
ORDER_ITEM
OrderNumber IN
(SELECT
OrderNumber
FROM
RETAIL_ORDER
WHERE
OrderMonth = 'January'
AND
OrderYear = 2004));
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-38
Querying Multiple Tables:
Joins
SELECT
FROM
WHERE
Buyer, ExtendedPrice
SKU_DATA, ORDER_ITEM
SKU_DATA.SKU = ORDER_ITEM.SKU;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-39
Querying Multiple Tables:
Joins (Continued)
SELECT
FROM
WHERE
GROUP BY
ORDER BY
Buyer, SUM(ExtendedPrice)
AS BuyerRevenue
SKU_DATA, ORDER_ITEM
SKU_DATA.SKU = ORDER_ITEM.SKU
Buyer
BuyerRevenue DESC;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-40
Querying Multiple Tables:
Joins (Continued)
SELECT
FROM
WHERE
AND
Buyer, ExtendedPrice, OrderMonth
SKU_DATA, ORDER_ITEM, RETAIL_ORDER
SKU_DATA.SKU = ORDER_ITEM.SKU
ORDER_ITEM.OrderNumber =
RETAIL_ORDER.OrderNumber;
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-41
Subqueries versus Joins
• Subqueries and joins both process multiple
tables.
• A subquery can only be used to retrieve data
from the top table.
• A join can be used to obtain data from any
number of tables, including the “top table” of the
subquery.
• In Chapter 7, we will study the correlated
subquery. That kind of subquery can do work
that is not possible with joins.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-42
David M. Kroenke’s
Database Processing
Fundamentals, Design, and Implementation
(10th Edition)
End of Presentation:
Chapter Two Part Two
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition
© 2006 Pearson Prentice Hall
1-43
SQL for SQL Server
Bijoy Bordoloi and Douglas Bock
Chapter 1: Introduction
44
SQL
• SQL, pronounced ‘Sequel’ or simply S-Q-L, is a
computer programming language that was
developed especially for querying relational
databases using a nonprocedural approach.
• The term nonprocedural means that you can
extract information by simply telling the system
what information is needed without telling it how
to perform the data retrieval.
• Transact-SQL or T-SQL is Microsoft's
implementation of the SQL language.
45
Chapter OBJECTIVES
• Develop a basic understanding of the relational
database.
• Learn the general capabilities of a relational database
management system.
• Become familiar with the features of the SQL Server
relational database management system.
• Learn to use the SQL Query Analyzer and SQL Server
Management Studio .
• Become familiar with the basic relational operations
including the selection, projection, and join operations.
• Become familiar with the basic syntax of the SELECT
statement.
• Learn the T-SQL naming conventions.
46
DATA AND INFORMATION
• Information is derived from raw facts known
as data.
• Data has little meaning or usefulness to
managers unless it is organized in some
logical manner.
• One of the most efficient ways to organize
and manage data is through the use of
database management systems (DBMS).
47
DBMS
• Some popular relational DBMS products are the
Oracle RDBMS, IBM’s DB2, Microsoft’s SQL
Server, and Microsoft’s desktop single user
RDBMS named Microsoft Access.
• A DBMS provides both systems development
professionals and information users with an easyto-use interface to their organization’s database.
48
Relational Database
• The most common type of DBMS software in
use today is termed a relational DBMS or
RDBMS.
• A relational database stores data in the form of
tables.
• A table is defined as a collection of rows and
columns.
• The tables are formally known as relations; this
is where the relational database gets its name.
49
TABLE
50
Characteristics of a Relation
(Table)
• The order of rows and columns is immaterial.
• All values are atomic (indivisible) – each row/column
intersection represents a single value. In other words,
‘repeating groups’ are not allowed.
• Every value in a column must be a member of a
conceptual set of atomic values called a domain.
– Unsigned Integer domain 0 – 65364 (8 bits)
• A value may be null, that is, not known or inapplicable.
• A relation, by definition, cannot have duplicate rows.
Every table must have a ‘Primary Key’ ,which
guarantees that there are no duplicate rows.
51
Relating Tables: Foreign Keys
• Foreign key – a (simple or composite) column that
refers to the primary key of some table (including
itself) in a database.
• Foreign and primary keys must be defined on same
data type (and from the same domain).
• A relational DBMS can relate any data field in one
table to any data field in another table as long as the
two tables share a data field that is defined on the same
‘domain’ (the same data type).
• Therefore, if a table has a foreign key then you can
always link (‘join’) this table with the table where this
foreign key is the primary key.
• Foreign keys are also discussed further in Chapter 2.
52
Relating Tables
53
DATABASE MANAGEMENT SYSTEM
• A database management system (DBMS)
manages the data in a database.
• A DBMS is a software package (collection of
programs) that enables the users to create
and maintain a database.
• A DBMS also enables data to be shared.
• SQL is the language used to create and
retrieve data from a relational database
using a RDMS, such as SQL Server.
54
DBMS
55
DATA
• Two types of data are stored within a
database.
• User data: Data that must be stored by
an organization.
• System data: Data the database needs to
manage user data to manage itself. This
is also termed metadata, or the data
about data.
56
DBMS Services
• Data definition for defining and storing
all of the objects that comprise a database
such as tables and indexes
• Data maintenance
• Data manipulation
• Data display
• Data integrity
• Data security Database backup and
recovery
57
SQL Server Versions
Edition
SQL Server
Standard
Edition
Description
Small-and medium-sized businesses without large data
center applications will find this edition best fits their
budget. It supports up to four CPUs and 2GB of
random access memory.
SQL Server
Enterprise
Edition
Aimed at large companies including multinational
conglomerates that are moving into e-commerce. This
version provides high availability and scalability. It
can support up to 32 CPUs and 64GB of random access
memory.
SQL Server
Developer
Edition
This is like the Enterprise Edition, but for system
developers. It cannot be licensed for use in a
production environment.
58
SQL Server Versions Contd.
SQL Server
Desktop
Edition
SQL Server
2000 Personal
Edition
SQL Server
2000 Windows
CE Edition
This Edition has the SQL Server database engine, but
not all of the management tools or analysis services.
Database size for this edition is limited to 2GB. It
supports full application development and deployment
for small business applications.
This version has much of the functionality of the
Standard Edition. It can service small groups of
concurrent access users. It will run on desktop
Windows operating systems from Windows 98 to
Windows 2000 Professional Edition.
This runs on the Windows CE operating system for
pocket PC devices.
59
SQL Server 2005 Editions
http://www.microsoft.com/sqlserver/2005/en/us/compare-features.aspx
60
SQL Server Features
Feature
Description
Internet
standard
support
SQL Server uses Microsoft's new .NET technology to support data
exchange across the Internet including new detailed support for the
extensible-markup language, or XML.
Scalability
SQL Server can be used to build very large, multiprocessor systems.
Security
mechanisms
SQL Server's sophisticated security mechanisms control access to
sensitive data through an assortment of privileges, for example, the
privilege to read or write specific information within a database.
Backup and
recovery
SQL Server's sophisticated backup and recovery programs minimize data
loss and downtime if problems arise.
61
SQL Server Features Cont.
Space
management
Open
connectivity
Tools and
applications
SQL Servers automated space management capability
makes it easy for a database administrator to manage disk
space for storage. These capabilities also include the
ability to specify subsequent allocations on how much
disk space to set aside for future requirements.
SQL Server's open connectivity functionality provides
uninterrupted access to the database throughout the day.
It also provides open connectivity to and from other
vendors’ software.
SQL Server provides a wide range of development tools,
end-user query tools, and support for third-party software
applications that are used to model business processes
and data and to generate program language code
62
automatically.
SQL: DDL and DML
•
SQL is used by SQL Server for all interaction
with the database. SQL statements fall into
two major categories:
1. Data Definition Language(DDL): Set of SQL
commands that create and define objects in a
database.
2. Data Manipulation Language(DML): Set of
SQL commands that allow users to
manipulate the data in a database.
63
SQL
• SQL is basically a free format language. This
means that there are no particular spacing rules
that must be followed when typing SQL
commands.
• SQL is a nonprocedural language. This means
that the user only has to specify the task for the
DBMS to complete, but not how the task is to
be completed. The RDBMS parses (converts)
the SQL commands and completes the task.
64
Procedural and Nonprocedural
Nonprocedural
SELECT emp_last_name,
emp_first_name
FROM employee
WHERE emp_last_name =
'BOCK';
Procedural
intIndex = 1
DO WHILE intIndex <=
Count_Of_Rows
If emp_last_name =
'BOCK' Then
DISPLAY
emp_last_name,
emp_first_name
End If
intIndex += 1
LOOP
65
SQL Query Analyzer
GUI can be used to:
– Create databases.
– Develop, test, and debug stored procedures.
– Run SQL scripts – these are miniature programs that contain either
DDL or DML commands or a combination of these commands.
An example would be a script to create a database, and then
populate the tables in the database with data.
– Optimize system performance.
– Analyze query plans – these are the plans that the DBMS generates
for processing a query.
– Maintain and manage statistics concerning database performance.
– Generate tune table indexes – the indexes are supposed to improve
system performance for data retrieval.
66
SQL Query Analyzer Contd.
67
SQL Query Analyzer Contd.
68
SQL Query Analyzer Contd.
69
SQL Query Analyzer Contd.
70
SQL Server management studio
71
SQL Server management studio
72
73
Creating a Database
• When SQL Server is initially installed, five system
databases are generated. These are named: (1)
master, (2) model, (3) msdb, (4) distribution, and
(5) tempdb.
• When you create a new database in SQL Server,
the DBMS uses the model database as a template
to create a new database.
• The command to create a user database is :
CREATE DATABASE <database_name>
Note: You must have prior authorization from your
system administrator to execute this command.
74
75
Personal Databases
• Everyone has their own database
on little black
• Admin access to personal
database restricted to Tony and
individual student
76
Creating a Database: In-Class Exercise
• Invoke SQL management Studio, Log on to SQL
Server, and Create a database called Company in your
own database:
CREATE DATABASE Company;
• Simply type the command in the Editor pane of the
Query window and click the Execute Query button (or
press the F5 key).
• Once the Company database has been created, you will
see it listed in the Object Browser. If you do not see it in
the Object Browser, simply right-mouse click and select
the Refresh option to refresh the screen.
77
The Company Database
• Throughout this textbook you will study SQL
commands against the backdrop of a sample
database called the Company database, which is
described in Appendix A. You may wish to
familiarize yourself with Appendix A at this time.
• Note that the Company database you just created
does not contain any data yet. Chapter 2 explains
the commands to populate a database through
creation of tables and insertion of rows in much
more detail.
78
Using a Database
• After you have CREATED your database(s)
you must use the USE command to select a
database for future processing.
• You can type the USE command into the
Editor pane and execute it also.
USE Company;
The command(s) completed successfully.
79
Executing Scripts
•
•
•
Sometimes you need to execute a script that
contains a series of SQL statements. The
Editor pane can be used to create and save a
script as shown in Figure 1.8.
Simply select the Editor pane to make it the
active window, then use the toolbar Save option
and specify the location, file name, and file
format when the Save Query dialog box
displays.
You should use the default filename extension
of .sql when naming a script file.
80
Executing Scripts (Fig: 1.8)
81
Executing Scripts
• You can also open scripts and execute
them, even if they were created with
another text editor, such as Microsoft
Notepad or Word.
• Figure 1.9 shows this operation.
• Select the Load SQL Script toolbar
button and when the Open Query File
dialog box displays, locate and select the
name of the file to be opened.
82
Executing Scripts (Fig: 1.9)
83
Creating, Saving, and Running
a Sample Script
• Practice creating, saving, and running a
sample script file named Product.sql as
shown in SQL Examples 1.1 and 1.2.
• Type the code exactly as shown.
• Do not worry if you do not understand
(you are not expected to) the code at this
point. Things will become clearer as we
cover more materials in later chapters.
84
Project.sql
/* SQL Example 1.1 */
/* Product.sql script – creates a Product table */
/* in the Company database.
*/
USE Company;
CREATE TABLE product (
pro_id
SMALLINT PRIMARY KEY,
pro_description VARCHAR(25),
pro_cost
MONEY );
GO
INSERT INTO product VALUES (4, ‘Kitchen Table’, 879.95);
INSERT INTO product VALUES (6, ‘Kitchen Chair’, 170.59);
INSERT INTO product VALUES (12, ‘Brass Lamp’, 85.98);
GO
SELECT * FROM product;
/* end of script file */
85
RELATIONAL OPERATIONS: OVERVIEW
• SQL operations for creating new tables,
inserting table rows, updating table rows,
deleting table rows, and querying databases
are the primary means of interfacing with
relational databases.
• The SELECT statement is used primarily to
write queries that extract information from
the database, which is a collection of related
tables.
86
RELATIONAL OPERATIONS
• The ability to select specific rows and
columns from one or more tables is referred
to as the fundamental relational operations,
and there are three of these operations:
– Selection
– Projection
– Join
• The purpose of the next few slides is just to
familiarize you with each of these
operations. We will study these operations
in detail in later chapters.
87
Selection Operation
• A selection operation selects a subset of rows
in a table (relation) that satisfy a selection
condition. That subset can range from no
rows to all rows in a table. The SELECT
statement below selects a subset of rows
through use of a WHERE clause.
SELECT emp_ssn, emp_last_name, emp_first_name
FROM employee
WHERE emp_ssn = '999111111';
emp_ssn emp_last_name
------------- --------------------999111111 Bock
emp_first_name
-------------Douglas
88
Projection Operation
• A projection operation selects only certain
columns from the table, thus producing a subset
of all available columns.
• The result table can include anything from a
single column to all the columns in the table.
89
EXAMPLE
• This SELECT statement selects a subset
of columns from the employee table by
specifying the columns to be listed.
SELECT emp_ssn, emp_first_name,
emp_last_name
FROM employee;
emp_ssn
--------999111111
999222222
999333333
more rows
emp_first_name
---------------Douglas
Hyder
Dinesh
will display…
emp_last_name
-------------Bock
Amin
Joshi
90
Join Operation
• A join operation combines data from two or
more tables based upon one or more common
column values.
• The relational join is a very powerful operation
because it allows users to investigate
relationships among data elements.
• The following SELECT statement displays
column information from both the employee
and department tables.
• This SELECT statement also completes both
selection and projection operations.
91
Join Operation: Example
92
JOIN: Example
• The tables are joined upon values stored in the
department number columns named emp_dpt_number in
the employee table and dpt_no in the department table.
SELECT emp_ssn, emp_first_name, emp_last_name, dpt_name
FROM employee, department
WHERE emp_dpt_number = dpt_no;
emp_ssn emp_first_name
------------- ---------------999111111 Douglas
999222222 Hyder
999333333 Dinesh
more rows will display…
emp_last_name
-------------------Bock
Amin
Joshi
dpt_name
-------------Production
Admin and Records
Production
93
SQL Syntax
•
Now that you've seen some basic SQL
statements, you may have noticed that SQL
requires you to follow certain syntax rules;
otherwise, an error message is returned by
the system and your statements fail to
execute.
94
T-SQL Naming Rules
• The rules for creating identifiers in TSQL differ slightly from those in the
ANSI/ISO-92 SQL standard.
• Identifiers are the names given by
information system developers and
system users to database objects such as
tables, columns, indexes, and other
objects as well as the database itself.
95
T-SQL Naming Rules Contd.
There are several rules for naming database objects that must be
followed:
•
•
•
•
•
Identifiers must be no more than 128 characters.
Identifiers can consist of letters, digits, or the symbols #, @, $, and
_ (underscore).
The first character of an identifier must be either a letter (a-z, AZ) or the #, @ or _ (underscore) symbol. After the first character,
you may use digits, letters, or the symbols $, #, or _ (underscore).
Temporary objects are named by using the # symbol as the first
character of the identifier. Avoid using this symbol as the leading
character when naming permanent database objects.
The @ symbol as the first character of an identifier denotes a
variable name. Avoid using this symbol as the leading character
when naming other database objects.
SQL keywords such as SELECT and WHERE cannot be used as
an identifier.
96
SELECT Statement Syntax Overview
•
Each select statement must follow precise
syntactical and structural rules.
•
For example, you cannot place the FROM clause
before the SELECT clause, or place the FROM
clause after the WHERE clause or the ORDER BY
clause, and so on.
•
The basic syntax (including the order of various
clauses) is as follows:
97
SELECT Statement Syntax Overview
Contd.
SELECT [DISTINCT | ALL] [TOP n [PERCENT][WITH TIES]]
{* | select_list}
[INTO {table_name} ]
[FROM {table_name [alias] | view_name}
[{table_name [alias] | view_name}]]...
[WHERE condition | JOIN_type table_name ON
(join_condition) ]
[GROUP BY condition_list]
[HAVING condition]
[ORDER BY {column_name | column_# [ ASC | DESC ] } ...
98
SELECT Statement Syntax
• you will learn the various clauses
of the SELECT statement
throughout your study of this
text.
• Welcome to the study of SQL!
99
SUMMARY
This chapter:
• Introduced you to the basics of relational
database, DBMS, and SQL.
• Familiarized you with the features of the SQL
Server DBMS including its GUI, the SQL
Query Analyzer.
• Familiarized you with the basic relational
operations including the selection, projection,
and join operations.
• Familiarize with the basic syntax of the
SELECT statement.
100