Sei sulla pagina 1di 44

Introduction to Structured

Query Language (SQL)


Updating Table Rows
• Use the UPDATE command to modify data in the
table.
• Syntax:
– UPDATE tablename SET columnname =
expression [,columnname =
expression][WHERE conditionlist]
• If more than one attributes is to be updated in row,
separate corrections with commas (,)

2
Updating Table Rows : Example
• Change P_INDATE from December 13, 2009, to
January 18, 2010 for the product 13-Q2/P2 of the
PRODUCT table.
UPDATE PRODUCT
SET P_INDATE = '18-JAN-2010'
WHERE P_CODE = '13-Q2/P2';
• If more than one attribute is to be updated in the row,
separate the corrections with commas:
UPDATE PRODUCT
SET P_INDATE = '18-JAN-2010', P_PRICE =
17.99, P_MIN = 10
WHERE P_CODE = '13-Q2/P2';
3
Updating Table Rows : Example
• What will happen if the UPDATE command
does not include the WHERE condition?
– P_INDATE, P_PRICE, and P_MIN values will be
changed in all rows of the PRODUCT table.
– UPDATE command is a set-oriented operator.
Therefore, if you don’t specify a WHERE
condition, the UPDATE command will apply the
changes to all rows in the specified table.

4
Deleting Table Rows
• DELETE
– Deletes a table row
– Syntax:
DELETE FROM tablename
[WHERE conditionlist ];
• WHERE condition is optional
• If WHERE condition is not specified, all rows from
specified table will be deleted

5
Deleting Table Rows: Example
• Delete from the PRODUCT table whose product code
is 'BRT-345':
DELETE FROM PRODUCT WHERE P_CODE =
'BRT-345';
• Here, the primary key value lets SQL find the exact
record to be deleted.
• However, deletions are not limited to a primary key
match; any attribute may be used.
• For example, to delete from PRODUCT table whose
P_MIN =5.
DELETE FROM PRODUCT WHERE P_MIN =
5;
• Check the PRODUCT table’s contents to verify that all
products with P_MIN equal to 5 have been deleted.
6
Deleting Table Rows (cont.)
• Remember that DELETE is a set-oriented
command.
• And keep in mind that the WHERE condition
is optional.
• Therefore, if you do not specify a WHERE
condition, all rows from the specified table
will be deleted!

7
Advanced Data Definition Commands
• All changes in table structure are made by
using ALTER command
• Three options:
– ADD adds a column
– MODIFY changes column characteristics
– DROP deletes a column
• Can also be used to:
– Add table constraints
– Remove table constraints

8
Syntax of ALTER TABLE
• Add or Modify columns
ALTER TABLE tablename
{ADD | MODIFY} ( columnname datatype );
• Add table constraints
ALTER TABLE tablename
ADD constraint;
• Remove a column or table constraint
ALTER TABLE tablename
DROP{PRIMARY KEY | COLUMN columnname |
CONSTRAINT constraintname };
When removing a constraint, you need to specify the name given
to the constraint. That is one reason why you should always name
your constraints in your CREATE TABLE or ALTER TABLE
statement.
9
Changing a Column’s Data Type
• ALTER can be used to change data type.
• Some RDBMSs, such as Oracle, do not let
you change data types unless the column to
be changed is empty.
• Example: To change the V_CODE field
from the current number definition to a
character definition.
ALTER TABLE PRODUCT
MODIFY (V_CODE CHAR(5));

10
Changing a Column’s Data
Characteristics
• Use ALTER to change data characteristics
• Changes in column’s characteristics are
permitted if changes do not alter the existing
data type.
• For example, if you want to increase the width
of the P_PRICE column to nine digits, use the
command:
ALTER TABLE PRODUCT
MODIFY (P_PRICE DECIMAL(9,2));
11
Adding a Column
• Can alter an existing table by adding one or more
columns.
• For example, add the column named P_SALECODE to
the PRODUCT table.
ALTER TABLE PRODUCT
ADD (P_SALECODE CHAR(1));
When adding a column, be careful not to include the NOT NULL
clause for the new column. Doing so will cause an error message;
if you add a new column to a table that already has rows, the
existing rows will default to a value of null for the new column.
Therefore, it is not possible to add the NOT NULL clause for this
new column. (You can, of course, add the NOT NULL clause to the
table structure after all of the data for the new column have been
entered and the column no longer contains nulls.)

12
Dropping a Column
• Modify a table by deleting a column.
• Example: Delete V_ORDER attribute from the
VENDOR table.
ALTER TABLE VENDOR
DROP COLUMN V_ORDER;
• Some RDBMSs impose restrictions on attribute
deletion.
– For example, you may not drop attributes that are
involved in foreign key relationships, nor may you
delete an attribute of a table that contains only that
one attribute.

13
Advanced Data Updates
• The UPDATE command updates only data in existing rows.
• For example: Enter P_SALECODE value '2' for the P_CODE '1546-QQ2'.
UPDATE PRODUCT
SET P_SALECODE = '2'
WHERE P_CODE = '1546-QQ2';
• Subsequent data can be entered the same way, defining each entry location
by its primary key (P_CODE) and its column location (P_SALECODE).
• For example, to enter the P_SALECODE value '1' for the P_CODE values
'2232/QWE' and '2232/QTY‘.
UPDATE PRODUCT
SET P_SALECODE = '1'
WHERE P_CODE IN ('2232/QWE', '2232/QTY');

14
Advanced Data Updates (cont.)
• If your RDBMS does not support IN, use the following command:
UPDATE PRODUCT
SET P_SALECODE = '1'
WHERE P_CODE = '2232/QWE' OR P_CODE = '2232/QTY';
• The arithmetic operators are useful in data updates.
• For example, if the quantity on hand in your PRODUCT table has dropped
below the minimum desirable value, you’ll order more of the product.
• Suppose, for example, you have ordered 20 units of product 2232/QWE. When
the 20 units arrive, you’ll want to add them to inventory, using:
UPDATE PRODUCT
SET P_QOH = P_QOH + 20
WHERE P_CODE = '2232/QWE';

15
Advance SQL
Relational Set Operators
• The set operations union, intersect and except operate on
relations and corresponding to the relational algebra .
• Each of the above operations automatically eliminates
duplicates.
• To retain all duplicates use the correspoding multiset version
union all, intersect all and except all.
• Union, intersect and minus work properly only if relations are
union-compatible, which means that the number of attributes
must be the same and their corresponding data types must be
alike.
Union Operation - Example
• The UNION statement combines rows from two or more
queries without including duplicate rows.
• Syntax:
query UNION query
• In other words, the UNION statement combines the output of
two SELECT queries.
Union Operation – Example (1)
Union all Operation - Example
EXCEPT Operation

SELECT * FROM a
except
SELECT* FROM b

MySQL supports no MINUS or EXCEPT operation


INTERSECT Operation

SELECT * FROM a
INTERSECT
SELECT * FROM b

MySQL supports no INTERSECT


Multirow Subquery Operators: ANY
and ALL
• Allows comparison of single value with a list of
values using inequality comparison
– IN subquery uses an equality operator
• it selects only those rows that match (are equal to) at least one of
the values in the list.
– What happens if you need to do an inequality comparison
(> or <) of one value to a list of values?
• some ( >some,<some,<=some,>=some,=some,
<>some)
• all ( >all,<=all,>=all,=all,<>all)
• NOTE:
– =some is identical to in, whereas <>some is
not the same as not in.
– <>all is identical to not in
Definition of some Clause
Definition of all Clause
Example - some
• Find the names of all instructors whose salary is greater than
at least one instructor in the Biology department.
– select name from instructor where salary > some (select
salary from instructor where dept name = ’Biology’);

Example - all
• Find the names of all instructors whose salary is greater than
the salary of all instructors in the Biology department.
– select name from instructor where salary > all (select salary
from instructor where dept name = ’Biology’)
Example - all
• Find the names of all instructors whose salary is greater than
the salary of all instructors in the Biology department.
– select name from instructor where salary > all (select salary
from instructor where dept name = ’Biology’)
Introduction to SQL-3
Multiple source tables
• Using more than a single table of a database is
usually essential.
• The basic form is just to list all the needed tables in
the from line.
• You do have to explain to the DBMS how the tables
should be joined together…

30
Joined Relations
• Join operations take two relations and return as a result another
relation.
• Different types of JOINS.
1. CROSS JOIN
2. INNER JOIN
3. OUTER JOIN
Outer Joins are again divided into 3 types
1. Left Join or Left Outer Join
2. Right Join or Right Outer Join
3. Full Join or Full Outer Join
A join operation is a Cartesian product which requires that tuples in
the two relations match (under some condition). It also specifies
the attributes that are present in the result of the join
• The join operations are typically used as subquery expressions in
the from clause

31
Example
• Find the Cartesian product instructor X teaches
select *
from instructor, teaches
– generates every possible instructor – teaches pair, with all
attributes from both relations.
• Cartesian product is not very useful directly, but useful combined
with where-clause condition.
• CROSS JOIN
CROSS JOIN, produces the cartesian product of
the 2 tables involved in the join. For example, in
the Employees table we have 15 rows and in the
Departments table we have 4 rows. So, a cross
join between these 2 tables produces 60 rows.
Cross Join shouldn't have ON clause

32
Cartesian Product
instructor teaches

33
Joined Relations
• Join condition – defines which tuples in the two relations
match, and what attributes are present in the result of the
join.
• Join type – defines how tuples in each relation that do not
match any tuple in the other relation (based on the join
condition) are treated.

General Formula for Joins


SELECT ColumnList
FROM LeftTableName
JOIN_TYPE RightTableName
ON JoinCondition

34
Join operations – Datasets for Examples

 Note: borrower information missing for L-260


and loan information missing for L-155

35
Join operations
INNER JOIN, returns only the matching rows between
both the tables. Non matching rows are eliminated
LEFT JOIN, returns all the matching rows + non
matching rows from the left table. In reality, INNER
JOIN and LEFT JOIN are extensively used
RIGHT JOIN, returns all the matching rows + non
matching rows from the right table
FULL JOIN, returns all rows from both the left and right
tables, including the non matching rows.

36
Inner join – Examples
• loan inner join borrower on
loan.loan_number = borrower.loan_number

• loan left outer join borrower on


loan.loan_number = borrower.loan_number

37
Joined Relations – Examples (cont.)

• loan natural inner join borrower

• loan natural right outer join borrower

38
Joined Relations – Examples (cont.)
• loan full outer join borrower using (loan_number)

39
Tuple Variables
• Tuple variables are defined in the from clause via the use of
the as clause.
• Eg: Find the names of all instructors and the courses they are
teaching.
select I.name,T.course_id
from instructor as I, teaches as T
where I.instructor_id=T.instructor_id

• Keyword as is optional and may be omitted


instructor as I ≡ instructor I

40
Tuple Variables-example
• Find the names of all instructors who have a higher
salary than some instructor in ‘Comp. Sci’.

select distinct T. name,T.salary


from instructor T, instructor S
where T.salary > S.salary and
T.dept_name='Comp.Sci'

41
Self Join
• A MANAGER is also an EMPLOYEE. Both the,
EMPLOYEE and MANAGER rows, are present in the
same table. Here we are joining EMP with itself using
different alias names, E for Employee and M for
Manager.
select e.ENAME,m.ENAME as manager
from emp e
left join emp m
on e.EMPNO=m.MGR

42
View
A view is nothing more than a SQL statement that is stored in the
database with an associated name. A view is actually a composition of a
table in the form of a predefined SQL query.
A view is nothing more than a saved SQL query. A view can also be
considered as a virtual table.
Advantages of using views:
1. Views can be used to reduce the complexity of the database schema,
for non IT users.

2. Views can be used as a mechanism to implement row and column level


security.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2..... FROM table_name WHERE [condition];

43
View -Example
• Create a view from loan(branch_name, loan_number,
amount) that hides the amount information.
create view branch_loan as
select branch_name, loan_number
from loan
• Find all loans in the Downtown branch (from view
branch_loan)
select loan_number
from branch_loan
where branch_name = ‘Downtown’
• A user who has access to the view, but not the loan
table, cannot see the amount.

44

Potrebbero piacerti anche