Grade 12 Ict Dbms Using SQL

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 61

Database Management

Systems and SQL

Session 1
What is a DBMS?
• Collection of interrelated data – manual or
computerized or online
• Set of programs to access the data
• DBMS provides an environment that is both
convenient and efficient to use.

2
Applications Areas of DBMS?

 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


3
Why do we use DBMS
• To avoid data redundancy and inconsistency
Multiple file formats, duplication of information in
different files
• To avoid difficulty in accessing data
Need to write a new program to carry out each
new task
• To deal with data isolation — multiple files and
formats
• To deal with integrity problems
Integrity constraints (e.g. account balance > 0)
become part of program code
Easy to add new constraints or change existing 4
ones
Why do we use DBMS (contd..)
1. Atomicity of updates
• Failures may leave database in an inconsistent state with partial
updates carried out
• E.g. transfer of funds from one account to another should either
complete or not happen at all
2. Concurrent access by multiple users
• Concurrent accessed needed for performance
• Uncontrolled concurrent accesses can lead to inconsistencies
o E.g. two people reading a balance and updating it at the same
time
3. Security problems

5
Relational Model
Attributes

Example of tabular data in the relational model


customer- customer- customer- account-
customer-id
name street city number
192-83-7465 Johnson
Alma Palo Alto A-101
019-28-3746 Smith
North Rye A-215
192-83-7465 Johnson
Alma Palo Alto A-201
321-12-3123 Jones
Main Harrison A-217
019-28-3746 Smith
North Rye A-201

6
A Logically Related Database

7
Database Users
Users are differentiated by the way they expect to interact with the
system
• Application programmers – interact with system through DML
calls
• Sophisticated users – form requests in a database query
language
• Specialized users – write specialized database applications that
do not fit into the traditional data processing framework
• Naïve users – invoke one of the permanent application
programs that have been written previously
 E.g. people accessing database over the web, bank tellers, clerical staff

8
Database Administrator
• Coordinates all the activities of the database
system
• Has a good understanding of the enterprise’s
information resources and needs.
• Database administrator’s responsibilities include:
 Schema definition
 Storage structure and access method definition
 Schema and physical organization modification
 Granting user authority to access the database
 Specifying integrity constraints
 Acting as liaison with users
 Monitoring performance and responding to changes in
9
requirements
Transaction Management
• A transaction is a collection of operations that
performs a single logical function in a database
application
• Transaction-management component ensures that the
database remains in a consistent (correct) state
despite system failures (e.g., power failures and
operating system crashes) and transaction failures.
• Concurrency-control manager controls the interaction
among the concurrent transactions, to ensure the
consistency of the database.

10
Storage Management
• Storage manager is a program module that
provides the interface between the low-level
data stored in the database and the
application programs and queries submitted to
the system.

• The storage manager is responsible to the


following tasks:
 interaction with the file manager
 efficient storing, retrieving and updating of data

11
Overall
System
Structure

12
Application Architectures

Two-tier architecture: E.g. client programs using ODBC/JDBC


to communicate with a database
Three-tier architecture: E.g. web-based applications, and
applications built using “middleware”
13
DBMS: Allows to Create, Manipulate &
Access the Data

14
The Language of DBMS

SQL
Structured Query Language
Standard language for querying and manipulating
data. Very widely used.
1. Data Definition Language (DDL)
– Create/alter/delete tables and their attributes
2. Data Manipulation Language (DML)
– Insert/delete/modify tuples in tables
SQL
• SQL: widely used non-procedural language
– E.g. find the name of the customer with customer-id 192-83-7465
select customer.customer-name
from customer
where customer.customer-id = ‘192-83-7465’
– E.g. find the balances of all accounts held by the customer with
customer-id 192-83-7465
select account.balance
from depositor, account
where depositor.customer-id = ‘192-83-7465’ and
depositor.account-number = account.account-
number
• Application programs generally access databases through one of
– Language extensions to allow embedded SQL
– Application program interface (e.g. ODBC/JDBC) which allow SQL
16
queries to be sent to a database
Table name Attribute names

Tables in RDBMS
Product

PName Price Category Manufacturer

Gizmo 19.99 Gadgets GizmoWorks

Powergizmo 29.99 Gadgets GizmoWorks

SingleTouch 149.99 Photography Canon

MultiTouch 203.99 Household Hitachi

Tuples or rows 17
Steps to Define the Schema
Step 1: Define table name and its attributes
Product(PName, Price, Category, Manufacturer)
Product
PName Price Category Manufacturer

Gizmo 19.99 Gadgets GizmoWorks

Powergizmo 29.99 Gadgets GizmoWorks

SingleTouch 149.99 Photography Canon

MultiTouch 203.99 Household Hitachi


18
Data Types and Domain of Attributes
Product(PName, Price, Category, Manfacturer)

Basic data types


– Numeric
• Integer numbers: INTEGER, INT, and SMALLINT
• Floating-point (real) numbers: FLOAT or REAL, and
DOUBLE PRECISION
– Character-string
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR VARYING(n),
CHARACTER VARYING(n)
19
Data Types and Domain of Attributes
– Boolean
• Values of TRUE or FALSE or NULL
– DATE
• Ten positions
• Components are YEAR, MONTH, and DAY in the
form YYYY-MM-DD
– Timestamp
• Includes the DATE and TIME fields
• Plus a minimum of six positions for decimal
fractions of seconds
• Optional WITH TIME ZONE qualifier 20
Steps to Define the Schema
Step 2: Define Data Types and Domain of Attributes.

Product(PName, Price, Category, Manfacturer)

Pname : Varchar,
Price: Float,
Category: Varchar
Manfacturer: Varchar

21
Step 3: Specifying Constraints.
Product(PName, Price, Category, Manfacturer)

Constraints: Restrictions on values of


Attribute.

• Specifying Attribute and Domain Constraints

• Specifying Key Constraints

• Specifying Key and Referential Integrity


Constraints

22
Specifying Attribute and Domain Constraints
• NOT NULL
NULL is not permitted for a particular attribute

• Default value
DEFAULT <value>

• CHECK clause
Dnumber > 0 AND Dnumber < 21;

• UNIQUE clause
Specifies attributes that have unique values 23
Specifying Key Constraints

• PRIMARY KEY clause


Specifies one or more attributes that make up the
primary key of a relation

 It is an attribute or a combination of attributes that


that uniquely identifies the records./tuples

e.g. roll_no, account_no, Id etc.

PRIMARY KEY = NOT NULL+ UNIQUE


24
Schema of Table Product
Product(Pname varchar Primary Key,
Price float Not Null,
Category varchar, check(Gadget, Photoraphy,
Household
Manufacturer varchar )

Attribute Data Type Constraints


Pname Varchar Primary Key
Price Float Not Null
Category Varchar Gadget,
Photography,
Household

Manufacturer Varchar

25
LET’S CODE
TOGETHER!!

26
Creating a Database
Step 1. Create a Database Company
CREATE
CREATEDATABASE
DATABASE <DATABSE
<DATABSENAME>;
NAME>;

Create database company;


Step 2. USE Database
USE
USE <DATABSE
<DATABSENAME>;
NAME>;

use company;
Step 2. SHOW TABLES
show tables;
27
Creating a Table
Step 1. Create a TABLE
CREATE
CREATETABLE
TABLE <TABLE
<TABLENAME>
NAME> ((
<ATTRIBUTE
<ATTRIBUTELIST>
LIST> <DATA
<DATATYPE>
TYPE> <CONSTRAINT>,
<CONSTRAINT>,
<ATTR2>
<ATTR2> <DATA
<DATATYPE>,<CONSTRAINT>);
TYPE>,<CONSTRAINT>);
Attribute Data Type Constraints
Pname Varchar Primary Key
Price Float Not Null
Category Varchar Gadget,
Photography,
Household
Manufacturer Varchar
28
Creating a Table
create table product(Pname varchar(20) primary key,
price float NOT NULL,category varchar(20)
CHECK(category
in("Gadget","Photography","Household")),
manufacturer varchar(20));
Attribute Data Type Constraints
Pname Varchar Primary Key
Price Float Not Null
Category Varchar Gadget,
Photography,
Household
Manufacturer Varchar
VIPS: Oct - Dec 2019 29
Show Existing Tables
Show
Showtables;
tables;

Describe structure of a Existing Table


Desc
Desc<tablename>;
<tablename>;

Desc product;
30
Insert records in Table
INSERT
INSERT INTO
INTO R(A1,….,
R(A1,….,An)
An) VALUES
VALUES (v1,….,
(v1,…., vn)
vn)

insert into product(Pname,price,category,manufacturer)


values("Gizmo",19.99, "Gadgets", "GizmoWorks");
or
insert into product values("Gizmo",19.99, "Gadgets", "GizmoWorks");
insert into product values("Powergizmo",29.99, "Gadgets", "GizmoWorks");
insert into product values("SingleTouch",149.99, "Photography", "Canon");
insert into product values("MultiTouch",203.99, "Household", "Hitachi");

PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks

Powergizmo 29.99 Gadgets GizmoWorks

SingleTouch 149.99 Photography Canon

MultiTouch 203.99 Household Hitachi


31
Select Query
SELECT
SELECT <attributes>
<attributes>
FROM
FROM <one
<oneor or more
morerelations>
relations>
WHERE
WHERE <conditions>
<conditions>
Product

SELECT
SELECT **
FROM
FROM product;
product;
PName Price Category Manufacturer
“selection”
Gizmo 19.99 Gadgets GizmoWorks

Powergizmo 29.99 Gadgets GizmoWorks

SingleTouch 149.99 Photography Canon

MultiTouch 203.99 Household Hitachi

32
Select Query using WHERE
PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
Product
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT Pname,
Pname,Price
Price
FROM
FROM Product
Product PName Price
Gizmo 19.99
Powergizmo 29.99
SingleTouch 149.99
“projection”
MultiTouch 203.99

33
Select Query using WHERE

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE category=‘Gadgets’;
category=‘Gadgets’;

PName Price Category Manufacturer


“selection” with Gizmo 19.99 Gadgets GizmoWorks
where Powergizmo 29.99 Gadgets GizmoWorks

34
Select Query using WHERE

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT PName,
PName,Price,
Price,Manufacturer
Manufacturer
FROM
FROM Product
Product
WHERE
WHERE Price
Price>>100;
100;
PName Price Manufacturer
“selection” and SingleTouch 149.99 Canon

“projection” with MultiTouch 203.99 Hitachi

where 35
Select Query using WHERE

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT PName,
PName,Price,
Price,Manufacturer
Manufacturer
FROM
FROM Product
Product
WHERE
WHERE Price
Price>>100
100and
and manufacturer
manufacturer=“Canon”;
=“Canon”;

Combine two or more PName Price Manufacturer


conditions Using
SingleTouch 149.99 Canon
and
36
Select Query using WHERE
PName Price Category Manufacturer
Product
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT PName,
PName,Price,
Price,Manufacturer
Manufacturer
FROM
FROM Product
Product
WHERE
WHERE manufacturer
manufacturer=“Hitachi”
=“Hitachi”or
or
manufacturer
manufacturer==“Canon”;
“Canon”;

PName Price Manufacturer


Combine two or more
conditions Using SingleTouch 149.99 Canon
or MultiTouch 203.99 Hitachi

37
Select Query using WHERE
PName Price Category Manufacturer
Product
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT PName,
PName,Price,
Price,Manufacturer
Manufacturer
FROM
FROM Product
Product
WHERE
WHERE manufacturer
manufacturer
IN(“Hitachi”,“Canon”);
IN(“Hitachi”,“Canon”);

PName Price Manufacturer


Replace OR with In
conditions Using SingleTouch 149.99 Canon
IN MultiTouch 203.99 Hitachi

38
Note That
• Case insensitive:
– Same: SELECT Select select
– Same: Product product
– Different: ‘Seattle’ ‘seattle’

• Constants:
– ‘abc’ - yes
– “abc” - no

39
The LIKE operator
SELECT
SELECT **
FROM
FROM Products
Products
WHERE
WHERE PName
PName LIKE
LIKE <pattern>
<pattern>

Pattern : pattern matching on strings. It contains two


special symbols:
% = any sequence of characters
_ = any single character

40
Like Operator with %
Product name that starts with P

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE Pname
Pnamelike
like‘p%’;
‘p%’;

PName Price Category Manufacturer

Powergizmo 29.99 Gadgets GizmoWorks


41
Like Operator with %
Product name that ends with Touch

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE Pname
Pnamelike
like‘%Touch’;
‘%Touch’;
PName Price Category Manufacturer
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi
42
Like Operator with %
Product name that contains e anywhere in the name

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE Pname
Pnamelike
like‘%e%’;
‘%e%’;

PName Price Category Manufacturer


Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
43
Like Operator with _ &%
Product name with second letter ‘o’
Product PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE Pname
Pnamelike
like‘_o%’;
‘_o%’;

PName Price Category Manufacturer

Powergizmo 29.99 Gadgets GizmoWorks


44
Like Operator with %
Product name with second last character ‘c’

Product PName Price Category Manufacturer


Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE Pname
Pnamelike
like‘%c_’;
‘%c_’;
PName Price Category Manufacturer
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi
45
Eliminating Duplicates
Category
SELECT
SELECT DISTINCT
DISTINCT category
category Gadgets
FROM
FROM Product;
Product; Photography
Household

Compare to:
Category
Gadgets
SELECT
SELECT category
category Gadgets
FROM
FROM Product;
Product; Photography
Household
46
Aggregate Functions

SQL supports several aggregation operations:

 Sum
 Max
 Min
 Avg
 Count

Except count, all aggregations apply to a single attribute

47
Aggregate Functions – SUM
Sum of Price of all Products
Product PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT sum(price)
sum(price)
FROM
FROM Product;
Product;

403.96

48
Aggregate Functions – MAX
Max of Price of all Products
Product PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT max(price)
max(price)
FROM
FROM Product;
Product;

203.96

49
Aggregate Functions – MIN
Min of Price of all Products
Product PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT min(price)
min(price)
FROM
FROM Product;
Product;

19.99

50
Aggregate Functions – AVG
Avg of Price of all Products
Product PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT avg(price)
avg(price)
FROM
FROM Product;
Product;

100.99

51
Aggregate Functions – COUNT
Total number of Products
Product PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi

SELECT
SELECT count(price)
count(price)
FROM
FROM Product;
Product;

4
SELECT
SELECT count(*)
count(*)
FROM
FROM Product;
Product;
52
More Examples
Query Sql

Max price of Gadgets Select Max(price) from


category Products product where
category=“Gadgets”

Total no of products in Select count(*) from product


Household category where Category=“Household”

Count total no. of categories Select


Count(Distinct(category) )
from product

53
PName Price Category Manufacturer
WRITE Gizmo 19.99 Gadgets GizmoWorks

THE Powergizmo
SingleTouch
29.99
149.99
Gadgets
Photography
GizmoWorks
Canon
QUERY MultiTouch 203.99 Household Hitachi

Problem Statement SQL Query


Average Price of Gizmo Works
manufacturer ?
Total price of Gizmo Works manufacturer
?
Count total number of manufacturers
?
Count number of products that contains ‘o’
in their name
?

54
Ordering the Results
SELECT
SELECT pname,
pname, price,
price, manufacturer
manufacturer
FROM
FROM Product
Product
WHERE
WHERE manufacturer=‘GizmoWorks’
manufacturer=‘GizmoWorks’AND ANDprice
price>> 50
50
ORDER
ORDERBYBY price,
price, pname;
pname;
• Ties are broken by the second attribute on the ORDER
BY list, etc.

• Also works without Where


• Ordering is ascending, unless you specify the DESC
keyword.

SELECT
SELECT pname,
pname, price,
price, manufacturer
manufacturer
FROM
FROM Product
Product
ORDER
ORDERBYBY price
priceDESC;
DESC;
55
PName Price Category Manufacturer
FIND Gizmo 19.99 Gadgets GizmoWorks

THE Powergizmo 29.99 Gadgets GizmoWorks


SingleTouch 149.99 Photography Canon
RESULT MultiTouch 203.99 Household Hitachi

SELECT
SELECT DISTINCT
DISTINCTcategory
?
category
FROM
FROM Product
Product
ORDER
ORDERBYBYcategory
category

SELECT
SELECT Category
?
Category
FROM
FROM Product
Product
ORDER
ORDERBYBY PName
PName

SELECT
SELECT DISTINCT
DISTINCTcategory
?
category
FROM
FROM Product
Product
ORDER
ORDERBYBYPName
PName 56
Practice Exercise

57
Create a new table in your current database
‘COMPANY’ with the following schema

Attribute Data Type Constraints

Cname Varchar Primary Key

Reg_Date Date Not Null

Stock_Price Float

Country Varchar

58
Create a new table named ‘COMPDTLS’ in your
current database with the following schema

Attribute Data Type Constraints


CompName Varchar Primary Key
RegDate Date Not Null
StockPrice Float

Country Varchar

COMPDTLS( CompName varchar Primary Key,


RegDate Date Not Null,
StockPrice Float
Country varchar )

59
Insert the following Records in COMPDTLS

CompName RegDate StockPrice Country

GizmoWorks 2019/10/21 25 USA

Canon 2019/10/3 65 Japan

Hitachi 2019/10/10 15 India

60
Write SQL Queries for:
1. List the details of all companies
2. List the registration date of all companies
3. Show the details of all companies of Japan
4. List the company name whose stock price is 65
5. List the companies of Japan or India
6. Show the maximum stock price.
7. Show the average stock price.
8. Show the distinct countries
9. Show the total no of countries
10. Show the company name whose country name ends with ‘a’.

61

You might also like