COMPSCI 280 S2 2016 Enterprise Software Development

COMPSCI 280 S2 2016
Enterprise Software Development
Introduction to Structured Query Language
Today’s Agenda

Topics








Reading:




2
What is SQL
Introduction to SQL
Data Types
Create your own table
Overview of Data Manipulation Commands
Adding one new row to a table
Sample : The Lunches database
Microsoft SQL Server Type Mapping
SQL Data Types for Various DBs
Data Types in a Microsoft SQL Server Compact 4.0 Database
SELECT statement (SQL Server compact)
02
Objectives




3
Explore basic commands and functions of SQL
How to use SQL for data administration (to create tables,
indexes, and views)
How to use SQL for data manipulation (to add, modify, delete,
and retrieve data)
How to use SQL to query a database to extract useful
information
02
What is SQL



SQL stands for Structured Query Language
A Computer Language designed to get information from a
Relational Database
SQL is a Declarative Computer Language


Focus is on the RESULT
Other languages’ focus is Procedural

4
For example, COBOL, Java, Fortran,VB
02
What is a Relational Database





5
All Data is stored in Tables
A Table has two dimensions called Rows and Columns
Tables can hold even the most complex information
All operations begin with Tables and end with Tables
All Data is represented in a Table
02
Parts of a Table




A Table is a Two-dimensional structure that has Rows and
Columns
A Column may be called a Field
A Row may be called a Record
Attribute names
Tables are used everyday in many formats

Tax schedules, Stock quotes, Annuities
Table name
Product
6
Tuples or rows
PName
Price
Category
Manufacturer
Gizmo
$19.99
Gadgets
GizmoWorks
Powergizmo
$29.99
Gadgets
GizmoWorks
SingleTouch
$149.99
Photography
Canon
MultiTouch
$203.99
Household
Hitachi
02
Table Components






7
A Row represents an Object or Event and the information
about it
A Column represents one type of information
A Cell is the smallest part of a Table
Each Cell should express just one Thing
Primary Key columns identify each row
Most Tables are Tall and Thin
02
Introduction to SQL

SQL functions fit into two broad categories:

Data definition language

SQL includes commands to:



Data manipulation language

8
Create database objects, such as tables, indexes, and views
Define access rights to those database objects
Includes commands to insert, update, delete, and retrieve data within
database tables
02
Introduction to SQL (continued)
9
02
Introduction to SQL (continued)
10
02
Data Types


Data type selection is usually dictated by nature of data and
by intended use
Pay close attention to expected use of attributes for sorting
and data retrieval purposes

Characters: CHAR(20),VARCHAR(50)




11
Char: Holds a fixed length string
Varchar: Holds a variable length string
Numbers: INT, BIGINT, SMALLINT, FLOAT
Others: DATE, DATETIME
02
Data Types in Various DBMS

SQL Server Data Types






MySQL Data Types



char/varchar: max 8,000 characters
Text: max 2GB of text data
nchar/nvarchar: for Unicode string
bit: Allows 0, 1 or null; int: 4 bytes ; bigint: 8 bytes
Money: Monetary data; date: Store a date only; datetime
char/varchar: up to 255 characters
text: 65,535 characters
Oracle SQL Server Data Types

Number(P,S)



12
P=precision (total number of significant digits)
S=scale (number of digits after the decimal point)
DATE
A Data and Time
02
Data Types (continued)
13
02
Data types Comparison



14
Characters:
Oracle
MySQL
MS Server Compact
VARCHAR2(SIZE)
VARCHAR(SIZE)
NVARCHAR(SIZE)
CHAR(SIZE)
CHAR(SIZE)
NCHAR(SIZE)
Numeric:
NUMBER(19, 0)
BIGINT
BIGINT
NUMBER(10, 0)
INT
INT
NUMBER(5, 0)
SMALLINT
SMALLINT
FLOAT(126)
FLOAT
FLOAT
Decimal(10,2)
DECIMAL
MONEY
NUMBER(3)
TINYINT(1)
BIT
DATE
DATE
DATE
DATE
DATE/TIME
DATETIME
Date:
02
Exercise 1

Determine which data type makes the most sense for each
column:
Column Name
Description
Example
price
Cost item of an
item for sale
5678.40
zip_code
1010
quantity
239
Best choice of data
type
tax_rate
gender
One character M/F
book_title
meeting time
15
02
Create your own table

The create table statement creates a new table.

When it is first created, this table will not have any rows of data in
it. The command has the following format:
CREATE TABLE table_name(
column_name1 data_type_1,
column_name2 data_type_2,
. . .
);

It consists of:




16
A table name
Name of the columns
Datatypes of the columns
A sequence to the columns
02
Example

MS Server Compact
CREATE TABLE tutorials_tbl(
tutorial_id INT NOT NULL,
tutorial_title NVARCHAR(100) NOT NULL);

Oracle SQL
CREATE TABLE tutorials_tbl(
tutorial_id NUMBER(2) NOT NULL,
tutorial_title VARCHAR2(100) NOT NULL);

MySQL
CREATE TABLE tutorials_tbl(
tutorial_id INT NOT NULL,
tutorial_title VARCHAR(100) NOT NULL);

17
Note: the list of datatypes in Oracle SQL/ MS Sever Compact/ MS Access
are not exactly the same.
02
SQL Constraints

NOT NULL constraint


UNIQUE constraint


Ensures that all values in column are unique
DEFAULT constraint

18
Ensures that column does not accept nulls
Assigns value to attribute when a new row is added to table
02
Data Manipulation Commands







19
Adding table rows
Saving table changes
Listing table rows
Updating table rows
Restoring table contents
Deleting table rows
Inserting table rows with a select subquery
02
Adding one new row to a table

Method 1:
INSERT INTO table_name
VALUES ( ...);



Specifies a value for each column of the table
Values MUST be in the same order as the columns of the table
Method 2:
INSERT INTO table_name (column_name1, column_name2)
VALUES ( ...);


20
Put values in only some of the columns of the table
These columns are listed after the name of the table
02
Example
MS SQL Server Compact

insert into l_lunches values
(2, '16-Nov-2005', 207, '13-oct-2005 10:35:39');
insert into l_employees values
(201, 'Susan', 'Brown', 'Exe', '01-Jun-1998', 30, '3484', null );
insert into l_employees values
(202, 'Jim', 'Kern', 'Sal', '16-Aug-1999', 25, '8722', 201);
insert into l_employees
(employee_id, first_name, last_name, dept_code)
values (201, 'Susan', 'Brown', 'Exe');
21
02
Adding Table Rows

When entering values, notice that:






22
Row contents are entered between parentheses
Character and date values are entered between
apostrophes
Numerical entries are not enclosed in apostrophes
Attribute entries are separated by commas
A value is required for each column
Use NULL for unknown values
02
Null Values

There are certain columns in your table that should always
have values. For example: first_name, last_name

Add “NOT NULL” after the data type
CREATE TABLE table_name(
column_name1 data_type_1 NOT NULL,
. . .
);

If a column in a table is optional, we can insert a new record
without adding a value to this column

23
Add “NULL” after the data type if it is not compulsory to assign the
value when
CREATE TABLE table_name(
column_name1 data_type_1 NULL,
. . .
);
02
Default

If we have a column that we know is usually a specific value,
we can assign it a DEFAULT value.

The value is automatically inserted into the table each time a row is
added if no other value is specified.
CREATE TABLE table_name(
column_name1 data_type_1 NOT NULL DEFAULT = the_value,
. . .
);
24
02
IDENTITY Property


Creates an identity column in a table.
Syntax:
IDENTITY [ (seed,increment) ]




Note:



25
Seed: The value that is used for the first row loaded into the table.
Increment: The incremental value that is added to the identity value
of the previous row that was loaded.
You must specify both the seed and increment, or neither. If neither
is specified, the default is (1,1).
SQL Sever Compact only
The IDENTITY property can be created only on a column of data
type integer or bigint.
A table can have only one IDENTITY column.
02
Example

Create a table:
CREATE TABLE Tool (
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name NVARCHAR(40) NOT NULL
);
INSERT INTO Tool(Name) VALUES ('Screwdriver');
INSERT INTO Tool(Name) VALUES ('Hammer');
INSERT INTO Tool(Name) VALUES ('Saw');
Select * from Tool;
ID
26
Name
1
Screwdriver
2
Hammer
3
Saw
02
Saving Table Changes

Changes made to table contents are not physically saved on
disk until, one of the following occurs:




Syntax:


27
Database is closed
Program is closed
COMMIT command is used
COMMIT [WORK];
Will permanently save any changes made to any table in the
database
02
Sample : The Lunches database


There is a small company with 10 employees. This company will
serve lunch to its employees on three occasions. Each employee
can attend as many of these lunches as his or her schedule permits.
When employees register to attend a lunch, they get to pick what
they want to eat. They may choose from among 10 foods available
to them. They can decide to have a single portion or a double
portion of any of these foods.
Data:






28
l_employees Table
l_department Table
l_lunches Table
l_foods Table
l_suppliers Table
l_lunch_Items Table
02
Relational Tables
l_suppliers
Supplier Id
Supplier Name
l_foods
Supplier Id
Product Code
Menu Item
Description
Price
Price Increase
l_lunch_Items
Lunch Id
Item Number
Supplier Id
Product Code
Quantity
29
l_lunches
Lunch Id
Lunch Date
Employee Id
Date Entered
l_department
Dept Code
Department Name
l_employees
Employee Id
First Name
Last Name
Dept Code
Hire Date
Credit Limit
Phone Number
Manager Id
02
l_department
Dept Code
Department Name
Relationship

Each employee




Lunch ID is the primary key
The l_foods table lists the foods an employee can choose for
his/her lunch

30
l_lunches
Lunch Id
Lunch Date
Employee Id
Date Entered
The l_lunches table registers an employee to attend a lunch


can be identified by an employee ID
has a manager
works for one department
l_employees
Employee Id
First Name
Last Name
Dept Code
Hire Date
Credit Limit
Phone Number
Manager Id
Each food is identified by a supplier ID and a product code
l_foods
l_suppliers
Supplier Id
Supplier Id
Product Code Supplier Name
Menu Item
Description
Price
Price Increase
02
Relationship (con’t)


The l_lunch_item table shows which foods each employee
has chosen for his/her lunch and a single or a double portion.
Check the lunch order for DAN Smith (ID: 207)



employee ID = 207
lunch ID = 2
lunch_Item:




31
ASP SW 2
FRV FF 1
JBR VR 2
VSB AS 1
L_Lunch_Items
Lunch Id
Item Number
Supplier Id
Product Code
Quantity
L_Lunches
Lunch Id
Lunch Date
Employee Id
Date Entered
L_Employees
Employee Id
First Name
Last Name
Dept Code
Hire Date
Credit Limit
Phone Number
Manager Id
02
Exercise 2

Create a table for a contact list. Design a suitable data type
for the following columns:






32
Last_name
First_name
Email
Birthday
Location
Interests
02