Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL...

49
Ch 7 Introduction to SQL

Transcript of Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL...

Page 1: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Ch 7

Introduction to SQL

Page 2: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Learning Objectives

• The 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

Page 3: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

SQL

--a standard for relational DB--used as DDL, DML--portable

Benefits:• .reduced training costs• .enhanced productivity• .application portability• .multiple vendors• .application longevity• .cross systems communications

Page 4: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

CREATE TABLEs:..SEE Pg 223 [RC]; ORACLE HANDOUT; and lesson 17 (BF)

• define fields

• field type

• length

• null/not null

• unique

• primary key

• foreign key

Page 5: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Create Statement

Format:CREATE TABLE tablename

(col name datatype col_constraints, ...

[primary key block][referential constraint]

• .• .• .);

Page 6: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

constraints in Create table statements

Constraint clause can constrain a single column or a group of columns in a table

• It helps maintain data integrity– Primary key– Foreign key– Check conditions

Page 7: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Two ways to specify constraints

part of col def– (col constraint)

at the end of the table– (table constraint)

Page 8: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Primary key

A table can have only ONE primary key

• P.K. can not have NULL values

• for single-column primary key, it can be defined with a column

• For composite it must be defined as a constraint

Page 9: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

WORKER (w-name, age, lodging)

Create table WORKER (w_name varchar(25) Primary key, age number, Lodging varchar(15));orCreate table WORKER (

w_name varchar(25),age number,Lodging varchar(15),primary key (name));

Page 10: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

ENROLL(st_name, cl_name, grade)

PK is st_name, cl_name

Create table Enrollment (ST_name varchar(30) not null,

cl_name varchar(25) not null,grade smallintprimary key (st_name, cl_name));

NOTE: A concatenated (composite) PK must be defined at the END

Page 11: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Foreign Key: (SEE ORACLE HANDOUT AND PAGE 241 (RC), LESSON 22 (bf)

• known as referential integrity constraint

ex:

WORKER (name, age, lodging)

LODGING (lodging_name , No_of_rooms, lodging_Address)

Page 12: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Create table WORKER(name...

age...lodging..REFERENCES LODGING);

• will automatically reference PK of LODGING relation

or• foreign key(lodging) references LODGING(lodging_name)

Page 13: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

CHECK constraint: lesson 22 (bf);227(RC)

format:col type CHECK (condition)

• condition is any valid expression that tests True/false.ex: if age should be between 18 & 65

Create table WORKER(name..age number check (age between 18 and 65),lodging...);

• or age...check (age > 12),• ex:• class char(20) not null check (lower(class) in ('so', 'jr', 'sn') )

Page 14: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Data type(see ORACLE handout)

CHAR(size)   May contain any printable character such as 'A', '3', '&', or ' ' (blanks). Maximum size: 255 characters. Default is 1 byte. Padded on right with blanks to full length of size.

VARCHAR2(size) Variable length character string having a maximum of size bytes (up to 2000). NOT padded with blanks.

NUMBER For a numeric column of up to 40 digits. May be used with or without a size designation. You may use this type for integer fields, or for fields in which you wish to insert the decimal point.

NUMBER(size) For a NUMBER column of the specified size.

NUMBER(size, d) For a NUMBER column of specified size with d digits after the decimal point. For example, NUMBER(6,2) could contain nothing larger than 9999.99 without generating an error message.

DATE The DATE data type is stored in a special internal ORACLE format that includes not just the month, day, and year, but also the hour, minute, and second. However, for most tables, you will not need to be concerned about the time. For inserting a date into a table, use the following format: '10-OCT-06'.

Page 15: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

ex:ORDER(O#, O_date, Promised_date, C#)CUSTOMER(C#, name, address, discount)

CREATE TABLE ORDER

(ORDERNO NUMBER NOT NULL,

ORDERDATE DATE,

PROMISED_DATE DATE,

CUSTOMER_NO CHAR925) NOT NULL REFERENCES CUSTOMER,

PRIMARY KEY(ORDERNO));

Page 16: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Entering Data in tables: lesson 15 (BF), p230(RC) and oracle handout

Format:INSERT INTO table-name VALUES ( val1, val2, val3...)

• values must be in the same order as the cols in the table structure• char must be in single quotes• date must be in quotes and default format (see ORACLE handout)

Ex: ORDER(O#, O_date, Promised_date, C#)

Sql>insert into order values (61396,’6-jun-06', '29-jun-06',1256);

• you can also insert a NULL value in a column..col will be left empty for this row

Ex:insert into order

values(61396,'6-jun-06',null,1256);

Page 17: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

SQL

SQL can be used to manipulate data (DML)format:Sql>SELECT col name(s)

FROM table name(s)[Where condition(s)][Group BY..][HAVING.][UNION\INTERSECT\MINUS[ORDER BY....]

Page 18: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Assume following tables

Customer ( Cust_numb, Cust_name, Cust_address,

cust_state,Cust_balance,Credit_limit, sales_numb)

Salesperson (Sales_numb, sales_name, Sale_add, sales_state, commission_rate,

sales)

Order (Order_numb, Order_date, Cust_numb)

Page 19: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Working with single table

List names and balances of each customer

Sql>Select cust_name, cust_balance

From Customer;

If you want all attributes

Sql>select * from customer;

* Is a wild card and selects everything

Page 20: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Remove duplicate entries

Select name of cities our customers live in

Sql>select distinct cust_state

From customer;

Page 21: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

LOGICAL TESTS AGAINST A SINGLE VALUE:

Used with-- where clause

Creates a horizontal subsection

Mathematical operators:

=, >, >=, <, <=, <> or !=

Page 22: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

List the name of customer whose customer number is 9833

Sql> select cust_name

From customer

Where cust_numb = 9833;

Page 23: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

List the names of salesperson who live in MD

Sql>select sales_name From salesperson Where upper(sales_state) = ‘MD’;

Ex: give the customers who ordered before February 15, 2007.

Sql>select cust_numbFrom order where order_date <’15-Feb-2006’;

Page 24: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

LOGICAL operators:

• And• Or• Not

List the names of salespeople who live in new york and earn more than 5% as commission

Sql>select sales_name

From salesperson

Where upper(sales_ad) = ‘NEWYORK’ AND commission_rate is > 5%

List the names of salespeople who do not live in new york and earn more than 5% as commission

Page 25: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Case Sensitivity test

• Upper

• Lower

Page 26: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

SPECIAL OPERATORS

• In• Between• [not] in• [not] between

• Ex:• WHERE CITY IN ('CHICAGO','BALTIMORE','TAMPA')• WHERE AGE IN (20,21,22)

same as upper(city) =’CHICAGO’ OR upper(city) =’BALTIMORE’ OR upper(city )= ‘TAMPA’

Page 27: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Renaming columns with Aliases/Can do arithmetic calculations on numeric attributesuseful when doing calculations

format:Sql>select colname AS alias from table namewhere. ….

Ex: give commission of salespeople.

Sql>select sales_name, sales*commission_rate as commissionFrom salesperson;

EX:List the names of customers whose credit is greater

than 2000 but less than 10000

Credit between 2000 and 10000

Page 28: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Calculations

+, -, /, *, ^

Order of calculations:

Parentheses,

^,

* and /,

+ and -

Page 29: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Comparisons

Numeric:

Based on numeric values

Character:

Left to right based on collating sequence of the computer

Smithson > Smith

Page 30: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Special operator

Like

Used to find patterns

Allows you select tuples that have similar characters in strings% Any # of char.- For ONE character

List names of customers whose names end with an sSELECT cust_name FROM customerWHERE lower(cust_name) like ‘%s’;

Page 31: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Find the names of salesperson that have a ‘c’ followed by an ‘s’

SORTINGoutput from a query can be ordered• Must always be the last line of a query• ORDER BY colname {asc}

{desc}

default is ascending

Ex: sort all customers by state and descending order of their credit limit

Sql>select *

From customer

Order by cust_state, credit_limit desc;

Page 32: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Exists condition

Main querySub query

If subquery returns values , then ONLY main query is executed

FormatSelect col(s)From table nameWhere exists ( sub query);

Page 33: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

BUILT-IN-FUNCTIONS:

MaxMinSumAvgEx:Select max(credit), cust_name from customer;Has no meaning because ename is an array and

max(salary) is a scalar; cannot associate names with max(sal)

Can not mix built-in functions with other attributes, exception with groups

Page 34: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Count

Used to tally number of not-null values

Format:Count (*)Count(distinct attributename)Count (all attribute name)

count the number of customer in maryland or virginiaSql> select count(*)

from customerwhere upper(cust_state) In (‘MD’, ‘VA’);

Page 35: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Find maximum credit limit of customer whose names contain at least one o

Select max(credit_limit), cust_num

From customer

Where upper(cust_name) like ‘%O%’;

Page 36: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Group By

think of grouping as categorizing: P260(RC), lesson 10(bf)

Allows grouping by rows and then calculate statistics on “groups”

group by state

Will group by state

Group by state, city

Will group by state first, then by city within state

Ex: get the maximum credit limit by state

Sql>select credit_limit, cust_state

From customer

Group by cust_state;

Page 37: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Condition on groups: Having clause

Having puts a condition on groupsEx: select max credit limit by state where

there are atleast two customers

Sql>select max(credit_limit), cust_stateFrom customergroup by cust_stateHaving count(*) >=2;

Page 38: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Copying Part of table

Allows you to break tables in parts

Two steps:

1.Create NEW table

2. Use SQL to fill up the data

Format:

Insert into target_table_name (attribute names)

From source_table

Page 39: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Second method

Create new table and select rows directly from source table in single query

Format:

Create table target_tablename

Select attribute names

From source_table;

Page 40: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Create table credit for customers

1. MethodCreate table credit(c_name char(20) primary key,C_limit number (8,2));

Insert into credit (c_name, c_limit)Select cust_name, cust_limitFrom customer;

2nd Method:Create table credit asSelect cust_name as c_name, cust_limit as c_limitFrom customer;

Page 41: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Altering Table structure (see ORACLE Handout), lesson 17, 247 (RC)

all changes in table structure are done thru ALTER command

• MODIFY allows changing existing column

• ADD allows adding new fields

• DROP to delete a column

Page 42: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Alter format:

ALTER TABLE tablename[ADD (col name...,

colname...)]orALTER TABLE tablename• [MODIFY (col name..)] orALTER TABLE tablename• [Drop (col name..)]

Page 43: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Rules for ADDition

can add a col anytime if not null is not specified

can add multiple col at one time

can add a NULL column in three steps:– add the col without not null– fill every row– modify col to not null

Page 44: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Ex: add a new column soc-sec_no to customer

alter table customeradd (soc_sec_no char(14));

step2:update table customerset soc_sec_no = ‘123-32-4444”;step 3:alter table customer

modify (soc_sec_no not null);

Page 45: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Changing column structure

Ex: increase credit limit to 6,2

Alter table customer

Modify (credit_limit number(6,2));

Page 46: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Creating views (p 262); ch 18(BF)

User’s view of data

Create [or REPLACE VIEW view-name (col name) AS

SQL query

used if this view already exists

Page 47: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Create a view of customers with credit limit of >5000

Create view high_limit as

select cust_name from customer where

Credit_limit >500;

Page 48: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

COLUMN NAMES MUST BE specified if• ..column names are derived• ..two or more cols have the same name

Ex: create a view that keeps track of credit averages

Create view c_avg (cust_avg, cust_name) asSelect cust_name, avg(credit_limit)From customerGroup by cust_name);

Page 49: Ch 7 Introduction to SQL. Learning Objectives The basic commands and functions of SQL How to use SQL for data administration (to create tables, indexes,

Drop a view/advantages of views

Format:

Drop view view_name

Advantages of views:

• provide data independence

• different users can view data differently

• provide security