0% found this document useful (0 votes)
16 views38 pages

DB Lec4

The document provides an overview of SQL data manipulation, covering logical operators, aggregate functions, subqueries, and transaction statements. It explains the syntax and usage of various SQL commands such as SELECT, CREATE TABLE, CREATE VIEW, and the use of operators like IN, BETWEEN, and set operations like UNION and INTERSECT. Additionally, it includes examples and descriptions of data types and SQL schema statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views38 pages

DB Lec4

The document provides an overview of SQL data manipulation, covering logical operators, aggregate functions, subqueries, and transaction statements. It explains the syntax and usage of various SQL commands such as SELECT, CREATE TABLE, CREATE VIEW, and the use of operators like IN, BETWEEN, and set operations like UNION and INTERSECT. Additionally, it includes examples and descriptions of data types and SQL schema statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Data Manipulation Using

SQL
Table List

sailors
We will use these instances of
the
sailors and reservation
relations in our examples.
sailors1

reservation
Logical Operators

• The logical operators are AND, OR, NOT. They


take logical expressions as operands and
produce a logical result (True, False).
Logical Operators
• AND returns:
– True -- if both operands evaluate to true
– False -- if either operand evaluates to false

• OR returns:
– True -- if either operand evaluates to true
– False -- if both operands evaluate to false

• NOT operator inverts the result of a comparison


expression or a logical expression.
Logical Operators
AND
Input 1 Input 2 Input 1 Input 2 OR Result
Result
True True
True True
True False True False
False False False False
False True False True

Input NOT Result


True
False
SQL Logical Operators

SELECT * FROM sp WHERE sno=‘22' AND qty <


500

SELECT * FROM s WHERE sno=‘22' OR city =


'London‘

SELECT * FROM sp WHERE NOT sno = ‘22'


SQL IN Operator
• The IN operator allows you to specify multiple
values in a WHERE clause.
• Syntax,

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
SQL IN Example

• SELECT * FROM saliors WHERE age IN (35, 45);


Aggregate Operators
• COUNT -- count of rows
• SUM -- arithmetic sum of numeric
column
• AVG -- arithmetic average of numeric
column; should be
SUM()/COUNT().
• MIN -- minimum value found in column
• MAX -- maximum value found in column
Aggregate Operators
• SELECT COUNT (*) FROM sailors AS s;

• SELECT AVG (s.age) FROM sailors AS s WHERE s.rating=10;

• SELECT s.sname FROM sailors AS s WHERE s.rating= (SELECT


MAX(s2.rating) FROM sailors1 AS s2);

• SELECT COUNT (DISTINCT s.rating) FROM sailors AS s


WHERE s.sname=‘Bob;

• SELECT AVG ( DISTINCT s.age) FROM sailors AS s WHERE


s.rating=10;
Find name and age of the oldest
sailor(s)

SELECT s.name, MAX (s.age) FROM sailors AS s;

SELECT s.sname, s.age FROM sailors AS s WHERE


s.age = (SELECT MAX (s2.age) FROM Sailors AS
s2);
SQL BETWEEN Operator
• The BETWEEN operator selects values within a
range. The values can be numbers, text, or
dates.

• SQL BETWEEN Syntax:


SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SQL BETWEEN Example

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;
Subqueries
There are 3 basic types of subqueries in SQL:

• Predicate Subqueries -- Extended logical


constructs in the WHERE (and HAVING)
clause.

• Scalar Subqueries -- Standalone queries that


return a single value. They can be used
anywhere a scalar value is used.

• Table Subqueries -- Queries nested in the FROM


clause.
Subqueries
The comparison operator specifies how to compare
value-1 to the single query column value from each
subquery result row.

SELECT * FROM p WHERE pno = (SELECT pno FROM sp


where pno IS NOT NULL)

SELECT * FROM sp AS a WHERE qty >


( SELECT qty FROM sp b
WHERE a.pno = b.pno AND a.sno <> b.sno AND
qty IS NOT NULL )
SQL-Transaction Statements
SQL-Transaction Statements control transactions
in database access. There are 2 SQL-
Transaction Statements:

• COMMIT Statement -- commit (make


persistent) all changes for the current
transaction.
• ROLLBACK Statement -- roll back (rescind) all
changes for the current transaction.
Transaction Overview
A transaction ensures that the action of the framed
statements is atomic with respect to recovery. A SQL
Modification Statement has limited effect.

A given statement can only directly modify the contents of a


single table (Referential Integrity effects may cause indirect
modification of other tables.)

A classic example is a bank operation that transfers funds from


one type of account to another, requiring updates to 2 tables.
Transactions provide a way to group these multiple
statements in one unit.
SQL-Transaction Statements
• COMMIT Statement - The COMMIT Statement
terminates the current transaction and makes
all changes under the transaction persistent.
It commits the changes to the database.

• ROLLBACK Statement - The ROLLBACK Statement


terminates the current transaction and
rescinds all changes made under the
transaction. It rolls back the changes to the
database.
SQL-Schema Statements
• CREATE TABLE Statement -- create a new base
table in the current schema.

• CREATE VIEW Statement -- create a new view


table in the current schema.

• DROP TABLE Statement -- remove a base table


from the current schema.

• DROP VIEW Statement -- remove a view table


from the current schema.
Tables
• A table has a fixed set of columns. The
columns in a base table are not accessed
positionally but by name, which must be
unique among the columns of the table. Each
column has a defined data type, and the value
for the column in each row must be from the
defined data type or null. The columns of a
table are accessed and identified by name.
Data Type
This subsection describes data type
specifications. The data type categories are:

• Character (String)
CHAR [(length)]
CHARACTER [(length)]
VARCHAR [(length)]

length specifies the number of characters for


fixed size strings (CHAR, CHARACTER).
Data Type
• Numeric
SMALLINT
INT
INTEGER The integer types have default binary precision -- 15 for SMALLINT and 31
for INT, INTEGER.

• Fixed point types have a decimal precision (total number of digits) and scale
(which cannot exceed the precision). The default scale is 0. NUMERIC scales must
be represented exactly.
• DECIMAL values can be stored internally with a larger scale (implementation
defined).

• FLOAT [(precision)]
REAL
DOUBLE

• The floating point types have a binary precision (maximum significant binary
digits).
• Precision values are implementation dependent for REAL and DOUBLE, although
the standard states that the default precision for DOUBLE must be larger than for
REAL.
• FLOAT also uses an implementation defined default for precision (commonly this is
the same as for REAL), but the binary precision for FLOAT can be explicit.
Data Type
• Datetime
DATE
TIME [(scale)] [WITH TIME ZONE]
TIMESTAMP [(scale)] [WITH TIME ZONE] TIME and

TIMESTAMP allow an optional seconds fraction (scale).


The default scale for TIME is 0, for TIMESTAMP 6. The
optional WITH TIME ZONE specifier indicates that the
timezone adjustment is stored with the value; if
omitted, the current system timezone is assumed.
CREATE TABLE Statement
The CREATE TABLE Statement creates a new base table.
It adds the table description to the catalog. A base
table is a logical entity with persistence. The logical
description of a base table consists of:

• Schema -- the logical database schema the table


resides in.
• Table Name -- a name unique among tables and views
in the Schema.
• Column List -- an ordered list of column declarations.
• Constraints -- a list of constraints on the contents of
the table.
CREATE TABLE Statement
The CREATE TABLE Statement has the following general format:

CREATE TABLE table-name ({column-descr|constraint} [,{column-descr|constraint}]...)

CREATE TABLE s
(sno VARCHAR(5) NOT NULL PRIMARY KEY,
name VARCHAR(16),
city VARCHAR(16)
)

CREATE TABLE p
(pno VARCHAR(5) NOT NULL PRIMARY KEY,
descr VARCHAR(16),
color VARCHAR(8)
)

CREATE TABLE sp
(sno VARCHAR(5) NOT NULL REFERENCES s,
pno VARCHAR(5) NOT NULL REFERENCES p,
qty INT,
PRIMARY KEY (sno, pno)
)
CREATE TABLE Statement
Create for sp with a constraint that the qty column
can't be negative:

CREATE TABLE sp
(sno VARCHAR(5) NOT NULL REFERENCES s,
pno VARCHAR(5) NOT NULL REFERENCES p,
qty INT CHECK (qty >= 0),
PRIMARY KEY (sno, pno)
)
CREATE VIEW Statement
The CREATE VIEW statement creates a new database view.
A view is effectively a SQL query stored in the catalog.

The CREATE VIEW has the following general format:


CREATE VIEW view-name [ ( column-list ) ] AS query-1 [ WITH
[CASCADED|LOCAL] CHECK OPTION ]

• view-name is the name for the new view. column-list is an


optional list of names for the columns of the view, comma
separated.
• query-1 is any SELECT statement without an ORDER BY
clause.
• The optional WITH CHECK OPTION clause is a constraint on
updatable views.
CREATE VIEW Statement
• CREATE VIEW supplied_parts AS
SELECT * FROM p
WHERE pno IN
(SELECT pno FROM sp)

• CREATE VIEW part_locations (part, quantity,


location)
AS
SELECT pno, qty, city
FROM sp, s
WHERE sp.sno = s.sno
DROP TABLE, View Statement
• The DROP TABLE Statement removes a previously
created table and its description from the catalog.
It has the following general format:

DROP TABLE table-name {CASCADE|RESTRICT}

• The DROP VIEW Statement removes a previously


created view and its description from the catalog.
It has the following general format:

DROP VIEW view-name {CASCADE|RESTRICT}


Union, Intersect, and Difference
(Except)
• Can use normal set operations of Union, Intersection,
and Difference to combine results of two or more
queries into a single result table.

• Union of two tables, A and B, is table containing all


rows in either A or B or both.

• Intersection is table containing all rows common to


both A and B.

• Difference is table containing all rows in A but not in B.

• Two tables must be union compatible.


Union, Intersect, and Difference
(Except)
Use of UNION
• List all cities where there is either a branch or
property.

(SELECT city FROM Branch WHERE city IS NOT


NULL)
UNION
(SELECT city FROM PropertyForRent WHERE city
IS NOT NULL);
Use of UNION
Or

(SELECT * FROM Branch WHERE city IS NOT


NULL)
UNION CORRESPONDING BY city
(SELECT * FROM PropertyForRent WHERE city IS
NOT NULL);
Use of UNION
Produces result tables from both queries and
merges both tables together.
Use of INTERSECT
List all cities where there is both a branch and
rental property.

(SELECT city FROM Branch)


INTERSECT
(SELECT city FROM PropertyForRent);

(SELECT * FROM Branch)


INTERSECT CORRESPONDING BY city
(SELECT * FROM PropertyForRent);
Use of INTERSECT
Could rewrite this query without INTERSECT
operator:

• SELECT b.city FROM Branch As b


PropertyForRent As p WHERE b.city = p.city;
Use of EXCEPT
List of all cities where there is a branch but no
properties.

(SELECT city FROM Branch)


EXCEPT
(SELECT city FROM PropertyForRent);

Or

(SELECT * FROM Branch)


EXCEPT CORRESPONDING BY city
(SELECT * FROM PropertyForRent);
Websites to Learn SQL

• http://www.w3schools.com/sql/default.asp

• http://www.tizag.com/sqlTutorial/

You might also like