0% found this document useful (0 votes)
4 views

Database(Upd)......

The document provides an overview of querying databases using SQL, emphasizing the importance of queries for data retrieval, decision-making, and database performance. It details various SQL commands, including SELECT, UPDATE, DELETE, and the use of clauses like WHERE and ORDER BY to filter and sort data. Additionally, it explains the significance of understanding query languages for various job roles in data management.

Uploaded by

Umar Khattak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Database(Upd)......

The document provides an overview of querying databases using SQL, emphasizing the importance of queries for data retrieval, decision-making, and database performance. It details various SQL commands, including SELECT, UPDATE, DELETE, and the use of clauses like WHERE and ORDER BY to filter and sort data. Additionally, it explains the significance of understanding query languages for various job roles in data management.

Uploaded by

Umar Khattak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

CSC 114

Information
communication
Technology

1
Querying a Database
 A query is an inquiry into the database using the SELECT
statement.
 A query is used to extract data from the database in
a readable format according to the user's request.
 A query language consists of simple, English-like
statements that allow users to specify the data to
display, print, or store.
 Each query language has its own grammar and
vocabulary
 Uses of querying
 Find data
 Calculate values per record
 Delete records
 Most important DBMS skill 2
Why Querying is the Most Important Skill in
Database Management
 Query is the main way you interact with the data. It
can be used to
 Find the Data Easily:
 When you need information from a database, you write a
query to get it.
 To make decision:
 Businesses use data to make decisions. If you can write
good queries, you can get the right data, which helps the
company make better choices.
 Improving Database Performance
 Good queries can make your database work faster. If
queries are poorly written, it can slow down the system
and make everything take longer.
3
 Keeping Data Safe and Accurate:
 Queries also allow you to update, delete, or add
data. It’s important to know how to do this carefully
so you don’t accidentally mess up or lose valuable
data.
 Job Requirement:
 Almost any job that involves working with data—like
in sales, marketing, or IT—requires you to know
how to query a database. It’s a basic skill needed
for many roles.

4
Query Languages
 All DBMS use a query language
 Most DBMS modify the language
 Structured Query Language (SQL)
 Most common query language
 xBase
 Query language for dBase systems
 Query by example (QBE)
 Interface to SQL or xBase
 Interactive query design

5
Query Examples

 SQL
Select FirstName, LastName, Phone
From tblPhoneNumbers
Where LastName=“Norton”;

6
Database Tables
 A database most often contains one or more
tables.
 Each table is identified by a name (e.g.
"Customers" or "Orders").
 Tables contain records (rows) with data.
 we are using the sample database
 Below is a selection from the "Customers"
table:

7
Sample Database

The table above contains five records (one for each customer) and seven
columns (CustomerID, CustomerName, ContactName, Address, City,
PostalCode, and Country).

8
SQL Statements

Most of the actions you need to


perform on a database are done
with SQL statements.
The following SQL statement
selects all the records in the
"Customers" table:

SELECT * FROM Customers;


Note: SQL keywords are NOT case sensitive:
9
Semicolon after SQL
Statements?
 Some database systems require a semicolon at

the end of each SQL statement.


 Some of The Most Important SQL
Commands
 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
 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

10
SELECT STATMENT
 There are four keywords or clauses that are
valuable part of SELECT statement.

 These keywords are as follows:


 SELECT
 FROM
 WHERE
 ORDER BY

 Each of these keywords is covered in detail in later


sections.
11
The SQL SELECT Statement
 The SELECT statement is used to select data from a
database.
 The data returned is stored in a result table, called the
result-set.
SELECT Syntax
 SELECT column1, column2, ...
FROM table_name;
 Here, column1, column2, ... are the field names of the table
you want to select data from.
 If you want to select all the fields available in the table, use
the following syntax:
 SELECT * FROM table_name;
12
SELECT * EXAMPLE
 The following SQL statement selects all the
columns from the "Customers" table:

 SELECT * FROM Customers;

13
SAMPLE DATABASE
(CUSTOMERS)

14
SELECT Column Example
 The following SQL statement selects the "CustomerName"
and "City" columns from the "Customers" table:

 SELECT CustomerName, City FROM Customers;

 RESULT RETURNED ON NEXT SLIDE

15
16
The SQL SELECT DISTINCT
 Statement
Inside a table, a column often contains many
duplicate values; and sometimes you only want
to list the different (distinct) values.
 The SELECT DISTINCT statement is used to
return only distinct (different) values.
 SELECT DISTINCT Syntax

SELECT DISTINCT column1, column2, ...


FROM table_name;

17
SELECT DISTINCT
Examples
 The following SQL statement selects only the

DISTINCT values from the "Country" column in


the "Customers" table:
 SELECT DISTINCT Country FROM Customers;

18
Continued…
 The following SQL statement lists the number
of different (distinct) customer countries:
 SELECT COUNT(DISTINCT Country) FROM
Customers;

Result:

 Number of Records: 1
COUNT(DISTINCT Country)
21

19
FOR MS ACCESS
 SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM
Customers);

 Number of Records: 1

 COUNT(DISTINCT Country)
 21

20
The 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 condition.
 WHERE Syntax
 SELECT column1, column2, ...
FROM table_name
WHERE condition;

 SELECT * FROM Customers


WHERE Country='Mexico';

21
SAMPLE DATABASE
RESULT ON NEXT SLIDE
CustomerID CustomerNa ContactNam Address City PostalCode Country
me e
1 Alfreds Maria Obere Str. Berlin 12209 Germany
Futterkiste Anders 57

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedado Constitución
s y helados 2222
3 Antonio Antonio Mataderos México D.F. 05023 Mexico
Moreno Moreno 2312
Taquería
4 Around the Thomas 120 Hanover London WA1 1DP UK
Horn Hardy Sq.

5 Berglunds Christina Berguvsväg Luleå S-958 22 Sweden


snabbköp Berglund en 8

22
RESULT

CustomerID Customer ContactN Address City PostalCo Country


Name ame de
2 Ana Ana Avda. de México 05021 Mexico
Trujillo Trujillo la D.F.
Empared Constituci
ados y ón 2222
helados
3 Antonio Antonio Matadero México 05023 Mexico
Moreno Moreno s 2312 D.F.
Taquería

23
Operators in The WHERE
Clause
 The following operators can be used in the

WHERE clause:
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column

24
Text Fields vs. Numeric

Fields
SQL requires single quotes around text values (most
database systems will also allow double quotes).
 However, numeric fields should not be enclosed in quotes:
 SELECT * FROM Customers WHERE CustomerID=1;
 Number of Records: 1

CustomerID Customer ContactN Address City PostalCo Country


Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e

25
SQL AND, OR and
NOT Operators
 The WHERE clause can be combined with

AND, OR, and NOT operators.


 The AND and OR operators are used to filter
records based on more than one condition:
 The AND operator displays a record if all the
conditions separated by AND is TRUE.
 The OR operator displays a record if any of the
conditions separated by OR is TRUE.
 The NOT operator displays a record if the
condition(s) is NOT TRUE.

26
AND Syntax
 SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condi
tion3 ...;

 OR Syntax

 SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR condition2 OR conditio
n3 ...;
27
OR Example
 SELECT * FROM Customers
WHERE City='Berlin' OR City='München';

 Number of Records: 2

Customer ID Customer ContactN Address City PostalCo Country


Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e
25 Frankenv Peter Berliner München 80805 Germany
ersand Franken Platz 43

28
AND Example
 The following SQL statement selects all fields
from "Customers" where country is "Germany"
AND city is "Berlin":
 SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
 Number of Records: 1
CustomerID Customer ContactN Address City PostalCo Country
Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e

29
NOT Syntax
 SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
CustomerID CustomerNa ContactNam Address City PostalCode Country
me e
1 Alfreds Maria Obere Str. Berlin 12209 Germany
Futterkiste Anders 57

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedado Constitución
s y helados 2222
3 Antonio Antonio Mataderos México D.F. 05023 Mexico
Moreno Moreno 2312
Taquería
4 Around the Thomas 120 Hanover London WA1 1DP UK
Horn Hardy Sq.

5 Berglunds Christina Berguvsväg Luleå S-958 22 Sweden


snabbköp Berglund en 8 30
NOT Example
 The following SQL statement selects all fields from
"Customers" where country is NOT "Germany":
 SELECT * FROM Customers
WHERE NOT Country='Germany';
CustomerID CustomerNam ContactName Address City PostalCode Country
e
2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico
Emparedados Constitución
y helados 2222
3 Antonio Antonio Mataderos México D.F. 05023 Mexico
Moreno Moreno 2312
Taquería
4 Around the Thomas Hardy 120 Hanover London WA1 1DP UK
Horn Sq.
5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden
snabbköp Berglund 8

31
Combining AND, OR and
NOT
 You can also combine the AND, OR and NOT

operators.
 The following SQL statement selects all fields
from "Customers" where country is "Germany"
AND city must be "Berlin" OR "München" (use
parenthesis to form complex expressions):
 SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin'
OR City='München');

32
RESULT

Number of Records: 2

CustomerID Customer ContactN Address City PostalCo Country


Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e
25 Frankenv Peter Berliner München 80805 Germany
ersand Franken Platz 43

33
(DIY) Do it Yourself
 The following SQL statement selects all fields
from "Customers" where country is NOT
"Germany" and NOT "USA":

SELECT * FROM Customers


WHERE NOT Country='Germany' AND NOT
Country='USA’;
OR
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'USA');
34
RESULT
CustomerID CustomerNam ContactName Address City PostalCode Country
e
2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico
Emparedados Constitución
y helados 2222

3 Antonio Antonio Mataderos México D.F. 05023 Mexico


Moreno Moreno 2312
Taquería

4 Around the Thomas Hardy 120 Hanover London WA1 1DP UK


Horn Sq.
5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden
snabbköp Berglund 8
7 Blondel père et Frédérique 24, place Strasbourg 67000 France
fils Citeaux Kléber
8 Bólido Martín C/ Araquil, 67 Madrid 28023 Spain
Comidas Sommer
preparadas

9 Bon app' Laurence 12, rue des Marseille 13008 France


Lebihans Bouchers
10 Bottom-Dollar Elizabeth 23 Tsawassen Tsawassen T2F 8M4 Canada
Marketse Lincoln Blvd.

35
SQL ORDER BY Keyword
 The ORDER BY keyword is used to sort the
result-set in ascending or descending order.
 To sort the records in descending order, use
the DESC keyword.
 The ORDER BY keyword sorts the records in
ascending order by default.

36
ORDER BY SYNTAX
 SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

 SELECT * FROM Customers


ORDER BY Country;

37
RESULT
CustomerID CustomerNam ContactName Address City PostalCode Country
e
12 Cactus Patricio Cerrito 333 Buenos Aires 1010 Argentina
Comidas para Simpson
llevar

54 Océano Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Atlántico Ltda. Moncada Moncada 8585
Piso 20-A

64 Rancho Sergio Av. del Buenos Aires 1010 Argentina


grande Gutiérrez Libertador 900
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria
mehr
50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium
Dewey Bens 532
76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium
délices Cartrain Tirou, 255

38
ORDER BY DESC EXAMPLE

SELECT * FROM Customers ORDER BY Country DESC;
33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela
Restaurante Palos Grandes
35 HILARIÓN- Carlos Carrera 22 con San Cristóbal 5022 Venezuela
Abastos Hernández Ave. Carlos
Soublette #8-
35

46 LILA- Carlos Carrera 52 con Barquisimeto 3508 Venezuela


Supermercado González Ave. Bolívar
#65-98 Llano
Largo

47 LINO- Felipe Ave. 5 de I. de Margarita 4980 Venezuela


Delicateses Izquierdo Mayo Porlamar

32 Great Lakes Howard 2732 Baker Eugene 97403 USA


Food Market Snyder Blvd.
36 Hungry Coyote Yoshi Latimer City Center Elgin 97827 USA
Import Store Plaza 516
Main St.

43 Lazy K Kountry John Steel 12 Orchestra Walla Walla 99362 USA


Store Terrace
45 Let's Stop N Jaime Yorres 87 Polk St. San Francisco 94117 USA
Shop Suite 5 39
Order by several columns

example
SELECT * FROM Customers ORDER BY Country, CustomerName;
CustomerID CustomerNam ContactName Address City PostalCode Country
e
12 Cactus Patricio Cerrito 333 Buenos Aires 1010 Argentina
Comidas para Simpson
llevar

54 Océano Yvonne Ing. Gustavo Buenos Aires 1010 Argentina


Atlántico Ltda. Moncada Moncada 8585
Piso 20-A

64 Rancho Sergio Av. del Buenos Aires 1010 Argentina


grande Gutiérrez Libertador 900
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria
mehr
50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium
Dewey Bens 532
76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium
délices Cartrain Tirou, 255

40
ORDER BY Several Columns
Example
SELECT 2 ORDER BY Country ASC, CustomerName DESC;
* FROM Customers

CustomerID CustomerNam ContactName Address City PostalCode Country


e
64 Rancho Sergio Av. del Buenos Aires 1010 Argentina
grande Gutiérrez Libertador 900
54 Océano Yvonne Ing. Gustavo Buenos Aires 1010 Argentina
Atlántico Ltda. Moncada Moncada 8585
Piso 20-A

12 Cactus Patricio Cerrito 333 Buenos Aires 1010 Argentina


Comidas para Simpson
llevar

59 Piccolo und Georg Pipps Geislweg 14 Salzburg 5020 Austria


mehr
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
76 Suprêmes Pascale Boulevard Charleroi B-6000 Belgium
délices Cartrain Tirou, 255
50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium
Dewey Bens 532

41
Database Query
 Query by example (QBE) provides a GUI to
assist users with retrieving data
 Program retrieves records that match criteria
entered in form fields.

criteria
Query results

42
Use of Simple Query Wizard

43
Data Security
A DBMS provides means to ensure that only
authorized users access data at permitted times
 Access privileges define activities that specific
user or group of users can perform
 Read-only privileges - user can view data, but
cannot change it
 Full-update privileges -user can view and change
data
 principle of least privilege policy, where users’
access privileges are limited to the lowest level
necessary to perform required tasks
44
Backup and Recovery
 A DMBS provides a variety of techniques to
restore the database to a usable form in case it
is damaged or destroyed

Backup Log

Recovery Continuous
utility backup
45
Backup and Log
 Backup is a copy of the before image

entire database
 Log is a listing of activities
that change database
contents
 DBMS places three items in change
log:
 before image after image
 actual change, and
 after image
 also, might store who made
the change, when it was
made, and from which
computer it was made.
46
Recovery Utility
 Uses logs and/or backups to restore database when it
is damaged or destroyed
 Rollforward— DBMS uses log to re-enter changes
made to data-base since last save or backup
 Also called forward recovery
 Rollback— DBMS uses log to undo any changes made
to database during a certain period of time
 Also called backward recovery
 Continuous backup is a backup plan in which all data
is backed up whenever a change is made.
 Can cost more than other backup strategies but is growing
in popularity because of its benefits
 Provides recovery of damaged data in a matter of seconds.
47
Relational Databases
 stores data in tables that
consist of rows and
columns
 Each row has a primary
key
 Each column has a unique
name
 Stores data relationships
 A relationship is a link
within the data
 can set up a relationship
between tables at any time
48
Data Terminology
 A relational database uses terms different from
a file processing system.

49
Data Warehouse
 A data warehouse is a huge database that stores and
manages the data required to analyze historical and
current transactions
 Uses multidimensional databases
 Quick and efficient way to access large amounts of data
 typically has a user-friendly interface, so that users easily
can interact with its data
 Often, the database is distributed.
 Data in a distributed database exists in many separate locations
throughout a network or the Internet
 Data is accessible through a single server
 Data’s location is transparent to the user, who usually is unaware that
the data is stored in multiple servers.
 Often uses a process called data mining to find patterns and
relationships among data
50

Web Databases
 Databases on the Web allow you to:
 Some Web databases are collaborative databases, where
users store and share photos, videos, recordings, and other
personal media with other registered users

Shop for
Buy or sell Search for a
products or
stocks job
services

Register for Check


Make airline
college semester
reservations
classes grades
51
Web Databases
 Database you access through the Web by filling
in a form on a Web page
 Usually resides on a database server, a computer
that stores and provides access to a database

52
Common Corporate DBMS
 Oracle
 Most popular enterprise-level DBMS
 Very flexible storage system
 Can be very complex
 Platform independent
 Offers a wide range of solutions
 DB2
 Suit of applications to assist with data mining,
analysis and integration, data warehousing
 Platform independent
 Only database using pure SQL
53
Common Corporate DBMS
 Microsoft SQL Server
 Fastest growing DBMS
 Only runs on Microsoft platforms
 Eight different versions exist
 Extremely scalable architecture
 Software can grow with the data
 MySQL
 Leading DBMS for Linux
 Very inexpensive
 Features are those needed in business
 Often faster than other DBMS
 Platform independent 54
Database Administration
Database analysts and administrators are responsible
for managing and coordinating all database activities

Database Analyst (DA) Database Administrator (DBA)


Focuses on meaning and usage Creates and maintains the data
of data. Decides on proper dictionary, manages security,
field placement, defines data monitors performance, and
relationship, and identifies checks backup and recovery
users’ access privileges procedures

55
Role of Employee as User
 Employees should learn how to use the data in
the database effectively
 Interact with database
 Identify new data for the database
 Maintain the database
 Users can take part in designing the database that will
help them achieve those goals

56

You might also like