Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

SQL Notes

The document provides an overview of SQL (Structured Query Language), detailing its components such as Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL). It covers various SQL operations including creating tables, inserting data, and retrieving data with examples of SELECT statements, comparison operators, and aggregate functions. Additionally, it explains the use of clauses like WHERE, ORDER BY, and GROUP BY in SQL queries.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL Notes

The document provides an overview of SQL (Structured Query Language), detailing its components such as Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL). It covers various SQL operations including creating tables, inserting data, and retrieving data with examples of SELECT statements, comparison operators, and aggregate functions. Additionally, it explains the use of clauses like WHERE, ORDER BY, and GROUP BY in SQL queries.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Database

Programming
using SQL:
Review??
SQL:
Structured Query Language

A standard computer database


language for defining, creating,
manipulating and providing
controlled access to a database.
SQL
SQL is a database language with
3 major components.
 Data Definition Language (DDL)

for defining the different


structures within the database .
Create/ modify
 Data Manipulation Language
( DML) . For managing of
database objects.
 Data Control Language: Used for

providing controlled
DBMS
access to a
3
4
5
Creating Tables
Create the table.
CREATE TABLE dept
(deptno NUMBER(8),
dname VARCHAR(14),
loc VARCHAR(13));

Confirm table creation. using


DESCRIBE dept
6
7
Understanding SQL
Consists of standard English words
e.g:

1.CREATE TABLE Staff(staffNo


VARCHAR(5), lName VARCHAR(15),
salary int);

2.INSERT INTO Staff VALUES ('SG16',


'Brown', 8300);

3. SELECT staffNo, lName, salary


DBMS 8
Literals
Literals are constants used in
SQL statements.

All non-numeric literals must be


enclosed in single quotes (e.g.
‘Lubaga’).

All numeric literals must not be


enclosed in quotes (e.g.
650.00). DBMS 9
SELECT Statement
SELECT Specifies which columns are to
appear in output.

FROM Specifies table(s) to be used.

WHEREFilters rows using a given condition.

DBMS 10
Data type

CREATE TABLE Staff(staffNo


VARCHAR(5), lName VARCHAR(15),
salary int);

Data Type
Indicates the type of data that can be
represented in the value of the data
element.
Types of Data types that can be used in
SQL.
- int , Char(10), DBMS
Varchar(15), Date. 11
Data Retrieval from one
Table
Four major scenarios of data retrieval
from a single table:

i. Retrieving all columns and all rows;


ii. Retrieving specific columns and all
rows;
iii. Retrieving all columns and specific
rows;
iv. Retrieving specific columns and
specific rows.

DBMS 12
Retrieving data from a Schema
1. Use of Arithmetic operators… Calculated
Fields, Renaming columns.
2. Comparision Operators
3. Other Comparision Operators( Between,
In ,Like, Is Null, NOT, IS NOT NULL)
4. Logical Conditions ( AND OR NOT)
5. Column Assortment.
6. Aggregate Function .
7. Group By : Collect data from multiple
records and claster the result by one or
more columns
8. Functions DBMS 13
A schema is a collection of logical
structures of data, or schema
objects. A schema is owned by a
database user and has the same
name as that user. Each user owns
a single schema.

DBMS 14
Example 5.1 All
Columns, All Rows
Request: List full details of all staff.
SELECT staffNo, fName, lName,
address,
position, sex, DOB, salary,
branchNo
FROM Staff;
Can use * as an abbreviation for 'all
columns':
SELECT *
FROM Staff;

DBMS 15
Example 5.1 All
Columns, All Rows

DBMS 16
Example 5.2 Specific
Columns, All Rows
Produce a list of salaries for all
staff, showing only staff number,
first and last names, and salary.

SELECT staffNo, fName, lName,


salary
FROM Staff;

DBMS 17
Example 5.2 Specific
Columns, All Rows

DBMS 18
Distinct Key word
Distinct is used to retrieve rows
from a given table that have
unique values for a given column.
For example say we have a table
of employees and in this table of
employees we have several job
titles from janitors to CEOs. We
would like to know just how many
distinct job titles we have.
some of the columns
DBMS
may contain19
Example 5.3 Use of
DISTINCT
List the property numbers of all
properties that have been
viewed.

SELECT propertyNo
FROM Viewing;

DBMS 20
Example 5.3 Use of
DISTINCT
Use DISTINCT to eliminate
duplicates:

SELECT DISTINCT propertyNo


FROM Viewing;

DBMS 21
Example 5.4 Calculated Fields

Produce a list of monthly


salaries for all staff, showing
staff number, first and last
names, and salary details.

SELECT staffNo, fName,


lName, salary/12 FROM Staff;
(salary is divided by 12 to calculate the monthly salary from the annual
salary)

DBMS 22
Example 5.4 Naming
columns
To name column, use AS clause:
SELECT staffNo, fName,
lName, salary/12
AS monthlySalary
FROM Staff;

QN: Write an SQL statement that will


increase salaries of all position
=Assistant
by 15000. DBMS 23
Comparison Search
Condition
This is done using the WHERE
clause. General syntax:
◦ SELECT clause
FROM table
WHERE condition;

Comparison operators are used to


define conditions in the where
clause
>, <,>=,<=, =. DBMS 24
DBMS 25
Comparison Search
Condition
List all staff with a salary greater than
10,000.
SELECT staffNo, fName, lName,
position, salary
FROM Staff
WHERE salary > 10000;

DBMS 26
DBMS 27
Comparison Operators
= equals
< is less than
> is less than
!= Not Equal
>= greater than or equal to.
<= Less than or equal to

DBMS 28
Example 5.6 Compound
Comparison Search Condition
List addresses of all branch offices in
London or Glasgow.

SELECT *
FROM Branch
WHERE city = 'London' OR city
= 'Glasgow';

DBMS 29
Compound Comparison
Search Condition
List all positions that are
Managers or sex =M.

List all positions that are


Managers and sex =M.

DBMS 30
Example 5.7 Range
Search Condition
BETWEEN test includes the endpoints of
range.

List all staff with a salary between 20,000 and


30,000.

SELECT staffNo, fName, lName, position,


salary
FROM Staff
WHERE salary BETWEEN 20000 AND 30000;

DBMS 31
Example 5.7 Range Search
Condition

DBMS 32
Example 5.7 Range
Search Condition
Also a negated version, NOT BETWEEN can
be used.
BETWEEN does not add much to SQL's
expressive power Could also write:

SELECT staffNo, fName, lName, position,


salary
FROM Staff
WHERE salary>=20000 AND salary <=
30000;

Useful, though, for a range of values.

QN : Write an SQL
DBMS statement that will
33
IN Clause
IN clause :is a special kind of
operator for use in your where
clauses.
Recall that in a where expression
only one value is allowed to be
sent through the query. With the in
operator one can send multiple
values in the where clause.
DBMS 34
Example 5.8 Set
Membership
List all managers and supervisors.
SELECT staffNo, fName, lName,
position
FROM Staff
WHERE position IN ('Manager',
‘Supervisor');

DBMS 35
Membership
There is a negated version (NOT
IN).
IN does not add much to SQL's
expressive power.
Could have expressed this as:
SELECT staffNo, fName, lName, position
FROM Staff
WHERE position='Manager' OR
position=‘Supervisor';

IN is more efficient when set


contains many values.
DBMS 36
Pattern Matching
Find all owners with the string 'Glasgow' in
their address.

SELECT clientNo, fName, lName, address,


telNo
FROM PrivateOwner
WHERE address LIKE '%Glasgow%';

DBMS 37
Pattern Matching
SQL has two special pattern
matching symbols.

LIKE '%Glasgow%' means a


sequence of characters of any
length containing 'Glasgow'.
Like ‘n%’ ; Starts with letter n.
Like ‘%w’ ; Ends with a letter
w.
DBMS 38
NULL Search Condition
List details of all viewings on property PG4
where a comment has not been supplied.
Null represents a value for an attribute that
is currently unknown or not applicable for a
tuple.
Have to test for null explicitly using special
keyword IS NULL:
SELECT clientNo, viewDate
FROM Viewing
WHERE propertyNo = 'PG4' AND
comment IS NULL;

DBMS 39
Example 5.10 NULL
Search Condition

Negated version (IS NOT NULL)


can test for non-null values.

DBMS 40
SQL - Order By

The order by statement allows for


table column assortment. It allows
for ascending or descending lists of
your table column values
permitting SQL to re-order your
table rows for the purpose of
viewing.

DBMS 41
Single Column Ordering
List salaries for all staff,
arranged in descending order of
salary.

SELECT staffNo, fName,


lName, salary FROM Staff
ORDER BY salary DESC;

DBMS 42
Example 5.11 Single
Column Ordering

DBMS 43
Example 5.12 Multiple
Column Ordering
Produce abbreviated list of
properties in order of property
type.

SELECT propertyNo, type,


rooms, rent
FROM PropertyForRent
ORDER BY type;

DBMS 44
Example 5.12 Multiple
Column Ordering

DBMS 45
Multiple Column
Ordering
Four flats in this list - as no minor sort key
specified, system arranges these rows in
any order it chooses.
To arrange in order of rent, specify minor
order:

SELECT propertyNo, type, rooms, rent


FROM PropertyForRent
ORDER BY type, rent DESC;

DBMS
46
Example 5.12 Multiple
Column Ordering

DBMS 47
SELECT Statement -
Aggregates
AGGREGATE Functions: Used to summarize data
on a query, report, or form
ISO standard defines five aggregate
functions:

COUNT(*) returns the number of rows in a table.

SUM returns sum of values in specified


column.
AVG returns average of values in specified
column.
MIN returns smallest value in specified
column.
MAX returns largest value in specified
DBMS 48
column.
SELECT Statement -
Aggregates
Each operates on a single column of a
table and return single value.
COUNT, MIN, and MAX apply to
numeric and non-numeric fields, but
SUM and AVG are used on numeric
fields only.
Apart from COUNT(*), each function
eliminates nulls first and operates
only on remaining non-null values.

DBMS 49
SELECT Statement -
Aggregates
COUNT(*) counts all rows of a table,
regardless of whether nulls or
duplicate values occur.
Can use DISTINCT before column name
to eliminate duplicates.
DISTINCT has no effect with MIN/MAX,
but may have with SUM/AVG.

DBMS 50
Example 5.13 Use of
COUNT(*)
How many properties cost more
than 350 per month to rent?
SELECT COUNT(*) AS count
FROM PropertyForRent
WHERE rent > 350;

DBMS 51
COUNT
Find the number of staff
who belong to
branchno=b005?

SELECT COUNT(*)
FROM staff
WHERE branchno = ‘b005’;

DBMS 52
Example 5.15 Use of COUNT
and SUM
Find number of Managers and sum of their
salaries.
SELECT COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
WHERE position = 'Manager';

DBMS 53
Example 5.16 Use of MIN, MAX,
AVG

Find minimum, maximum,


and average staff salary.
SELECT MIN(salary) AS
myMin,
MAX(salary) AS myMax,
AVG(salary) AS myAvg
FROM Staff;

54
Group By
Used to cluster identical data
sets in to a group. It works
hand in hand with the Aggregate
functions .
SQL Statements- Summary
SELECT Data Retrieval

CREATE , ALTER, DROP, Data definition Language


RENAME, TRUNCATE (DDL)

INSERT, UPDATE, Data Manipulation Language


DELETE (DML)
MERGE

GRANT, REVOKE Data Control Language (DCL)

DBMS 56
SQL Statements cont’d
Statement Description
SELECT Retrieves data from the database

CREATE , ALTER, DROP, Sets up, changes and removes data


RENAME, TRUNCATE structures from tables

INSERT, UPDATE, DELETE Enters new rows, changes existing


rows and removes unwanted rows
from tables in a database

COMMIT, ROLLBACK, Manages changes made by DML.


SAVEPOINT Changes to data may be grouped
into logical transactions
GRANT, REVOKE
Gives and removes access rights to
both the database and the structures
within it.
DBMS 57
Creating a Table
 Involves using the CREATE TABLE statement
which includes:
 Specifying a table name [mandatory]
 Defining columns of the table [mandatory]
 Column data type [mandatory]

( Data types help in identifying what type


of data that can be represented in a data
element)
 Column constraints [optional]

eg . Not Null , Primary Key, Check , Foreign


key
SQL 4.58
 Providing a default value
DBMS [optional] 58
Creating Table Syntax
CREATE TABLE table_name
(
column_name data_type
[column_constraint] [DEFAULT expr] , ….
….
[, table_constraints]
)

Example - considering only mandatory


specifications.

CREATE TABLE emp (emp_id number, name


varchar(30)); SQL 4.59
DBMS 59
Create Table – using the DEFAULT
option
 Example:
 Write an SQL statement to create the following
tables

CREATE TABLE students


(regNo varchar(15), name varchar(20),
dob date, gender char(1) default ‘M’);

Confirm table creation. using


DESCRIBE students;
SQL 4.60
DBMS 60
INSERT
INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)

columnList is optional; if omitted, SQL


assumes a list of all columns in their
original CREATE TABLE order.
Any columns omitted must have been
declared as NULL when table was created,
unless DEFAULT was specified when
creating column.

61 DBMS
INSERT Syntax
INSERT INTO "table_name"
("column1", "column2", ...)
VALUES ("value1", "value2", ...)

E.g. Inserting data into the


Students’ Table
INSERT INTO students
VALUES('S001','Kanaye','1980-08-12', 'M');

DBMS 62
Inserting Data Into the
Table
The INSERT statement
Select * from user_tables;

DBMS 64
Exercise
 Write an SQL statement to create the
following tables
 Branch(branchNo, street, city,
postcode)
 Staff(staffNo, fName, lName, position,
sex, DOB, salary)

DBMS 65
Exercise
Set up two tables.
 Product with columns ProductCode 4 digits,
ProductName 15 characters, ProductPrice
Decimal – 4 digits with two after the decimal
place. The product code is the primary key.
 Supplier with columns SupplierId 4 digits,
SName 15 characters. SupplierId is the
primary key.
Find the tables in the catalog.
 To find tables in the catalog, you manipulate
the SQLPlus buffer.
 Select * from cat
Inserting Data Into the Table

General Syntax:
INSERT INTO TableName [ (columnList) ]
VALUES (dataValueList)
or
INSERT INTO "table_name" ("column1",
"column2", ...)
VALUES ("value1", "value2", ...)

E.g. Inserting data into the Students’ Table


INSERT INTO students
VALUES('S001','Katto,'1980-08-12', 'M');

DBMS 67
Example 5.35 INSERT … VALUES

Insert a new row into Staff table supplying data


for all columns.

INSERT INTO Staff


VALUES (‘SG16’, ‘Alan’, ‘Brown’, ‘Assistant’, ‘M’, ‘1957-
05-25’, 8300, ‘B003’);
DBMS 68
Solution
Decide on the data types for the different
attributes. I.e.
Attribute Data type FieldSize
regNo Varchar 10
fName Varchar 30
lName Varchar 30
course Varchar 10
age Integer

Find out the data types supported by Oracle


DBMS

DBMS 69

You might also like