0% found this document useful (0 votes)
72 views54 pages

SQL: Data Manipulation: Aisha Batool

SQL is a language for storing, manipulating, and retrieving data in databases. It can be used to create and manage database structures, populate tables with data, and query databases. The core SQL statements are SELECT, INSERT, UPDATE, and DELETE. The SELECT statement is used to query databases and retrieve data. It allows users to select specific columns, apply filters to rows, and perform calculations on retrieved data.

Uploaded by

Saman Paul
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)
72 views54 pages

SQL: Data Manipulation: Aisha Batool

SQL is a language for storing, manipulating, and retrieving data in databases. It can be used to create and manage database structures, populate tables with data, and query databases. The core SQL statements are SELECT, INSERT, UPDATE, and DELETE. The SELECT statement is used to query databases and retrieve data. It allows users to select specific columns, apply filters to rows, and perform calculations on retrieved data.

Uploaded by

Saman Paul
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/ 54

SQL: Data

Manipulation
AISHA BATOOL
Chapter Objective
Introduction to SQL
In 1974, D. Chamberlin, also from the IBM San José Laboratory, defined a language called the
Structured English Query Language, or SEQUEL.
SQL stands for Structured Query Language
SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database.
A particular language that has emerged from the development of the relational model is the
Structured Query Language,
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
Standard relational database language
More than one hundred DBMSs now support SQL
Introduction to SQL
Example of a transform-oriented language
Transform-oriented language : A language designed to use relations to
transform inputs into required outputs.
SQL standard has two major components:
Data Definition Language: are used to create the database structure (that
is, the tables) and the access mechanisms (that is, what each user can legally
access)
Data Manipulation Language (DML) for retrieving and updating data.
 To populate and query the tables
Introduction to SQL
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 views in a database
SQL can set permissions on tables, procedures, and views
Introduction to SQL
Introduction to SQL
It is a nonprocedural language; you specify what information you require, rather than how to get it. In
other words, SQL does not require you to specify the access methods to the data.
Like most modern languages, SQL is essentially free-format, which means that parts of statements do not
have to be typed at particular locations on the screen
The command structure consists of standard English words such as CREATE
TABLE, INSERT, SELECT. For example:
CREATE TABLE Staff (staffNo VARCHAR(5), IName VARCHAR(15), salary
DECIMAL(7,2));
– INSERT INTO Staff VALUES (‘SG16’, ‘Brown’, 8300);
– SELECT staffNo, IName, salary
FROM Staff
WHERE salary > 10000;

SQL can be used by a range of users including database administrators (DBA), management personnel,
application developers, and many other types of end-user.
Writing SQL Commands
The ISO SQL standard does not use the formal terms of relations, attributes, and
tuples,
Instead using the terms tables, columns, and rows
An SQL statement consists of reserved words and user-defined words.
Reserved words are a fixed part of the SQL language and have a fixed meaning.
They must be spelled exactly as required and cannot be split across lines.

User-defined words are made up by the user (according to certain syntax rules)
Represent the names of various database objects such as tables, columns, views, indexes, and so
on.
Writing SQL Commands
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database
systems that allow more than one SQL statement to be executed in the same call
to the server.
SQL statement are case-insensitive, which means that letters can be typed in
either upper- or lowercase.
Literal character data must be typed exactly as it appears in the database.
For example, if we store a person’s surname as “SMITH” and then search for it using the string
“Smith,” the row will not be found.
Writing SQL Commands
SQL is free-format, an SQL statement or set of statements is more readable if indentation and
lineation are used
Each clause in a statement should begin on a new line;
The beginning of each clause should line up with the beginning of other clauses;
If a clause has several parts, they should each appear on a separate line and be indented under
the start of the clause to show the relationship.
Data Manipulation
SQL DML statements:
INSERT – to insert data into a table /Create
SELECT – to query data in the database /Read
UPDATE – to update data in a table
DELETE – to delete data from a table
Literals
Literals are constants that are used in SQL statements
There are different forms of literals for every data type supported by SQL
All nonnumeric data values must be enclosed in single quotes; all numeric data values must not
be enclosed in single quotes.

Example:
 INSERT INTO PropertyForRent(propertyNo, street, city, postcode, type, rooms, rent,
ownerNo, staffNo, branchNo)
VALUES (‘PA14’, ‘16 Holhead’, ‘Aberdeen’, ‘AB7 5SU’, ‘House’, 6, 650.00,
‘CO46’, ‘SA9’, ‘B007’);
Data Definition Language
The CREATE DATABASE statement is used to create a new SQL database.
Syntax: CREATE DATABASE databasename;

The DROP DATABASE statement is used to drop an existing SQL database


Syntax: DROP DATABASE databasename;

The CREATE TABLE statement is used to create a new table in a database.


Syntax: REATE TABLE table_name (
     column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);

The DROP TABLE statement is used to drop an existing table in a database.


Syntax: DROP TABLE table_name;
Simple Queries
SELECT: The purpose of the SELECT statement is to retrieve and display data from one or
more database tables.
Most frequently used SQL command
Extremely powerful command
Capable of performing the equivalent of the relational algebra’s Selection, Projection, and
Join operations in a single statement
SYNTAX: SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from.

Select all the fields available in the table


SELECT * FROM table_name;
Simple Queries
General form of SELECT query:

olumnExpression represents a column name or an expression,


TableName is the name of an existing database table or view that you have access to
alias is an optional abbreviation for TableName.
Simple Queries
The sequence of processing in a SELECT statement is:

The order of the clauses in the SELECT statement cannot be changed


The only two mandatory clauses: SELECT and FROM; the remainder are optional.
Result of a query on a table is another table
Variations of SELECT Statement
Retrieve all columns, all rows
Retrieve specific columns, all rows
Use of DISTINCT
Calculated fields
SELECT Statement
Retrieve all columns, all rows
All columns of a table
SELECT staffNo, fName, IName, position, sex, DOB,
salary, branchNo
FROM Staff;
Quick way of expressing is using asterisk ( * ), in
place of the column names
SELECT *
FROM Staff;
SELECT Statement
Retrieve specific columns, all rows
Produce a list of salaries for all staff, showing only the
staff number, the first and last names, and the salary
details.
SELECT staffNo, fName, IName, salary
FROM Staff;
New table is created from Staff containing only the
designated columns staffNo, fName, IName, and
salary, in the specified order
SELECT Statement
Use of DISTINCT
List the property numbers of all properties that
have been viewed.
1. SELECT propertyNo
FROM Viewing; (several duplicates)
1 To eliminate the duplicates, we use the DISTINCT
keyword
2. SELECT DISTINCT propertyNo
FROM Viewing;

2
Calculated Fields
Sometimes called computed or derived fields
To use a calculated field, you specify an SQL expression in the SELECT list
An SQL expression can involve:
Addition,
Subtraction
Multiplication
Division
Parentheses can be used to build complex expressions
More than one table column can be used in a calculated column
The columns referenced in an arithmetic expression must have a numeric type.
Calculated Fields
Example:
SELECT staffNo, fName, IName, salary/12
FROM Staff;
SQL does not know how to label the
column
Some dialects give the column a name
corresponding to its position
Calculated Fields
SQL does not know how to label the column
Some dialects give the column a name corresponding to its position
Some may leave the column name blank
The ISO standard allows the column to be named using an AS clause.
EXAMPLE: SELECT staffNo, fName, IName, salary/12 AS monthlySalary
FROM Staff;
Row selection (WHERE clause)
Restrict the rows that are retrieved achieved with the WHERE clause
Keyword WHERE followed by a search condition that specifies the rows to be retrieved
The WHERE clause is equivalent to the relational algebra Selection operation
The five basic search conditions (or predicates, using the ISO terminology) are as follows:
1. Comparison search condition
1. Comparison search condition
EXAMPLE: List all staff with a salary greater than £10,000.
SELECT staffNo, fName, IName, position, salary
FROM Staff
WHERE salary > 10000;
INPUT: (Table: Staff) (Predicate: salary>10,000)
OUTPUT: Selection creates a new table containing only those Staff rows with a salary greater than £10,000.
1. Comparison search condition (cont.)
Logical operators are used for more complex predicates e.g., AND, OR
Parenthesis re used to show the order of evaluation
The rules for evaluating a conditional expression are:

The use of parentheses is always recommended, in order to remove any possible ambiguities
1. Comparison search condition
Compound comparison search condition
EXAMPLE: List the addresses of all branch offices in London or Glasgow.
SELECT *
FROM Branch
WHERE city = ‘London’ OR city = ‘Glasgow’;
2. Range search condition
(BETWEEN/NOT BETWEEN) : BETWEEN test includes the endpoints of the range
EXAMPLE:
SELECT staffNo, fName, IName, position, salary
FROM Staff
WHERE salary BETWEEN 20000 AND 30000;
2. Range search condition
There is also a negated version of range test (NOT BETWEEN)
Checks for values outside the range
BETWEEN condition works like two comparison operators
 SELECT staffNo, fName, IName, position, salary
FROM Staff
WHERE salary > = 20000 AND salary < = 30000;
BETWEEN test is a simpler way to express a search condition when considering a range of
values.
3. Set membership search condition
(IN/NOT IN) : The set membership test (IN) tests whether a data value matches one of a list of
values
EXAMPLE: List all managers and supervisors
 SELECT staffNo, fName, IName, position
FROM Staff
WHERE position IN (‘Manager’, ‘Supervisor’);
3. Set membership search condition
(IN/NOT IN) Cont..
There is a negated version (NOT IN) that can be used to check for data values that do not lie in
a specific list of values.
IN test does not add much to the expressive power of SQL, as previous query can also be
written expressed as:
SELECT staffNo, fName, IName, position
FROM Staff
WHERE position = ‘Manager’ OR position = ‘Supervisor’;

IN test provides a more efficient way of expressing the search condition, particularly if the set
contains many values.
4. Pattern Match Search Condition
LIKE/NOT LIKE)
SQL has two special pattern-matching symbols:
The % percent character represents any sequence of zero or more characters (wildcard).
The _ underscore character represents any single character

EXAMPLE: Find all owners with the string ‘Glasgow’ in their address.
 SELECT ownerNo, fName, IName, address, telNo
FROM PrivateOwner
WHERE address LIKE ‘%Glasgow%’;
4. Pattern Match Search Condition
EXAMPLE: Find all owners with the string ‘Glasgow’ in their address.
 SELECT ownerNo, fName, IName, address, telNo
FROM PrivateOwner
WHERE address LIKE ‘%Glasgow%’;
4. Pattern Match Search Condition
5. NULL search condition
IS NULL/IS NOT NULL
EXAMPLE:
 SELECT clientNo, viewDate
FROM Viewing
WHERE propertyNo = ‘PG4’ AND comment IS NULL;
SQL: Data Manipulation
(2)
DATABASE SYSTEMS: SIXTH EDITION
BY: CONALLY AND BEGG
Sorting Results (ORDER BY CLAUSE)
Single Column Ordering
EXAMPLE: Produce a list of salaries for all staff, arranged in descending order of salary.
 SELECT staffNo, fName, IName
FROM Staff
ORDER BY salary DESC;
Sorting Results (ORDER BY CLAUSE)
Multiple column ordering
EXAMPLE: Produce an abbreviated list of properties arranged in order of property type.
SELECT propertyNo, type, rooms, rent SELECT propertyNo, type, rooms, rent
FROM PropertyForRent FROM PropertyForRent
ORDER BY type; ORDER BY type, rent DESC;
Major Sort Key Minor Sort key
SQL Aggregate Functions
The ISO standard defines five aggregate functions:
COUNT – returns the number of values in a specified column
SUM – returns the sum of the values in a specified column
AVG – returns the average of the values in a specified column
 MIN – returns the smallest value in a specified column
 MAX – returns the largest value in a specified column
SQL Aggregate Functions
Aggregate functions operate on a single column of a table and return a single value
COUNT, MIN, and MAX apply to both numeric and nonnumeric fields
SUM and AVG may be used on numeric fields only
Each function eliminates nulls first and operates only on the remaining nonnull values
Aggregate function can be used only in the SELECT list and in the HAVING clause
SQL Aggregate Functions
Use of COUNT(*)
COUNT(*) is a special use of COUNT that counts all the rows of a table, regardless of whether
nulls or duplicate values occur
EXAMPLE : How many properties cost more than £350 per month to rent?
 SELECT COUNT(*) AS myCount
FROM PropertyForRent
WHERE rent > 350;
SQL Aggregate Functions
Use of COUNT(DISTINCT)
To eliminate duplicates before the function is applied, we use the keyword DISTINCT before the column
name in the function.
ISO standard allows the keyword ALL to be specified if we do not want to eliminate duplicates
Have significant effect on the result of SUM or AVG
Example: How many different properties were viewed in May 2013?
 SELECT COUNT(DISTINCT propertyNo) AS myCount
FROM Viewing
WHERE viewDate BETWEEN ‘1-May-13’ AND ‘31-May-13’;
The same property may be viewed many times, we have to use the DISTINCT keyword to eliminate duplicate
properties
SQL Aggregate Functions
Example: How many different properties were viewed in May 2013?
 SELECT COUNT(DISTINCT propertyNo) AS myCount
FROM Viewing
WHERE viewDate BETWEEN ‘1-May-13’ AND ‘31-May-13’;
SQL Aggregate Functions
Use of COUNT and SUM
EXAMPLE: Find the total number of Managers and the sum of their salaries.
 SELECT COUNT(staffNo) AS myCount, SUM(salary) AS mySum
FROM Staff
WHERE position = ‘Manager’;

SQL Aggregate Functions
Use of MlN, Max, aVG
EXAMPLE: Find the minimum, maximum, and average staff salary.
 SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary) AS myAvg
FROM Staff;
Grouping Results (GROUP BY
Clause)
A query that includes the GROUP BY clause is called a grouped query
Groups the data from the SELECT table(s) and produces a single
summary row for each group.
The columns named in the GROUP BY clause are called the grouping
columns
ISO standard requires the SELECT clause and the GROUP BY clause to
be closely integrated
When the WHERE clause is used with GROUP BY, the WHERE clause is
applied first, then groups are formed from the remaining rows that
satisfy the search condition.
Grouping Results (GROUP BY
Clause)
EXAMPLE: Find the number of staff working in each branch and the sum of their salaries.
 SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
SUBQUERIES
Subqueries
SELECT statement embedded within another SELECT statement
Results of this inner SELECT statement (or subselect) are used in the outer statement to help
determine the contents of the result
A sub-select can be used in the WHERE and HAVING clauses of an outer SELECT statement
where it is called a subquery or nested query.
Subselects may also appear in INSERT, UPDATE, and DELETE statements
Subqueries
Types of Subqueries
1. Scalar Subquery: Returns a single column and a single row, that is, a single value.
2. Row Subquery: Returns multiple columns, but only a single row.
3. Table Subquery: Returns one or more columns and multiple rows
Subquery
Using a subquery with equality
EXAMPLE: List the staff who work in the branch at ‘163 Main St’.
 SELECT staffNo, fName, IName, position
FROM Staff
WHERE branchNo = (SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’);
Subquery
QUESTIONS!!

You might also like