an introduction to sql kirk anne computing & information technology suny geneseo [email protected]...

45
An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo [email protected] Nael Alian [email protected]

Upload: candace-parrish

Post on 02-Jan-2016

219 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

An Introduction to SQL

• Kirk AnneComputing & Information Technology

• SUNY Geneseo• [email protected]

Nael [email protected]

Page 2: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

What is a database?

Page 3: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Parts of a database

• Attributes (fields)– An attribute or field is a component of a record that

describes something about an item.• Records

– A record is the representation of an individual item.• Table

– A collection of records• Database

– A collection of tables and rules for accessing the tables

Page 4: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Parts of a database

Record

Attribute/Field

Tables

• Records become “rows”• Attributes/fields become “columns”• Rules determine the relationship between the tables and tie the data together to form a database

Page 5: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

I need a new database!

• Many people ask for “new databases” when in fact they only need a new table within an existing database.

• The data within the tables should be all related somehow.– By owner– By project

Page 6: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Creating a database

• What information are we trying to store?• How do we describe the information?• Phone Book/Contact entries

– Name– Address– Company– Phone Number– URL/Web Page– Age– Height (in meters)– Birthday– When we added the entry

Page 7: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Data Types

• Binary– Database specific binary objects– Pictures, digital signatures, etc.

• Boolean– True/False values

• Character– Fixed width or variable size

• Numeric– Integer, Real (floating decimal point), Money

• Temporal– Time, Date, Timestamp

Page 8: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Phone Book/Contact Record

Name CharacterAddress CharacterCompany CharacterPhone Number CharacterURL/Web Page CharacterAge IntegerHeight Real (float)Birthday DateWhen we added the entry Timestamp

Page 9: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

All you need to know about SQL

Page 10: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

What is SQL?

1. SQL stands for Structured Query Language2. SQL lets you access and manipulate databases3. SQL is an ANSI (American National Standards Institute) standard

Page 11: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

• SQL can execute queries against a database• SQL can retrieve data from a database• SQL can insert records in a database• SQL can update records in a database• SQL can delete records from a database• SQL can create new databases• SQL can create new tables in a database• SQL can create stored procedures in a database• SQL can create views in a database• SQL can set permissions on tables, procedures, and

views

Page 12: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).

The query and update commands form the DML part of SQL:

SELECT - extracts data from a databaseUPDATE - updates data in a databaseDELETE - deletes data from a databaseINSERT INTO - inserts new data into a database

Page 13: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables.

The most important DDL statements in SQL are:

CREATE DATABASE - creates a new databaseALTER DATABASE - modifies a databaseCREATE TABLE - creates a new tableALTER TABLE - modifies a tableDROP TABLE - deletes a tableCREATE INDEX - creates an index (search key)DROP INDEX - deletes an index

Page 14: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Basic SQL Commands

• Creating tables with CREATE• Adding data with INSERT• Viewing data with SELECT• Removing data with DELETE• Modifying data with UPDATE• Destroying tables with DROP

Page 15: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Creating tables with CREATE

• Generic form

CREATE TABLE tablename (column_name data_type attributes…,column_name data_type attributes…,…

)

• Table and column names can’t have spaces or be “reserved words” like TABLE, CREATE, etc.

Page 16: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Phone Book/Contact Record

Name CharacterAddress CharacterCompany CharacterPhone Number CharacterURL/Web Page CharacterAge IntegerHeight Real (float)Birthday DateWhen we added the entry Timestamp

Page 17: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Phone Book/Contact Table

CREATE TABLE contacts (Name VARCHAR(40),Address VARCHAR(60),Company VARCHAR(60),Phone VARCHAR(11),URL VARCHAR(80),Age INT,Height FLOAT,Birthday DATE,WhenEntered TIMESTAMP

);Plan your tables very carefully!

Once created, they are difficult to change!

Page 18: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Phone Book/Contact Table

CREATE TABLE contacts (ContactID INT PRIMARY KEY,Name VARCHAR(40),Address VARCHAR(60),Company VARCHAR(60),Phone VARCHAR(11),URL VARCHAR(80),Age INT,Height FLOAT,Birthday DATE,WhenEntered TIMESTAMP

);If you are going to use the relational nature of a database,don’t forget you need to have a unique way to access records!

There is a way to make the key automatically increment,so you don’t have to worry about which one is next.

Page 19: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Data Types

• Binary– Database specific binary objects (BLOB)

• Boolean– True/False values (BOOLEAN)

• Character– Fixed width (CHAR) or variable size (VARCHAR)

• Numeric– Integer (INT), Real (FLOAT), Money (MONEY)

• Temporal– Time (TIME), Date (DATE), Timestamp (TIMESTAMP)

Page 20: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Create Table  emp ( eno Varchar2(10) Not Null, ename Varchar2(30) ,age Varchar2(5) Null , salary Number(10) , birth_day Date ) ;

التالية القيم على يحتوي جدول انشاء

الحقل اسم نوعة طولةادخال يجب

القيمة

eno Varchar2 10not Null يجب ادخالها

ename Varchar2 30not Null يجب ادخالها

age Varchar2 5 ادخالها اليجب

salary number 10 Null  ادخالها اليجب  

birth_day date - ادخالها اليجب

 

Page 21: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Adding data with INSERT

• Generic Form

INSERT INTO tablename (column_name,…)VALUES (value,…)

Page 22: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Inserting a record into ‘contacts’

INSERT INTO contacts (contactid,name,address,company,phone,url,age,height,birthday,whenentered)

VALUES(1,‘Joe’,’123 Any St.’,’ABC’,’800-555-1212’,‘http://abc.com’,30,1.9,’6/14/1972’,now());

Page 23: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Inserting a partial record

INSERT INTO contacts (contactid,name,phone)VALUES (2,’Jane’,’212-555-1212’);

Page 24: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Automatic key generation

• CREATE SEQUENCE contactidseq;• Change the ContactID line in the

CREATE TABLE to:ContactIDINT DEFAULT nextval(‘contactidseq’) PRIMARY KEY

• Or when inserting into a tableINSERT contacts (contactid,name,phone)VALUES (nextval(‘contactidseq’),’Jack’,

‘716-555-1212’);

Page 25: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Insert Into emp (eno,ename) values ('10' , 'صالح' )

المحددة الحقول الى التالية البيانات اضافة

Insert Into emp (eno,ename) values (&no , '&name' );

ويطلب المحددة الحقول الى التالية البيانات عند اضافة القيمالتنفيذ

Page 26: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Viewing data with SELECT

• Generic FormSELECT column,… FROM table,…

WHERE condition GROUP BY group_by_expressionHAVING condition ORDER BY order_expression

• The most used command• Probably the most complicated also• If used improperly, can cause very long waits because

complex computations

Page 27: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

A few simple SELECTs

• SELECT * FROM contacts;– Display all records in the ‘contacts’ table

• SELECT contactid,name FROM contacts;– Display only the record number and names

• SELECT DISTINCT url FROM contacts;– Display only one entry for every value of URL.

Page 28: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Select  Distinct ename from emp ;

بدون الموظفين اسماء  تكرار عرض

Select  Distinct ename,eno from emp ;

  حقل قيم تكرار دون وارقامهم الموظفين اسماء عرضاالسم

Page 29: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Refining selections with WHERE

• The WHERE “subclause” allows you to select records based on a condition.

• SELECT * FROM contactsWHERE age<10;

– Display records from contacts where age<10

• SELECT * FROM contactsWHERE age BETWEEN 18 AND 35;

– Display records where age is 18-35

Page 30: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Additional selections

• The “LIKE” condition– Allows you to look at strings that are alike

• SELECT * FROM contactsWHERE name LIKE ‘J%’;

– Display records where the name starts with ‘J’

• SELECT * FROM contactsWHERE url LIKE ‘%.com’;

– Display records where url ends in “.com”

Page 31: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Select * from emp ;

              Emp        الجدول بيانات جميع   عرض

Select ename  from emp ;

الموظفين جدول من الموظفين اسماء عرض

Select salary*0.91  from emp ;

  التقاعد منها مخصوم الموظفين رواتب   9عرضالمائة في

Page 32: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Removing data with DELETE

• Generic Form

DELETE FROM table WHERE condition;

DELETE FROM contacts WHERE age<13;

Page 33: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Delete  *  from emp  where eno=12 ;

   رقمة الذي الموظف بيانات جميع 12حذف

Delete  *  from emp  where eno=12 ;

   رقمة الذي الموظف بيانات جميع 12حذف

Delete  eno,name  from emp  where eno=12 ;

    رقمة الذي الموظف واسم رقم 12حذف

Page 34: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Modifying data with UPDATE

• Generic Form

UPDATE table SET column=expression WHERE condition;

UPDATE contacts SET company=‘AOL’WHERE company=‘Time Warner’;

Page 35: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Destroying tables with DROP

• Generic Form

DROP TABLE tablename;

DROP TABLE contacts;

Page 36: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

More about SELECT

Page 37: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Different types of JOINs

• “Inner Join”– Unmatched rows in either table aren’t printed

• “Left Outer Join”– All records from the “left” side are printed

• “Right Outer Join”– All records from the “right” side are printed

• “Full Outer Join”– All records are printed

• Multiple Table Join– Join records from multiple tables

Page 38: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

General form of SELECT/JOIN

SELECT columns,…FROM left_tablejoin_type JOIN right_table ON condition;

SELECT name,phone FROM peopleJOIN phonenumbers ON people.id=phonenumbers.id;

Page 39: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Other versions

SELECT name,phone FROM peopleLEFT JOIN phonenumbers ON people.id=phonenumbers.id;

SELECT name,phone FROM peopleRIGHT JOIN phonenumbers ON people.id=phonenumbers.id;

SELECT name,phone FROM peopleFULL JOIN phonenumbers ON people.id=phonenumbers.id;

Page 40: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

“Theta style” vs. ANSI

• Theta Style (used in most SQL books)

SELECT name,phone,zip FROM people, phonenumbers, address WHERE people.addressid=address.addressid AND

people.id=phonenumbers.id;

• ANSI Style uses JOIN

SELECT name,phone,zip FROM peopleJOIN phonenumbers ON people.id=phonenumbers.idJOIN address ON people.addressid=address.addressid;

Page 41: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Other SELECT examples

• SELECT * FROM contactsWHERE name is NULL;

• SELECT * FROM contactsWHERE zip IN (‘14454’,’12345’);

• SELECT * FROM contactsWHERE zip IN (

SELECT zip FROM addressWHERE state=‘NY’

);

Page 42: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

GROUP BY/HAVING

• The “GROUP BY” clause allows you to group results together with “aggregate functions”– AVG(), COUNT(), MAX(), MIN(), SUM()– COUNT DISTINCT

• HAVING allows you to search the GROUP BY results

Page 43: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

GROUP BY Examples

SELECT company,count(company)FROM contactsGROUP BY company;

SELECT company,count(company)FROM contactsGROUP BY companyHAVING count(company) > 5;

Page 44: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

ORDER BY

• The “ORDER BY” clause allows you to sort the results returned by SELECT.

SELECT * FROM contactsORDER BY company;

SELECT * FROM contactsORDER BY company, name;

Page 45: An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo kma@geneseo.edu Nael Alian naelalian@yahoo.com

Views

• You can use “CREATE VIEW” to create a virtual table from a SELECT statement.

CREATE VIEW contactview AS(SELECT name,phone,zip FROM

people,phonenumbers,addressWHERE people.id=phonenumbers.id AND people.addressid=address.addressid);