Sie sind auf Seite 1von 132

Course of Database Design and System Analysis

Database System

Databases
Database A database is a collection of data, typically describing the activities of one or more related organizations. For example, a university database might contain information about the following: Entities such as students, faculty, courses, and classrooms. Relationships between entities, such as students' enrollment in courses, faculty teaching courses, and the use of rooms for courses. Databases are useful Many computing applications deal with large amounts of information. Database systems give a set of tools for storing, searching and managing this information.

Introduction
Data: refer to what actually stored in the database. Field: Group of characters with specific meaning Record: Logically connected fields that describe a person, place, or thing File: Collection of related records Information: it refer to the meaning of that data as understood by some users.
Single-User System: is a system in which at most one user can access the database at any given time. Multi-User System: is a system in which many users can access the database at the same time. A major objective of Multi-User Systems is to allow each user to behave as if he or she were working with a single-user system instead. The data in the database will be both integrated and shared.

Database Management System (DBMS)


Collection of interrelated data Is a layer of software between the data as physically stored and users of system Manages very large amounts of data. Set of programs to access the data DBMS contains information about a particular enterprise

Database Applications: Banking: all transactions Airlines: reservations, schedules Universities: registration, grades Sales: customers, products, purchases Manufacturing: production, inventory, orders, supply chain Human resources: employee records, salaries, tax deductions Databases touch all aspects of our lives

Database Management System (DBMS)


Database Management System

(DBMS)
Database

Application Programs

End users

Figure (1): Simplified Picture of a database system

Why Use a DBMS?


Data independence and efficient access. Reduced application development time. Data integrity and security. Uniform data administration. Concurrent access, recovery from crashes.

Database Models
Collection of logical constructs used to represent data structure and relationships within the database

Implementation Database Models


Hierarchical Network Relational

Hierarchical Database Model


Logically represented by an upside down tree
Each parent can have many children Each child has only one parent

Network Database Model


Each record can have multiple parents
Composed of sets Each set has owner record and member record Member may have several owners

Relational Database Model


Perceived by user as a collection of tables for data storage Tables are a series of row/column intersections Tables related by sharing common entity characteristic(s)

Relational Database Model (cont.)

Data Models
A data model is a collection of concepts for describing data. A schema is a description of a particular collection of data, using the given data model. The relational model of data is the most widely used model today.
Main concept: relation, basically a table with rows and columns. Every relation has a schema, which describes the columns, or fields.

Levels of Abstraction
Many views, single conceptual (logical) schema and physical schema.
Views describe how users see the data. Conceptual schema defines logical structure Physical schema describes the files and indexes used. View 1 View 2 View 3

Conceptual Schema

Physical Schema

Example: University Database


Conceptual schema:

Students (sid: string, name: string, login: string, age: integer, gpa:real) Courses (cid: string, cname:string, credits:integer) Enrolled (sid:string, cid:string, grade:string) Relations stored as unordered files. Index on first column of Students. Course_info(cid:string,enrollment:integer)

Physical schema:

External Schema (View):

Instance of Students Relation


Students( sid: string, name: string, login: string, age: integer, gpa: real ) sid 53666 53688 53650 name Jones Smith Smith login age jones@cs 18 smith@ee 18 smith@math 19 gpa 3.4 3.2 3.8

The Entity-Relationship Model

Introduction to Entity-Relationship (E-R) Modeling


Notation uses three main constructs
Data entities Attributes Relationships

Entity-Relationship (E-R) Diagram


A detailed, logical representation of the entities, associations and data elements for an organization or business

Entity-Relationship (E-R) Modeling


Key Terms

Entity
A person, place, object, event or concept in the user environment about which the organization wishes to maintain data Represented by a rectangle in E-R diagrams

Entity Type
A collection of entities that share common properties or characteristics

Attribute
A named property or characteristic of an entity that is of interest to an organization

Entity-Relationship (E-R) Modeling


Key Terms

Candidate keys and identifiers


Each entity type must have an attribute or set of attributes that distinguishes one instance from other instances of the same type Candidate key
Attribute (or combination of attributes) that uniquely identifies each instance of an entity type

Entity-Relationship (E-R) Modeling


Key Terms

Identifier
A candidate key that has been selected as the unique identifying characteristic for an entity type
1. Avoid using intelligent keys

Selection rules for an identifier


1. Choose a candidate key that will not change its value 2. Choose a candidate key that will never be null 3. Consider substituting single value surrogate keys for large composite keys

Notation Guide
ENTITY TYPE
WEAK ENTITY TYPE RELATIONSHIP TYPE

IDENTIFYING RELATIONSHIP TYPE

Notation Guide
ATTRIBUTE
_____

KEY ATTRIBUTE

MULTIVALUED ATTRIBUTE DERIVED ATTRIBUTE


... COMPOSITE ATTRIBUTE

Notation Guide
E1 R E2

TOTAL PARTICIPATION OF E2 IN R
CARDINALITY RATIO 1:N FOR E1:E2 IN R STRUCTURAL CONSTRAINT (min, max) ON PARTICIPATION OF E IN R (Alternative Notation)

1 E1 R

N E2

(min,max)
R E2

ER Diagram Basics
Entity
sname Store Locations

Relationship
manager
qty Keeps pname price descrip

Attributes

Product

Entity
Real-world object distinguishable from other objects (e.g a student, car, job, subject, building ...) An entity is described using a set of attributes In the Company database, an employees car is of lesser importance In the Department of Transportations registration database, cars may be the most important concept In both cases, cars will be represented as entities; but with different levels of detail

Entity Sets
A collection of similar entities (e.g. all employees) All entities in an entity set have the same set of attributes Each entity set has a key Each attribute has a domain Can map entity set to a relation easily
EMPLOYEES SSN 321-23-3241 645-56-7895 NAME Kim Jones SAL 23,000 45,000

Entity Type
Defines set of entities that have the same attributes (e.g. EMPLOYEE) Each Entity Type is described by its NAME and attributes The Entity Type describes the Schema or Intension for a set of entities Collection of all entities of a particular entity type at a given point in time is called the Entity Set or Extension of an Entity Type Entity Type and Entity Set are customarily referred to by the same name

name SSN sal

EMPLOYEE

Notation

Attributes

Notation Key Attributes Value Sets of Attributes Null Valued Attributes Attribute Types Composite Vs. Simple Attributes Single-valued Vs. Multi-valued Attributes Derived Vs. Stored Attributes

Key Attributes: Identifier


Key (or uniqueness) constraints are applied to entity types Key attributes values are distinct for each individual entity in the entity set SSN A key attribute has its name underlined inside the oval Key must hold for every possible extension of the entity type Multiple keys are possible

EMPLOYEE

Composite Vs. Simple Attributes


Composite attributes can be divided into smaller parts which represent simple attributes with independent meaning Simple Attribute: Aircraft-Type Complex Attribute: Aircraft-Location which is comprised of : Aircraft-Latitude Aircraft-Longitude Notation Aircraft-Altitude

There is no formal concept of composite attribute in the relational model

Single Vs. Multivalued Attributes


Simple attributes can either be single-valued or multi-valued Single-valued: Gender = F Notation
Multivalued: Degree = {BSc, MInfTech} Notation

An attribute in the relational model is always single valued - Values are atomic!

Derived Vs. Stored Attributes


Some attribute values can be derived from related attribute values: Notation Age Date - B-day Y-Sal 12 * M-Sal
Age
B-days EMPLOYEE

M-sal
Y-sal

Derived Vs. Stored Attributes


Some attribute values can be derived from attributed values of related entities total-value sum (qty * price)
Order Total-Value

qty price

Item

Representing Attributes
Parenthesis ( ) for composite attributes Brackets { } for multi-valued attributes
Assume a person can have more than one residence and each residence can have multiple telephones {AddressPhone ({ Phone ( AreaCode,PhoneNum ) }, Address (StreetAddresss (Number, Street, AptNo), City,State,PostalCode) ) }

Example of Elements of E-R Model


Entity Sets Departments Professors Students Administrators Attributes Name of Departments, Phone No., Address... Name, SSN, Address of Professors... Relationship Students and Professors are under a certain department Admin manage the campus/ departments

Key Definitions
Primary Key:
One attribute whose value can uniquely identify a complete record (one row of data) within an entity.

Composite Primary Key


A primary key that consists of two or more attribute within an entity.

Foreign Key
A copy of a primary key that exists in another entity for the purpose of forming a relationship between the entities involved.

Degrees of a Relationship
One-to-one (1:1)

Man
One-to-many (1:n)

Woman

Customer
Many-to-many (n:m)

Order

Course

Subject

NOTE: Every many to many relationship consists of two one to many relationships working in opposite directions

Degrees of relationship, alternative representation


One-to-one (1:1)

Man
One-to-many (1:n)

Woman

Customer
Many-to-many (n:m)

Order

Course

Subject

NOTE: Every many to many relationship consists of two one to many relationships working in opposite directions

Notation for optional attributes


1

Person

Car

A person must own at least one car. A car doesnt have to be owned by a person, but if it is, it is owned by at least one person. A person may own many cars.

optional relationship

mandatory relationship

A Sample ER Diagram
Student

Course

Subject

A Student Record Entity Diagram

Example of the 3 elements in E/R Diagram


Attribute Attribute Attribute

Entity A

Entity B

Entity C

Relationship

E-R Diagram : Examples

E-R Diagram : Examples

Add some attributes to entities here Add some attributes to entities here Courses may have another course as pre-requisite Courses may have another course as pre-requisite

Relationship Degree
The degree of a relationship type is the number of participating entity types
2 entities: Binary Relationship 3 entities: Ternary Relationship n entities: N-ary Relationship Same entity type could participate in multiple relationship types
Supplier Supply Project Departments

Works_In

Binary

Employees

Multiple

Assigned_to

Ternary
Part

E-R Diagram : Examples


Title year Name Address

Movies

Stars-in

Stars

length fileType owns Studios

Name

Address

Kinds of Constraints
What kind of constraints can be defined in the ER Model? Cardinality Constraints Participation Constraints Together called Structural Constraints
Constraints are represented by specific notation in the ER diagram

Possible Cardinality Ratios


The Cardinality Ratio for a binary relationship specifies the number of relationship instances that an entity can participate in
Works-In is a binary relationship Participating entities are DEPARTMENT : EMPLOYEE One department can have Many employees Cardinality Ratio is 1 : N

Departments

Works_In

Employees

One-to-Many
A film is directed by at most one director A director can direct any number of films
id Director name Directed Film

title

Director

Directed

Film

Many-to-Many
A film is directed by any number of directors A director can direct any number of films
id Director name Directed Film

title

Director

Directed

Film

One-to-One
A film is directed by at most one director A director can direct at most one film
id Director name Directed Film title

Director

Directed

Film

Another Example
Where would you put the arrow?

age

father
id Person name child FatherOf

Example Cardinality Constraints


How many Employees can work in a Department? One employee can work in only one department How many Employees can be employed by a Department? One department can employ many employees How many managers can a department have? One department can have only one manager How many departments can an employee manage? One employee can have manage only one department

Normalisation

Introduction
Normalization: is the process of efficiently organizing

data in a database with two goals in mind.


First goal: eliminate redundant data

for example, storing the same data in more than one


table

Second Goal: ensure data dependencies make sense


for example, only storing related data in a table

Benefits of Normalization
Less storage space Quicker updates Less data inconsistency Clearer data relationships Easier to add data Flexible Structure

Redundancy and Data Anomalies


Redundant data is where we have stored the same information more than once. i.e., the redundant data could be removed without the loss of information.
Example: We have the following relation that contains staff and department details:
staffNo job SL10 Salesman SA51 Manager DS40 Clerk OS45 Clerk dept 10 20 20 30 dname Sales Accounts Accounts Operations city Stratford Barking Barking Barking

Such redundancy could lead to the following anomalies

Insert Anomaly: We cant insert a dept without inserting a member of staff that works in that department
Update Anomaly: We could change the name of the dept that SA51 works in without simultaneously changing the dept that DS40 works in.

Deletion Anomaly: By removing employee SL10 we have removed all information pertaining to the Sales dept.

Repeating Groups
A repeating group is an attribute (or set of attributes) that can have more than one value for a primary key value.
Example: We have the following relation that contains staff and department details and a list of telephone contact numbers for each member of staff.
staffNo job SL10 Salesman SA51 Manager DS40 Clerk OS45 Clerk dept 10 20 20 30 dname Sales Accounts Accounts Operations city Stratford Barking Barking Barking contact number 018111777, 018111888, 079311122 017111777
079311555

Repeating Groups are not allowed in a relational design, since all attributes have to be atomic - i.e., there can only be one value per cell in a table!

Functional Dependency
Formal Definition: Attribute B is functionally dependant upon attribute A (or a collection of attributes) if a value of A determines a single value of attribute B at any one time.
Formal Notation: A B This should be read as A determines B or B is functionally dependant on A. A is called the determinant and B is called the object of the determinant.
Example:
staffNo job SL10 Salesman SA51 Manager DS40 Clerk OS45 Clerk dept 10 20 20 30 dname Sales Accounts Accounts Operations

Functional Dependencies staffNo job staffNo dept staffNo dname dept dname

Dependencies: Definitions
Partial Dependency when an non-key attribute is determined by a part, but not the whole, of a COMPOSITE primary key.
CUSTOMER Cust_ID 101 101 125 Name AT&T AT&T Cisco
Partial Dependency

Order_ID 1234 156 1250

Dependencies: Definitions
Transitive Dependency when a non-key attribute determines another non-key attribute.
Transitive Dependency

EMPLOYEE Emp_ID 111 122 F_Name Mary Sarah L_Name Jones Smith Dept_ID 1 2 Dept_Name Acct Mktg

Example: Table 1
Title Author1 Author2 ISBN Subject Pages Publisher

Database System Concepts

Abraham Silberschatz

Henry F. Korth

0072958863

MySQL, Computers

1168

McGraw-Hill

Operating System Concepts

Abraham Silberschatz

Henry F. Korth

0471694665

Computers

944

McGraw-Hill

Table 1 problems
This table is not very efficient with storage.
This design does not protect data integrity. Third, this table does not scale well.

First Normal Form


In our Table 1, we have two violations of First Normal Form: First, we have more than one author field, Second, our subject field contains more than one piece of information. With more than one value in a single field, it would be very difficult to search for all books on a given subject.

First Normal Table


Table 2
Title Author ISBN Subject Pages Publisher

Database System Concepts

Abraham Silberschatz

0072958863

MySQL

1168

McGraw-Hill

Database System Concepts

Henry F. Korth

0072958863

Computers

1168

McGraw-Hill

Operating System Concepts


Operating System Concepts

Henry F. Korth

0471694665

Computers

944

McGraw-Hill

Abraham Silberschatz

0471694665

Computers

944

McGraw-Hill

We now have two rows for a single book. Additionally, we would be violating the Second Normal Form A better solution to our problem would be to separate the data into separate tablesan Author table and a Subject table to store our information, removing that information from the Book table:

Subject Table
Subject_ID 1 Subject MySQL

Computers

Author Table
Author_ID 1 2 Last Name Silberschatz Korth First Name Abraham Henry

Book Table
ISBN
0072958863

Title
Database System Concepts Operating System Concepts

Pages
1168

Publisher
McGraw-Hill

0471694665

944

McGraw-Hill

Each table has a primary key, used for joining tables together when querying the data. A primary key value must be unique with in the table (no two books can have the same ISBN number), and a primary key is also an index, which speeds up data retrieval based on the primary key. Now to define relationships between the tables

Relationships
Book_Author Table

Book_Subject Table
ISBN 0072958863 0072958863 0471694665 0471694665 Author_ID 1 2 1 2 ISBN 0072958863 0072958863 0471694665 Subject_ID 1 2 2

Second Normal Form


As the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, the tables must already be in First Normal Form. The Book Table will be used for the 2NF example

2NF Table
Publisher Table
Publisher_ID
1

Publisher Name
McGraw-Hill

Book Table
ISBN 0072958863 Title Database System Concepts Operating System Concepts Pages 1168 Publisher_ID 1

0471694665

944

2NF
Here we have a one-to-many relationship between the book table and the publisher. A book has only one publisher, and a publisher will publish many books. When we have a one-tomany relationship, we place a foreign key in the Book Table, pointing to the primary key of the Publisher Table. The other requirement for Second Normal Form is that you cannot have any data in a table with a composite key that does not relate to all portions of the composite key.

Third Normal Form


Third normal form (3NF) requires that there are no functional dependencies of non-key attributes on something other than a candidate key. A table is in 3NF if all of the non-primary key attributes are mutually independent There should not be transitive dependencies

Boyce-Codd Normal Form


BCNF requires that the table is 3NF and only determinants are the candidate keys

Stages of Normalisation
Unnormalised (UDF)
Remove repeating groups

First normal form (1NF)


Remove partial dependencies

Second normal form (2NF)


Remove transitive dependencies

Third normal form (3NF)


Boyce-Codd normal form (BCNF)

Remove remaining functional dependency anomalies

Remove multivalued dependencies

Fourth normal form (4NF)


Remove remaining anomalies

Fifth normal form (5NF)

DISTRIBUTED DATABASE SYSTEM

DISTRIBUTED DATABASES
WHAT IS A DISTRIBUTED DATABASE?

Distributed: Deals with Physical distribution of data over multiple sites.


A distributed database system is a collection of logically related databases that co-operate in a transparent manner.

DISTRIBUTED DATABASES
Stores logically related database over physically independent sites

DISTRIBUTED DATABASES
ADVANTAGES

Reduced Communication Overhead


Most data access is local, less expensive and performs better.

Improved Processing Power


Instead of one server handling the full database, we now have a collection of machines handling the same database.

Removal of Reliance on a Central Site


If a server fails, then the only part of the system that is affected is the relevant local site. The rest of the system remains functional and available.

DISTRIBUTED DATABASES
ADVANTAGES
Expandability
It is easier to accommodate increasing the size of the global (logical) database.

Local autonomy
The database is brought nearer to its users. This can effect a cultural change as it allows potentially greater control over local data .

Homogeneous & Heterogeneous DDBMSs


Homogeneous: All sites use same DBMS product.
Much easier to design and manage. Approach provides incremental growth Allows increased performance.

Homogeneous & Heterogeneous DDBMSs


Heterogeneous: Sites may run different DBMS products, underlying data models. Sites implemented their own databases-integration considered later. Translations required to allow for Different hardware.
Different DBMS products. Different hardware and DBMS products.

Typical solution is to use gateways.

DISTRIBUTED DATABASES Fragmentation


Why fragment?
Usage: - Apps work with views rather than entire relations. Efficiency: - Its more efficient if data is close to where it is frequently used. Security: - Data not required by local applications is not stored at the local site. Parallelism: - It is possible to run several sub-queries in tandem.

DISTRIBUTED DATABASES Fragmentation


Four types of fragmentation: 1. Horizontal 2. Vertical 3. Mixed 4. Derived

DISTRIBUTED DATABASES
HORIZONTAL DATA FRAGMENTATION
ACCOUNT CUSTOMER BRANCH BALANCE

200 324 345 350 400 456

JONES STRATFORD GRAY BARKING SMITH STRATFORD GREEN BARKING ONO BARKING KHAN STRATFORD

1000.00 200.00 23.17 340.14 500.00 333.00

Horizontal Fragmentation: Consists of a Restriction on a Relation.

e.g.,

( branch = Stratford Account)

DISTRIBUTED DATABASES
HORIZONTAL DATA FRAGMENTATION
ACCT NO.

STRATFORD BRANCH BRANCH CUSTOMER

BALANCE

200 345 456


ACCT NO.

JONES STRATFORD SMITH STRATFORD KHAN STRATFORD


BARKING BRANCH BRANCH CUSTOMER

1000.00 23.17 333.00


BALANCE

324 350 400

GRAY GREEN ONO

BARKING BARKING BARKING

200.00 340.14 500.00

DISTRIBUTED DATABASES
VERTICAL DATA FRAGMENTATION
S# NAME
200 324 456

SITE PHONE NO

LOGIN PASSWORD
JON200T

JONES STRATFORD 0208-500-9000 GRAY

XXYY22 ZZEE56 KJTR78

BARKING 0208-545-7528 GRA324S

KHAN STRATFORD 0208-500-5821 KHA456T

Vertical Fragmentation: Consists of a Projection on a Relation. e.g.,

( S#, NAME, SITE, PHONE NO Student)

DISTRIBUTED DATABASES
VERTICAL DATA FRAGMENTATION
STUDENT ADMINISTRATION SITE PHONE NO. S# NAME

200 324 456

JONES STRATFORD 0208-500-9000 GRAY BARKING 0208-545-7528 KHAN STRATFORD 0208-500-5821

NETWORK ADMINISTRATION S# LOGIN-ID PASSWORD

200 324 456

JON200T GRA324S KHA456T

XXYY22 ZZEE56 KJTR78

Id
100 200 300

Name
A B C

Sal
10K 20K 30K

Dept
D1 D2 D3

Horizontal Fragmentation

Vertical Fragmentation

Rows split : Sal > 20K


Id 100 200 Id 300 Name A B Name C Sal 10K 20K Sal 30K Dept D1 D2 Dept D3
100 200 300

Columns split : Primary Key retained


Id Name A B C Id 100 200 300 Sal 10K 20K 30K Dept D1 D2 D3

Structured Query Language SQL

Introduction to SQL
SQL is a standard language for accessing and manipulating databases What is SQL? SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?

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

SQL DML and DDL


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 database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database

SQL DML and DDL


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 database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key ) DROP INDEX - deletes an index

SQL SELECT Statement

The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. SQL SELECT Syntax SELECT column_name(s( FROM table_name and SELECT * FROM table_name

SQL SELECT Example


The "Persons" table:
P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select the content of the columns named "LastName" and "FirstName" from the table above. We use the following SELECT statement: SELECT LastName, FirstName FROM Persons The result-set will look like this:
LastName Hansen Svendson FirstName Ola Tove

Pettersen

Kari

SELECT * Example
Now we want to select all the columns from the "Persons" table. We use the following SELECT statement : SELECT * FROM Persons Tip :The asterisk (*) is a quick way of selecting all columns! The result-set will look like this:
P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

SQL SELECT DISTINCT Statement


In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can be used to return only distinct (different) values. SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name(s( FROM table_name

SELECT DISTINCT Example The "Persons" table:


P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

SQL SELECT DISTINCT Statement


Now we want to select only the distinct values from the column named "City" from the table above. We use the following SELECT statement: SELECT DISTINCT City FROM Persons The result-set will look like this:
City Sandnes Stavanger

For numeric values: This is correct: SELECT * FROM Persons WHERE Year=1965 This is wrong: SELECT * FROM Persons WHERE Year='1965'

SQL WHERE Clause


The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a specified criterion. SQL WHERE Syntax SELECT column_name(s) FROM table_name WHERE column_name operator value

WHERE Clause Example


The "Persons" table:
P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select only the persons living in the city "Sandnes" from the table above.
We use the following SELECT statement: SELECT * FROM Persons WHERE City='Sandnes'

WHERE Clause Example


The result-set will look like this:
P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Timoteivn 10 Borgvn 23 City Sandnes Sandnes

SQL uses single quotes around text values (most database systems will also accept double quotes). Although, numeric values should not be enclosed in quotes. For text values:
This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove

SQL WHERE Clause


For numeric values:

This is correct: SELECT * FROM Persons WHERE Year=1965 This is wrong: SELECT * FROM Persons WHERE Year='1965'

Operators Allowed in the WHERE Clause


Operator Description

= <>
> < >= <= BETWEEN LIKE IN

Equal Not equal


Greater than Less than Greater than or equal Less than or equal Between an inclusive range Search for a pattern If you know the exact value you want to return for at least one of the columns

SQL AND & OR Operators


The AND & OR operators are used to filter records based on more than one condition. The AND operator displays a record if both the first condition and the second condition is true. The OR operator displays a record if either the first condition or the second condition is true. AND Operator Example
P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to "Svendson":

SQL AND & OR Operators


We use the following SELECT statement: SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson The result-set will look like this:
P_Id LastName FirstName Address City

Svendson

Tove

Borgvn 23

Sandnes

SQL AND & OR Operators


OR Operator Example Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola": We use the following SELECT statement: SELECT * FROM Persons WHERE FirstName ='Tove' OR FirstName ='Ola The result-set will look like this:

P_Id
1 2

LastName
Hansen Svendson

FirstName
Ola Tove

Address
Timoteivn 10 Borgvn 23

City
Sandnes Sandnes

Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions). Now we want to select only the persons with the last name equal to "Svendson" AND the first name equal to "Tove" OR to "Ola": We use the following SELECT statement: SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR FirstName='Ola')

The result-set will look like this:


P_Id 2 LastName Svendson FirstName Tove Address Borgvn 23 City Sandnes

SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. SQL ORDER BY Syntax

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

ORDER BY Example
P_Id LastName FirstName Address City

1
2 3 4

Hansen
Svendson Pettersen Nilsen

Ola
Tove Kari Tom

Timoteivn 10
Borgvn 23 Storgt 20 Vingvn 23

Sandnes
Sandnes Stavanger Stavanger

Now we want to select all the persons from the table above, however, we want to sort the persons by their last name. We use the following SELECT statement:

SELECT * FROM Persons ORDER BY LastName

ORDER BY Example
The result-set will look like this:
P_Id
1 4 3 2

LastName
Hansen Nilsen Pettersen Svendson

FirstName
Ola Tom Kari Tove

Address
Timoteivn 10 Vingvn 23 Storgt 20 Borgvn 23

City
Sandnes Stavanger Stavanger Sandnes

ORDER BY DESC Example: Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.

ORDER BY Example
We use the following SELECT statement:

SELECT * FROM Persons ORDER BY LastName DESC

The result-set will look like this:


P_Id 2 LastName Svendson FirstName Tove Address Borgvn 23 City Sandnes

3
4 1

Pettersen
Nilsen Hansen

Kari
Tom Ola

Storgt 20
Vingvn 23 Timoteivn 10

Stavanger
Stavanger Sandnes

SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...) The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

SQL INSERT INTO Example


We have the following "Persons" table
P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to insert a new row in the "Persons" table. We use the following SQL statement:

INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

SQL INSERT INTO Example


The "Persons" table will now look like this:

P_Id 1 2

LastName Hansen Svendson

FirstName Ola Tove

Address Timoteivn 10 Borgvn 23

City Sandnes Sandnes

3
4

Pettersen
Nilsen

Kari
Johan

Storgt 20
Bakken 2

Stavanger
Stavanger

Insert Data Only in Specified Columns


It is also possible to only add data in specific columns. The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns: INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')

The "Persons" table will now look like this:


P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

4
5

Nilsen
Tjessem

Johan
Jakob

Bakken 2

Stavanger

SQL UPDATE Statement


The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax


UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

SQL UPDATE Example


The "Persons" table:
P_Id 1 2 3 4 5 LastName Hansen Svendson Pettersen Nilsen Tjessem FirstName Ola Tove Kari Johan Jakob Address Timoteivn 10 Borgvn 23 Storgt 20 Bakken 2 City Sandnes Sandnes Stavanger Stavanger

Now we want to update the person "Tjessem, Jakob" in the "Persons" table. We use the following SQL statement: UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob'

SQL UPDATE Example


The "Persons" table will now look like this:
P_Id 1 LastName Hansen FirstName Ola Address Timoteivn 10 City Sandnes

2
3 4 5

Svendson
Pettersen Nilsen Tjessem

Tove
Kari Johan Jakob

Borgvn 23
Storgt 20 Bakken 2 Nissestien 67

Sandnes
Stavanger Stavanger Sandnes

SQL UPDATE Warning Be careful when updating records. If we had omitted the WHERE clause in the example above, like this: UPDATE Persons SET Address='Nissestien 67', City='Sandnes'

SQL UPDATE Example


The "Persons" table would have looked like this:

P_Id 1 2 3 4 5

LastName Hansen Svendson Pettersen Nilsen Tjessem

FirstName Ola Tove Kari Johan Jakob

Address Nissestien 67 Nissestien 67 Nissestien 67 Nissestien 67 Nissestien 67

City Sandnes Sandnes Sandnes Sandnes Sandnes

SQL DELETE Statement


The DELETE statement is used to delete records in a table.

SQL DELETE Syntax


DELETE FROM table_name WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!

SQL DELETE Example


The "Persons" table:
P_Id LastName FirstName Address City

1
2 3 4 5

Hansen
Svendson Pettersen Nilsen Tjessem

Ola
Tove Kari Johan Jakob

Timoteivn 10
Borgvn 23 Storgt 20 Bakken 2 Nissestien 67

Sandnes
Sandnes Stavanger Stavanger Sandnes

Now we want to delete the person "Tjessem, Jakob" in the "Persons" table. We use the following SQL statement: DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'

SQL DELETE Example


The "Persons" table will now look like this:
P_Id LastName FirstName Address City

1
2 3 4

Hansen
Svendson Pettersen Nilsen

Ola
Tove Kari Johan

Timoteivn 10
Borgvn 23 Storgt 20 Bakken 2

Sandnes
Sandnes Stavanger Stavanger

Delete All Rows It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name or DELETE * FROM table_name
Note: Be very careful when deleting records. You cannot undo this statement!

The AVG() Function


The AVG() function returns the average value of a numeric column. SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name SQL AVG() Example

We have the following "Orders" table:


O_Id OrderDate OrderPrice Customer

1
2 3 4 5 6

2008/11/12
2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04

1000
1600 700 300 2000 100

Hansen
Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the average value of the "OrderPrice" fields. We use the following SQL statement: SELECT AVG(OrderPrice) AS OrderAverage FROM Orders

The AVG() Function


The result-set will look like this:
OrderAverage 950 Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value. We use the following SQL statement: SELECT Customer FROM Orders WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)

The result-set will look like this:

Customer Hansen Nilsen Jensen

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria. (1) SQL COUNT(column_name) Syntax The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name

SQL COUNT() Function


(2) SQL COUNT(*) Syntax The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name (3) SQL COUNT(DISTINCT column_name) Syntax The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: SELECT COUNT(DISTINCT column_name) FROM table_name

SQL COUNT() Function Example


(1) SQL COUNT(column_name) We have the following "Orders" table:
O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to count the number of orders from "Customer Nilsen". We use the following SQL statement:

SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Nilsen'

SQL COUNT() Function Example


The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:
CustomerNilsen 2

(2) SQL COUNT(*) Example If we omit the WHERE clause, like this: SELECT COUNT(*) AS NumberOfOrders FROM Orders The result-set will look like this:
NumberOfOrders 6

which is the total number of rows in the table.

SQL COUNT() Function Example


(3) SQL COUNT(DISTINCT column_name) Example Now we want to count the number of unique customers in the "Orders" table. We use the following SQL statement: SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders The result-set will look like this:
NumberOfCustomers

which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.

SQL INNER JOIN Keyword


The INNER JOIN keyword return rows when there is at least one match in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name


SQL INNER JOIN Example
The "Persons" table:
P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari O_Id 1 Address Timoteivn 10 Borgvn 23 Storgt 20 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15 City Sandnes Sandnes Stavanger

The "Orders" table:

2 3 4 5

SQL INNER JOIN Keyword


Now we want to list all the persons with any orders. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this:
LastName Hansen FirstName Ola OrderNo 22456

Hansen
Pettersen Pettersen

Ola
Kari Kari

24562
77895 44678

The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed.

Das könnte Ihnen auch gefallen