You are on page 1of 43

Advance

Database System 1
Herat University
Computer Science Faculty


Foawziah Naseri
Foawziah_naseri@yahoo.com

April-11-2015

4/13/15

Overview

What is SQL?
IntroducOon to SQL
CreaOng Database in SQL
CreaOng Table Command in SQL
ARributes Data Types
Alter Command
InserOng Data
Specifying Constrains in SQL
Schema Change Statements
Joining with Form
Where Clause
Ordering a Query Result

What is SQL?
OVen called Structured Query Language, although
SQL is the ocial name
Developed in the 1970s as the rst commercial
languages for Codds relaOonal model
SQL is not a procedural language.
SQL in combinaOon with a procedural language, such
as C, to create a complete applicaOon.

What is a query?
What is a Query ?
A query is a question posed to a
database
Queries are expressed in a high-level
declarative manner
Algorithms needed to answer the query
are not specified in the query

What is a query?
Examples:
Mouse click on a map symbol (e.g. road)
may mean
What is the name of road pointed to by
mouse cursor ?
Typing a keyword in a search engine (e.g.
google, yahoo) means
Which documents on web contain given keywords?
SELECT S.name FROM Senator S WHERE S.gender = F
means

Which senators are female?

What is a query language?


What is a query language?
A language to express interesOng quesOons
about data
A query language restricts the set of
possible queries
Examples:
Natural language, e.g. English, can express
almost all queries

What is a query language?


Computer programming languages, e.g. Java,
can express computable queries
however algorithms to answer the query is
needed
Structured Query Language(SQL)
Can express common data intensive queries
Not suitable for recursive queries
Graphical interfaces, e.g. web-search, mouse
clicks on a map
can express few dierent kinds of queries

An Example of World Database ER


Diagram

An Example World Database


RelaOons
Country( Name, Capital, Popula-on, Area,
province..)
City(Name, Country, district, Shape)
River(Name, Origin, Length, Shape)
Keys
Primary keys are Country.Name, City.Name,
River.Name
Foreign keys are River.Origin, City.Country

What is SQL?
The heart of SQL is the select-query:

1. Select A1, A2, .,An == the projection A1, A2, .,An

2. from R1, R2, Rn == the C.product R1, R2 Rn
Where p == the selection ()



This means that such a select statement is

equivalent to the algebra expression:


IntroducOon to SQL

SQL is now the standard language for commercial


relational DBMSs.

SQL is a comprehensive database language:

It has statements for data definitions, queries, and
updates.

it is both a DDL and a DML.

It has facilities for defining views on the database, for
specifying security and authorization, for defining
integrity constraints, and for specifying transaction
controls.

Has rules for embedding SQL statements into a
general-purpose programming language such as Java,
COBOL, or C/C++.

Crea0ng tables
CREATE DATABASE world;
A database table is a two-dimensional array
made up of rows and columns. You can create
a table by using the SQL CREATE TABLE
command. Within the command, you specify
the name and data type of each column.

IntroducOon to SQL

CreaOng Table Command in SQL


Checking whether a table is created or not

oShow Tables

To see the list of attributes of a table

oDescribe <table name>

oDesc <table name>

oEx: Describe student


CreaOng Database in SQL


To check whether a database is created or not and
also to see which databases are available

Show databases

To work on this database afterwards, use the USE


statement

Use database_name

EX: Use hostel

CreaOng Table Command in SQL


The relations declared through CREATE TABLE
statements are called base tables (or base relations)

othis means that the relation and its tuples are
actually created and stored as a file by the DBMS.

CREATE TABLE Students



( sid CHAR(9) NOT NULL,



name VARCHAR(20) NOT NULL, Bdate
DATE, Address VARCHAR(30)



age INTEGER;

Each sql statement ends with semicolon

ARributes Data Types


Numberic

Integer Numbers:

oInt, smallint, Integer

Float Numbers

oFloat, real, double

Character / String

oChar (n) / Character(n)

oVarchar (n)

ARributes Data Types


Date

YYYY-MM-DD

Time

HH:MM:SS

Time (i)

HH:MM:SS:i.i

Shows the fraction of seconds

TimeStamp

Includes both time and date stamps

Schema Change Statements


SomeOmes called Schema EvoluOon Commands
oCan be used to alter a schema by adding or
dropping tables, attributes, constrains and
other schema elements

oCan be done while the database is operational

oDoes not require recompilation of the database
schema

Drop Command
oCan be used to drop named schema elements
such as tables, domains or constrains

oDrop can be used to drop a schema too.

Alter Command
Is used to change the
deniOon of a base
table or other named schema elements
For base tables, the possible alter table
acOons include:
oAdding or dropping a column
oChanging a column deniOon
Ex: Adding a new column to table Employee
ALTER table COMPANY.EMPLOYEE ADD
COLUMN Job VARCHAR(10)

DeleOng Data
To delete tuples from a table we use:


delete from table where condition



The where clause works like in a select
statement. e.g.




delete from books where author=Tolkien;

DeleOng a table
We can delete whole tables with the drop
table command.
Example:
drop table books;

ARenOon: the whole table with all data is
deleted immediately

Specifying Constrains in SQL


Specifying Primary Key

keys and referential integrity constraints
are very important,

There are special clauses within the
CREATE TABLE statement to specify
them

If a primary key has a single attribute,
the clause can follow the attribute
directly.

oEx: age INT PRIMARY KEY

Specifying Constrains in SQL


Here is the syntax to dene ID aRribute as a
primary key in a CUSTOMERS table.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,





NAME VARCHAR (20) NOT NULL,


AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) );

Specifying Constrains in SQL


To create a PRIMARY KEY constraint on the
"ID" column when CUSTOMERS table already
exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY
(ID);
DeleOng PRIMARY KEY
ALTER TABLE CUSTOMERS DROP PRIMARY
KEY ;

Specifying Constrains in SQL


UNIQUE Constraint prevents two records from
having idenOcal values in a parOcular column. In
the CUSTOMERS table, for example, you might
want to prevent two or more people from having
idenOcal age.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) );

Specifying Constrains in SQL


If CUSTOMERS table has already been created,
then to add a UNIQUE constraint to AGE
column, you would write a statement similar
to the following:
ALTER TABLE CUSTOMERS MODIFY AGE INT
NOT NULL UNIQUE;
Drop a UNIQUE Constraint
ALTER TABLE CUSTOMERS DROP CONSTRAINT
myUniqueConstraint;

COMMIT and ROLLBACK Command


The COMMIT command permanently saves all
changes
Such as rows added, aRributes modied, and
rows deleted made to any table in the database
Syntax: COMMIT;
ROLLBACK undoes any changes since the last
COMMIT command and brings the data back to the
values that existed before the changes were made.
Syntax: ROLLBACK;

InserOng Data
Now we can make a table how do we
populate it with data?
insert into tablename values (tuple)
For example:
insert into books values (4, lord of the
Rings, Tolkien)

Changing data

Join with from

Where clause

String in Where Clouse


BETWEENUsed to check whether an
aRribute value is within a range.
IS NULLUsed to check whether an aRribute
value is null.
LIKEUsed to check whether an aRribute
value matches a given string paRern.
INUsed to check whether an aRribute value
matches any value within a value list.
EXISTSUsed to check whether a subquery
returns any rows.

String in where-Clause

COUNT, MAX and MIN

COUNT can be used in conjuncOon with the


DISTINCT clause. For example, suppose you
want to nd out how many dierent vendors
are in the PRODUCT table.
MAX and MIN
The MAX and MIN funcOons help you nd
answers to problems such as the:
Highest (maximum) price in the PRODUCT
table.
Lowest (minimum) price in the PRODUCT
table.

SUM
SUM funcOon computes the total sum for any
specied aRribute, using whatever
condiOon(s) you have imposed.
For example, if you want to compute the total
amount owed by your customers, you could
use the following command:
SELECT SUM(CUS_BALANCE) AS TOTBALANCE
FROM CUSTOMER;

Ordering a Query Result

Grouping Data
The GROUP BY clause is generally used when

you have aRribute columns combined with


aggregate funcOons in the SELECT statement.
SELECT FROM [WHERE [GROUP BY [HAVING
[ORDER BY
columnlist
tablelist
condi-onlist ]
columnlist ]
condi-onlist ]
columnlist [ASC | DESC] ] ;

Grouping Data
SELECT FROM GROUP BY

HAVING ORDER BY
V_CODE, SUM(P_Q * P_PRICE) AS TOTCOST
PRODUCT
V_CODE
(SUM(P_Q * P_PRICE) > 500)
SUM(P_Q * P_PRICE) DESC;
This statement will do the following:
Aggregate the total cost of products grouped by
V_CODE.
Select only the rows having totals that exceed
$500.
List the results in descending order by the total cost.

What we already know

Thats all..

Thanks for your aRenOon

You might also like