SlideShare a Scribd company logo
1 of 71
6 September 2019 Sikandar 1
Lesson 05
Relational Languages
6 September 2019 Sikandar 2
Relational Languages
 Commercial DB systems require more “User Friendly”
languages.
 Query languages (User makes requests to the DB to
obtain info.
 These languages should preserve fundamental
constructs and concepts
 Ones we saw in Relational Algebra.
 Examples
 SQL (Structured Query Language)
 QBE (Query By Example)
6 September 2019 Sikandar 3
Relational Languages
 SQL
 MS Access SQL version
 Oracle SQL version
 DB2 SQL version
 Etc
 Very Minor Differences between all the
implementations.
6 September 2019 Sikandar 4
SQL
 SQL consists of 2 key Parts
 Data Definition Language (DDL)
 The commands for defining , deleting, and
modifying relations schemas or structure , we can
change the structure of the table insert columns
etc.
 Data Manipulation Language (DML)
 This is further divided into two parts
 Commands to retrieve information called (Query
Part)
 The commands to insert , delete, and update tuples
called (Modification Part)
6 September 2019 Sikandar 5
SQL
DDL used to create
the table P# PNAME COLOR WEIGHT CITY
P1 Nut Red 12 London
P2 Bolt Green 17 Paris
P3 Screw Blue 17 Rome
P4 Screw Red 14 London
P5 Cam Blue 12 Paris
P6 Cog Red 19 London
DML used to fill the
table with tuples etc
 The languages Used to extract info or retrieve info are
called “Querying Languages”
6 September 2019 Sikandar 6
DML
 Query Part (of DML)
 Basic Structure
(3 clauses)
 Select
 From
 Where
 Select:
 Correspond to the project operation of relational
algebra.
 Lists the attributes desired in the result of the query.
6 September 2019 Sikandar 7
DML
 From:
 Corresponds to the Cartesian product operation in
relational algebra
 Lists the relations to be scanned in the evaluation
process
 Where:
 Corresponds to the selection conditions
 Involves attributes of the relations in the from clause.
 Typical Format:
select A1, A2, A3……..An (attribute names)
From r1,r2,r3………… rn (Relation names)
Where P (conditions)
6 September 2019 Sikandar 8
DML
 Typical Format:
select A1, A2, A3……..An (attribute names)
From r1,r2,r3………… rn (Relation names)
Where P (conditions)
 Similar expression can be written in relational
algebra
 ( ( r1,r2,r3………… rn ) where P ) [A1, A2,
A3……..An]
 If where is omitted the selection condition is true
for all tuples, so we only use 2 clauses
Select s#, city
From suppliers;
6 September 2019 Sikandar 9
DML examples
 If we want the whole table
Select *
From suppliers
 All of the info suppliers located in London
Select *
From suppliers
Where city = ‘London’
6 September 2019 Sikandar 10
Operators for where clause
 Operators for where clause:
 Logical operators
 AND, OR, NOT etc.
 Comparison operators
 < , > , <> , >= , <= etc
 Arithmetic operators
 + , - , / , *
 Between (or NOT between)
 A type of comparison operator.
6 September 2019 Sikandar 11
Operators for where clause
example 1
Select s#
From supplier
Where (status>= 0) AND (status <= 30);
example 2
select s#
From supplier
where (status between 10 and 30)
example 3
select s#
From supplier
where (status not between 10 and 30)
6 September 2019 Sikandar 12
String matching operators
 Oracle gives 2 special characters (wild characters)
 Percent(%) matches any sub string
 Under score (_) matches any character
 For Access
 * matches any sub string
 ? matches any character
6 September 2019 Sikandar 13
String matching operators examples
 “ABC%”
 Matches any string beginning with ABC.
 “%ABC%”
 Matches any string containing ABC as a sub string.
 ‘_ _ _’
 Matches any string with exactly 3 characters.
 ‘_ _ %”
 Matches any string matching at least 2 character
long.
6 September 2019 Sikandar 14
String matching operators
 Patterns are expressed using “LIKE” comparison
operator.
 Example
 Select SNAME
 From supplier
 Where city LIKE ‘%York%’ ;
 Example
 Select city
 From supplier
 Where SNAME LIKE ‘T%’ ;
To Use wild cards
we must use LIKE
operator
6 September 2019 Sikandar 15
Join
 No direct representation of natural join in SQL.
 SQL use Theta join.
 Example
 A list of parts number supplied by TOM
Select P#
From suppliers, shipment
Where (supplier.S# = shipment.S#)
 System creates a Cartesian product of the 2 tables.
6 September 2019 Sikandar 16
Handling Duplicate Tuples
 It is very tough to check duplicate tuples by default.
 there can be duplicate tuples due to the result of a
query.
 SQL allows duplicates by default
 Duplicate elimination is very costly.
 Also we might require an idea or number of tuples
recovered due to some query.
 To force elimination we use DISTINCT after select
clause.
6 September 2019 Sikandar 17
Distinct
 Example
 A list of cities for suppliers.
select city
from suppliers; //we get a lot of duplicate cities
select distinct city
from suppliers; // all duplicates are eliminated.
6 September 2019 Sikandar 18
Set Operators (  ,  , )
 UNION:
 Eliminates duplicates by default, if we want to keep
duplicates , we use : UNION ALL.
 Example
( Select SNAME
From supplier
Where (status > 30) )
UNION
( Select SNAME
From supplier
Where city = ‘London’)
6 September 2019 Sikandar 19
UNION
 Instead of the previous code we can also use
Select SNAME
From supplier
Where (status > 30 ) OR (city = ‘London’)
 If table names are different then we use UNION
 if we want to keep duplicates we use UNION ALL.
6 September 2019 Sikandar 20
Intersection and Minus
 Both intersection and Minus are NOT included in ANSI
standards , majority of SQL vendors do not support
these two.
 Some times even UNION is not supported
6 September 2019 Sikandar 21
Additional Operators
 IN and NOT IN
 Operator tests for set membership where the set is a
collection of values produced by the select clause in a
sub expression (“sub select”).
 E.g
 Get S# for suppliers who supplied ‘P2’ AND are
located in London.
Select S#
From shipment
Where p# = ‘P2’ and S# IN ( select S#
from suppliers
where (city = ‘London’) )
6 September 2019 Sikandar 22
IN and NOT IN
Select S#
From shipment
Where p# = ‘P2’ and S# IN ( select S#
from suppliers
where (city = ‘London’) )
 First check if P# for s# = P2
 If passes then
 Check S# is in London or not.
 OR
Select S#
From shipment
Where p# = ‘P2’ and S# IN ( ‘S1’ , ‘S2 , ‘S5’ )
 We can also use NOT IN
6 September 2019 Sikandar 23
ANY
 > ANY
 < ANY
 <= ANY
 >= ANY
 <> ANY
 This operator is called “set comparison operator”
 Example
 Find SNAME where all suppliers who had greater status
then some supplier located in ‘London’
6 September 2019 Sikandar 24
ANY
Select SNAME
From supplier
Where status > ANY ( select status
from supplier
where city = ‘London’ )
6 September 2019 Sikandar 25
ALL
 > ALL
 < ALL etc
Select SNAME
From supplier
Where status > ALL (select status
from supplier
where ( city = ‘London’ )
6 September 2019 Sikandar 26
Tuple Variable
 SQL uses the notion of tuple variables
 A tuple variable is defined in the FROM clause by
placing it after the name of the relation separated by
space.
 Tuple variables are most useful for comparing 2 tuples
in the same relation.
6 September 2019 Sikandar 27
Tuple Variable
 Example
find all customers who have a deposit account at
some branch at which Tom has an account.
Select copy2.customer
From deposit copy1 , deposit copy2
Where (copy1.customer = ‘Tom’
AND copy1.branchName = copy2.branchName)
 This makes 2 copies , makes an anchor and then
compare the 2 tuples
6 September 2019 Sikandar 28
Tuple Variable
 Example
get supplier’s name SNAME for suppliers who are
located in the same city as Tom.
Select B.SNAME
From supplier A, supplier B
Where A.SNAME = ‘Tom’ AND (A.city = B.city)
6 September 2019 Sikandar 29
Tuple Variable
 Example
Get all pairs of SNAME such the two suppliers
concerned are located in the same city.
Select X.SNAME , Y.SNAME
From supplier X , supplier Y
Where X.city = Y.city;
Now we might get some redundant information
Tom Tom
Tom Bob
Bob Tom
Etc, now how to eliminate duplicates ?
6 September 2019 Sikandar 30
Tuple Variable
Select X.SNAME , Y.SNAME
From supplier X , supplier Y
Where ( X.city = Y.city) AND (X.SNAME >
Y.SNAME)
Now we might get
Tom Tom
Tom Bob
Bob Tom
6 September 2019 Sikandar 31
Extra Clauses And Features
 ORDER BY:
 Used for ordering the display of tuples
 Order of statements is as follows:
 Select
 From
 Where
 Order by
6 September 2019 Sikandar 32
ORDER BY
Example:
select *
from suppliers
where status >= 10
order by status
S# SNAME STATUS CITY
S1 Smith 20 London
S2 Jones 10 Paris
S3 Blake 30 Paris
S4 Clark 20 London
S5 Adams 30 Athens
Supplier S (original table)
S# SNAME STATUS CITY
S2 Jones 10 Paris
S4 Clark 20 London
S1 Smith 20 London
S3 Blake 30 Paris
S5 Adams 30 Athens
Query result
6 September 2019 Sikandar 33
ORDER BY
 Default Order of order by is ascending.
 If we use
 Order by column_name desc
 We get a descending order of the tuples according to
column named column_name
Select *
From shipment
Order by s# , P# desc
6 September 2019 Sikandar 34
ORDER BY
Select account , customer , balance
From deposit
Order by 3 , 1 , 2
6 September 2019 Sikandar 35
Computing Functions
 Computing functions cannot be nested, I.e min(max())
 Examples of computing functions are
 Avg
 Sum
 Count
 Max
 Min etc
6 September 2019 Sikandar 36
Computing Functions
 Examples
Select avg(balance)
From deposit;
Select avg(qty)
From shipment;
Select avg(qty)
From shipment
Where S#=S1
6 September 2019 Sikandar 37
Computing Functions
 Examples
count the number of tuples in shipment
select count(*)
from shipment;
how many suppliers have made shipment
select count(distinct S#)
from shipment;
6 September 2019 Sikandar 38
Modify Part Of DML
 1) Deletion
 Delete whole tuple(s)
 <format>
Delete from table_name
Where condition
e.g.
Delete all of shipments made by S2
delete from shipment
where S# = ‘S2’
6 September 2019 Sikandar 39
Deletion
 E.g
Delete from suppliers
Where city = ‘London’
 E.g.
 Delete all deposit accounts at branches located in Chicago
 Deposit(branch_name, Account, customer, balance)
 Branches(branch_name, asserts , city)
Delete from deposit
Where branch_name IN ( select branch_name
from branches
Where city = ‘Chicago’ ; )
6 September 2019 Sikandar 40
Data Manipulation Language
 A DML statement is executed when you:
 Add new rows to a table
 Modify existing rows in a table
 Remove existing rows from a table
 A transaction consists of a collection of
DML statements that form a logical unit
of work.
6 September 2019 Sikandar 41
Adding a New Row to a Table
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
New row
50 DEVELOPMENT DETROIT
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
“…insert a new row
into DEPT table…”
50 DEVELOPMENT DETROIT
6 September 2019 Sikandar 42
The INSERT Statement
Add new rows to a table by using the
INSERT statement.
Only one row is inserted at a time with
this syntax.
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
6 September 2019 Sikandar 43
Inserting New Rows
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.
 Insert a new row containing values for each
column.
 List values in the default order of the
columns in the table.
 Optionally list the columns in the INSERT
clause.
 Enclose character and date values within
single quotation marks.
6 September 2019 Sikandar 44
Null Values
 A Null value is either unknown or not applicable.
 NULL is not equal to “” , or FI, or empty string
 E.g
 Insert into deposit
 Values(‘NEIU’ , 1006 , NULL , 1200)
 OR
 Values(‘NEIU’ , 1006 , , 1200)
6 September 2019 Sikandar 45
Nulls
 Problems caused by NULL values
 All comparison operations involving NULL are false.
 They simply wont be selected.
 Avoid using NULLs.
Select *
From shipment
Where qty < 200;
 So NULL rows wont be selected.
6 September 2019 Sikandar 46
DDL (Data Defination Language)
 To specify or modify schema definations
 To create tables
 To Update tables
6 September 2019 Sikandar 47
Creating and Managing
Tables
6 September 2019 Sikandar 48
Objectives
 After completing this lesson, you
should be able to do the following:
 Describe the main database objects
 Create tables
 Describe the datatypes that can be used
when specifying column definition
 Alter table definitions
 Drop, rename, and truncate tables
6 September 2019 Sikandar 49
Database Objects
Object Description
Table Basic unit of storage; composed of rows
and columns
View Logically represents subsets of data from
one or more tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Gives alternative names to objects
6 September 2019 Sikandar 50
Naming Conventions
Must begin with a letter
Can be 1–30 characters long
Must contain only A–Z, a–z, 0–9, _, $, and #
Must not duplicate the name of another
object owned by the same user
Must not be an Oracle Server reserved word
6 September 2019 Sikandar 51
The CREATE TABLE Statement
CREATE [GLOBAL TEMPORARY] TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);
 You must have :
 CREATE TABLE privilege
 A storage area
 You specify:
 Table name
 Column name, column datatype, and
column size
6 September 2019 Sikandar 52
Referencing Another User’s
Tables
 Tables belonging to other users are not
in the user’s schema.
 You should use the owner’s name as a
prefix to the table.
6 September 2019 Sikandar 53
The DEFAULT Option
… hiredate DATE DEFAULT SYSDATE, …
 Specify a default value for a column during an
insert.
• Legal values are literal value, expression, or SQL
function.
• Illegal values are another column’s name or
pseudocolumn.
• The default datatype must match the column
datatype.
6 September 2019 Sikandar 54
Creating Tables
SQL> CREATE TABLE dept
2 (deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13));
Table created.
• Confirm table creation.
SQL> DESCRIBE dept
Name Null? Type
--------------------------- -------- ---------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
 Create the table.
6 September 2019 Sikandar 55
Tables in the Oracle Database
 User Tables
 Collection of tables created and maintained
by the user
 Contain user information
 Data Dictionary
 Collection of tables created and maintained
by the Oracle server
 Contain database information
6 September 2019 Sikandar 56
Querying the Data Dictionary
• View distinct object types owned by the
user.
• View tables, views, synonyms, and
sequences owned by the user.
SQL> SELECT *
2 FROM user_tables;
SQL> SELECT DISTINCT object_type
2 FROM user_objects;
SQL> SELECT *
2 FROM user_catalog;
• Describe tables owned by the user.
6 September 2019 Sikandar 57
Datatypes
Datatype Description
VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data
up to 2 gigabytes
CLOB Single-byte character data up to 4
gigabytes
RAW and LONG RAW Raw binary data
BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an external
file; up to 4 gigabytes
6 September 2019 Sikandar 59
Creating a Table
by Using a Subquery
CREATE TABLE table
[(column, column...)]
AS subquery;
 Create a table and insert rows by combining the
CREATE TABLE statement and AS subquery option.
 Match the number of specified columns to the
number of subquery columns.
 Define columns with column names and
default values.
6 September 2019 Sikandar 60
SQL> CREATE TABLE dept30
2 AS
3 SELECT empno, ename, sal*12 ANNSAL, hiredate
4 FROM emp
5 WHERE deptno = 30;
Table created.
Creating a Table
by Using a Subquery
Name Null? Type
---------------------------- -------- -----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
ANNSAL NUMBER
HIREDATE DATE
SQL> DESCRIBE dept30
6 September 2019 Sikandar 61
The ALTER TABLE Statement
ALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);
ALTER TABLE table
MODIFY (column datatype [DEFAULT expr]
[, column datatype]...);
 Use the ALTER TABLE statement to:
 Add a new column
 Modify an existing column
 Define a default value for the new
column
6 September 2019 Sikandar 62
Adding a Column
DEPT30
EMPNO ENAME ANNSAL HIREDATE
------ ---------- --------
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
“…add a
new
column
into
DEPT30
table…”
DEPT30
EMPNO ENAME ANNSAL HIREDATE
------ ---------- --------
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
JOB
JOB
New column
6 September 2019 Sikandar 63
Adding a Column
EMPNO ENAME ANNSAL HIREDATE JOB
--------- ---------- --------- --------- ----
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
6 rows selected.
SQL> ALTER TABLE dept30
2 ADD (job VARCHAR2(9));
Table altered.
• The new column becomes the last column.
 You use the ADD clause to add
columns.
6 September 2019 Sikandar 64
Modifying a Column
SQL> ALTER TABLE dept30
2 MODIFY (ename VARCHAR2(15));
Table altered.
 You can change a column’s datatype, size,
and default value.
 A change to the default value affects only
subsequent insertions to the table.
6 September 2019 Sikandar 65
Dropping a Column
SQL> ALTER TABLE dept30
2 DROP COLUMN job ;
Table altered.
You use the DROP COLUMN clause drop
columns you no longer need from the
table.
6 September 2019 Sikandar 66
SET UNUSED Option
ALTER TABLE table
(column);
ALTER TABLE table
COLUMN column;
OR
ALTER TABLE table
DROP UNUSED COLUMNS;
SET UNUSED
SET UNUSED
 You use the SET UNUSED option to mark one
or more columns as unused.
 You use the DROP UNUSED COLUMNS option
to remove the columns that are marked as
UNUSED.
6 September 2019 Sikandar 67
Dropping a Table
SQL> DROP TABLE dept30;
Table dropped.
 All data and structure in the table is
deleted.
 Any pending transactions are committed.
 All indexes are dropped.
 You cannot roll back this statement.
6 September 2019 Sikandar 68
Changing the Name of an
Object
SQL> RENAME dept TO department;
Table renamed.
 To change the name of a table, view,
sequence, or synonym, you execute the
RENAME statement.
 You must be the owner of the object.
6 September 2019 Sikandar 69
Truncating a Table
SQL> TRUNCATE TABLE department;
Table truncated.
 The TRUNCATE TABLE statement:
 Removes all rows from a table
 Releases the storage space used by that
table
 You cannot roll back row removal when
using TRUNCATE.
 Alternatively, you can remove rows by
using the DELETE statement.
6 September 2019 Sikandar 70
Adding Comments to a Table
SQL> COMMENT ON TABLE emp
2 IS 'Employee Information';
Comment created.
 You can add comments to a table or
column by using the COMMENT statement.
 Comments can be viewed through the
data dictionary views.
 ALL_COL_COMMENTS
 USER_COL_COMMENTS
 ALL_TAB_COMMENTS
 USER_TAB_COMMENTS
6 September 2019 Sikandar 71
Summary
Statement Description
CREATE TABLE Creates a table
ALTER TABLE Modifies table structures
DROP TABLE Removes the rows and table structure
RENAME Changes the name of a table, view,
sequence, or synonym
TRUNCATE Removes all rows from a table and
releases the storage space
COMMENT Adds comments to a table or view
6 September 2019 Sikandar 72
End
END OF LESSON 05
(slides adapted from M Ali Shahid’s original slides)

More Related Content

Similar to Lesson05 relational languages sql (10)

Open SQL & Internal Table
Open SQL & Internal TableOpen SQL & Internal Table
Open SQL & Internal Table
 
03 abap3-090715081232-phpapp01-100511101016-phpapp02
03 abap3-090715081232-phpapp01-100511101016-phpapp0203 abap3-090715081232-phpapp01-100511101016-phpapp02
03 abap3-090715081232-phpapp01-100511101016-phpapp02
 
03 abap3-090715081232-phpapp01
03 abap3-090715081232-phpapp0103 abap3-090715081232-phpapp01
03 abap3-090715081232-phpapp01
 
Reading Fixed And Varying Data
Reading Fixed And Varying DataReading Fixed And Varying Data
Reading Fixed And Varying Data
 
Practical Lab Assignment based on Database Management System BCA – II SEMESTER
Practical Lab Assignment based on Database Management System BCA – II SEMESTER Practical Lab Assignment based on Database Management System BCA – II SEMESTER
Practical Lab Assignment based on Database Management System BCA – II SEMESTER
 
Relational Model
Relational ModelRelational Model
Relational Model
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
 
Assignment#04
Assignment#04Assignment#04
Assignment#04
 
uniT 4 (1).pptx
uniT 4 (1).pptxuniT 4 (1).pptx
uniT 4 (1).pptx
 
Relational Algebra1.pptx
Relational Algebra1.pptxRelational Algebra1.pptx
Relational Algebra1.pptx
 

More from Muhammad Sikandar Mustafa

More from Muhammad Sikandar Mustafa (19)

What is organizational behavior
What is organizational behaviorWhat is organizational behavior
What is organizational behavior
 
11. estimation-1
11. estimation-111. estimation-1
11. estimation-1
 
9. risk-management
9. risk-management9. risk-management
9. risk-management
 
8. project-management
8. project-management8. project-management
8. project-management
 
7. requirement-engineering
7. requirement-engineering7. requirement-engineering
7. requirement-engineering
 
6. software requirements
6. software requirements6. software requirements
6. software requirements
 
software process
software process software process
software process
 
software myths
software mythssoftware myths
software myths
 
software characteristics
software characteristicssoftware characteristics
software characteristics
 
overview introduction to Software Engineering
overview introduction to Software Engineeringoverview introduction to Software Engineering
overview introduction to Software Engineering
 
5. software process model
5. software process model5. software process model
5. software process model
 
Lesson02 database system architecture
Lesson02 database system architectureLesson02 database system architecture
Lesson02 database system architecture
 
Lesson01 Database introduction
Lesson01 Database introductionLesson01 Database introduction
Lesson01 Database introduction
 
Lesson00 intro to databases
Lesson00 intro to databasesLesson00 intro to databases
Lesson00 intro to databases
 
Lesson10 Database security
Lesson10 Database security Lesson10 Database security
Lesson10 Database security
 
Lesson08 tm recovery
Lesson08 tm recoveryLesson08 tm recovery
Lesson08 tm recovery
 
Lesson07 e r modelling
Lesson07 e r modellingLesson07 e r modelling
Lesson07 e r modelling
 
Lesson06 database design
Lesson06 database designLesson06 database design
Lesson06 database design
 
Advanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptAdvanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter ppt
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Lesson05 relational languages sql

  • 1. 6 September 2019 Sikandar 1 Lesson 05 Relational Languages
  • 2. 6 September 2019 Sikandar 2 Relational Languages  Commercial DB systems require more “User Friendly” languages.  Query languages (User makes requests to the DB to obtain info.  These languages should preserve fundamental constructs and concepts  Ones we saw in Relational Algebra.  Examples  SQL (Structured Query Language)  QBE (Query By Example)
  • 3. 6 September 2019 Sikandar 3 Relational Languages  SQL  MS Access SQL version  Oracle SQL version  DB2 SQL version  Etc  Very Minor Differences between all the implementations.
  • 4. 6 September 2019 Sikandar 4 SQL  SQL consists of 2 key Parts  Data Definition Language (DDL)  The commands for defining , deleting, and modifying relations schemas or structure , we can change the structure of the table insert columns etc.  Data Manipulation Language (DML)  This is further divided into two parts  Commands to retrieve information called (Query Part)  The commands to insert , delete, and update tuples called (Modification Part)
  • 5. 6 September 2019 Sikandar 5 SQL DDL used to create the table P# PNAME COLOR WEIGHT CITY P1 Nut Red 12 London P2 Bolt Green 17 Paris P3 Screw Blue 17 Rome P4 Screw Red 14 London P5 Cam Blue 12 Paris P6 Cog Red 19 London DML used to fill the table with tuples etc  The languages Used to extract info or retrieve info are called “Querying Languages”
  • 6. 6 September 2019 Sikandar 6 DML  Query Part (of DML)  Basic Structure (3 clauses)  Select  From  Where  Select:  Correspond to the project operation of relational algebra.  Lists the attributes desired in the result of the query.
  • 7. 6 September 2019 Sikandar 7 DML  From:  Corresponds to the Cartesian product operation in relational algebra  Lists the relations to be scanned in the evaluation process  Where:  Corresponds to the selection conditions  Involves attributes of the relations in the from clause.  Typical Format: select A1, A2, A3……..An (attribute names) From r1,r2,r3………… rn (Relation names) Where P (conditions)
  • 8. 6 September 2019 Sikandar 8 DML  Typical Format: select A1, A2, A3……..An (attribute names) From r1,r2,r3………… rn (Relation names) Where P (conditions)  Similar expression can be written in relational algebra  ( ( r1,r2,r3………… rn ) where P ) [A1, A2, A3……..An]  If where is omitted the selection condition is true for all tuples, so we only use 2 clauses Select s#, city From suppliers;
  • 9. 6 September 2019 Sikandar 9 DML examples  If we want the whole table Select * From suppliers  All of the info suppliers located in London Select * From suppliers Where city = ‘London’
  • 10. 6 September 2019 Sikandar 10 Operators for where clause  Operators for where clause:  Logical operators  AND, OR, NOT etc.  Comparison operators  < , > , <> , >= , <= etc  Arithmetic operators  + , - , / , *  Between (or NOT between)  A type of comparison operator.
  • 11. 6 September 2019 Sikandar 11 Operators for where clause example 1 Select s# From supplier Where (status>= 0) AND (status <= 30); example 2 select s# From supplier where (status between 10 and 30) example 3 select s# From supplier where (status not between 10 and 30)
  • 12. 6 September 2019 Sikandar 12 String matching operators  Oracle gives 2 special characters (wild characters)  Percent(%) matches any sub string  Under score (_) matches any character  For Access  * matches any sub string  ? matches any character
  • 13. 6 September 2019 Sikandar 13 String matching operators examples  “ABC%”  Matches any string beginning with ABC.  “%ABC%”  Matches any string containing ABC as a sub string.  ‘_ _ _’  Matches any string with exactly 3 characters.  ‘_ _ %”  Matches any string matching at least 2 character long.
  • 14. 6 September 2019 Sikandar 14 String matching operators  Patterns are expressed using “LIKE” comparison operator.  Example  Select SNAME  From supplier  Where city LIKE ‘%York%’ ;  Example  Select city  From supplier  Where SNAME LIKE ‘T%’ ; To Use wild cards we must use LIKE operator
  • 15. 6 September 2019 Sikandar 15 Join  No direct representation of natural join in SQL.  SQL use Theta join.  Example  A list of parts number supplied by TOM Select P# From suppliers, shipment Where (supplier.S# = shipment.S#)  System creates a Cartesian product of the 2 tables.
  • 16. 6 September 2019 Sikandar 16 Handling Duplicate Tuples  It is very tough to check duplicate tuples by default.  there can be duplicate tuples due to the result of a query.  SQL allows duplicates by default  Duplicate elimination is very costly.  Also we might require an idea or number of tuples recovered due to some query.  To force elimination we use DISTINCT after select clause.
  • 17. 6 September 2019 Sikandar 17 Distinct  Example  A list of cities for suppliers. select city from suppliers; //we get a lot of duplicate cities select distinct city from suppliers; // all duplicates are eliminated.
  • 18. 6 September 2019 Sikandar 18 Set Operators (  ,  , )  UNION:  Eliminates duplicates by default, if we want to keep duplicates , we use : UNION ALL.  Example ( Select SNAME From supplier Where (status > 30) ) UNION ( Select SNAME From supplier Where city = ‘London’)
  • 19. 6 September 2019 Sikandar 19 UNION  Instead of the previous code we can also use Select SNAME From supplier Where (status > 30 ) OR (city = ‘London’)  If table names are different then we use UNION  if we want to keep duplicates we use UNION ALL.
  • 20. 6 September 2019 Sikandar 20 Intersection and Minus  Both intersection and Minus are NOT included in ANSI standards , majority of SQL vendors do not support these two.  Some times even UNION is not supported
  • 21. 6 September 2019 Sikandar 21 Additional Operators  IN and NOT IN  Operator tests for set membership where the set is a collection of values produced by the select clause in a sub expression (“sub select”).  E.g  Get S# for suppliers who supplied ‘P2’ AND are located in London. Select S# From shipment Where p# = ‘P2’ and S# IN ( select S# from suppliers where (city = ‘London’) )
  • 22. 6 September 2019 Sikandar 22 IN and NOT IN Select S# From shipment Where p# = ‘P2’ and S# IN ( select S# from suppliers where (city = ‘London’) )  First check if P# for s# = P2  If passes then  Check S# is in London or not.  OR Select S# From shipment Where p# = ‘P2’ and S# IN ( ‘S1’ , ‘S2 , ‘S5’ )  We can also use NOT IN
  • 23. 6 September 2019 Sikandar 23 ANY  > ANY  < ANY  <= ANY  >= ANY  <> ANY  This operator is called “set comparison operator”  Example  Find SNAME where all suppliers who had greater status then some supplier located in ‘London’
  • 24. 6 September 2019 Sikandar 24 ANY Select SNAME From supplier Where status > ANY ( select status from supplier where city = ‘London’ )
  • 25. 6 September 2019 Sikandar 25 ALL  > ALL  < ALL etc Select SNAME From supplier Where status > ALL (select status from supplier where ( city = ‘London’ )
  • 26. 6 September 2019 Sikandar 26 Tuple Variable  SQL uses the notion of tuple variables  A tuple variable is defined in the FROM clause by placing it after the name of the relation separated by space.  Tuple variables are most useful for comparing 2 tuples in the same relation.
  • 27. 6 September 2019 Sikandar 27 Tuple Variable  Example find all customers who have a deposit account at some branch at which Tom has an account. Select copy2.customer From deposit copy1 , deposit copy2 Where (copy1.customer = ‘Tom’ AND copy1.branchName = copy2.branchName)  This makes 2 copies , makes an anchor and then compare the 2 tuples
  • 28. 6 September 2019 Sikandar 28 Tuple Variable  Example get supplier’s name SNAME for suppliers who are located in the same city as Tom. Select B.SNAME From supplier A, supplier B Where A.SNAME = ‘Tom’ AND (A.city = B.city)
  • 29. 6 September 2019 Sikandar 29 Tuple Variable  Example Get all pairs of SNAME such the two suppliers concerned are located in the same city. Select X.SNAME , Y.SNAME From supplier X , supplier Y Where X.city = Y.city; Now we might get some redundant information Tom Tom Tom Bob Bob Tom Etc, now how to eliminate duplicates ?
  • 30. 6 September 2019 Sikandar 30 Tuple Variable Select X.SNAME , Y.SNAME From supplier X , supplier Y Where ( X.city = Y.city) AND (X.SNAME > Y.SNAME) Now we might get Tom Tom Tom Bob Bob Tom
  • 31. 6 September 2019 Sikandar 31 Extra Clauses And Features  ORDER BY:  Used for ordering the display of tuples  Order of statements is as follows:  Select  From  Where  Order by
  • 32. 6 September 2019 Sikandar 32 ORDER BY Example: select * from suppliers where status >= 10 order by status S# SNAME STATUS CITY S1 Smith 20 London S2 Jones 10 Paris S3 Blake 30 Paris S4 Clark 20 London S5 Adams 30 Athens Supplier S (original table) S# SNAME STATUS CITY S2 Jones 10 Paris S4 Clark 20 London S1 Smith 20 London S3 Blake 30 Paris S5 Adams 30 Athens Query result
  • 33. 6 September 2019 Sikandar 33 ORDER BY  Default Order of order by is ascending.  If we use  Order by column_name desc  We get a descending order of the tuples according to column named column_name Select * From shipment Order by s# , P# desc
  • 34. 6 September 2019 Sikandar 34 ORDER BY Select account , customer , balance From deposit Order by 3 , 1 , 2
  • 35. 6 September 2019 Sikandar 35 Computing Functions  Computing functions cannot be nested, I.e min(max())  Examples of computing functions are  Avg  Sum  Count  Max  Min etc
  • 36. 6 September 2019 Sikandar 36 Computing Functions  Examples Select avg(balance) From deposit; Select avg(qty) From shipment; Select avg(qty) From shipment Where S#=S1
  • 37. 6 September 2019 Sikandar 37 Computing Functions  Examples count the number of tuples in shipment select count(*) from shipment; how many suppliers have made shipment select count(distinct S#) from shipment;
  • 38. 6 September 2019 Sikandar 38 Modify Part Of DML  1) Deletion  Delete whole tuple(s)  <format> Delete from table_name Where condition e.g. Delete all of shipments made by S2 delete from shipment where S# = ‘S2’
  • 39. 6 September 2019 Sikandar 39 Deletion  E.g Delete from suppliers Where city = ‘London’  E.g.  Delete all deposit accounts at branches located in Chicago  Deposit(branch_name, Account, customer, balance)  Branches(branch_name, asserts , city) Delete from deposit Where branch_name IN ( select branch_name from branches Where city = ‘Chicago’ ; )
  • 40. 6 September 2019 Sikandar 40 Data Manipulation Language  A DML statement is executed when you:  Add new rows to a table  Modify existing rows in a table  Remove existing rows from a table  A transaction consists of a collection of DML statements that form a logical unit of work.
  • 41. 6 September 2019 Sikandar 41 Adding a New Row to a Table DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON New row 50 DEVELOPMENT DETROIT DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON “…insert a new row into DEPT table…” 50 DEVELOPMENT DETROIT
  • 42. 6 September 2019 Sikandar 42 The INSERT Statement Add new rows to a table by using the INSERT statement. Only one row is inserted at a time with this syntax. INSERT INTO table [(column [, column...])] VALUES (value [, value...]);
  • 43. 6 September 2019 Sikandar 43 Inserting New Rows SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'DEVELOPMENT', 'DETROIT'); 1 row created.  Insert a new row containing values for each column.  List values in the default order of the columns in the table.  Optionally list the columns in the INSERT clause.  Enclose character and date values within single quotation marks.
  • 44. 6 September 2019 Sikandar 44 Null Values  A Null value is either unknown or not applicable.  NULL is not equal to “” , or FI, or empty string  E.g  Insert into deposit  Values(‘NEIU’ , 1006 , NULL , 1200)  OR  Values(‘NEIU’ , 1006 , , 1200)
  • 45. 6 September 2019 Sikandar 45 Nulls  Problems caused by NULL values  All comparison operations involving NULL are false.  They simply wont be selected.  Avoid using NULLs. Select * From shipment Where qty < 200;  So NULL rows wont be selected.
  • 46. 6 September 2019 Sikandar 46 DDL (Data Defination Language)  To specify or modify schema definations  To create tables  To Update tables
  • 47. 6 September 2019 Sikandar 47 Creating and Managing Tables
  • 48. 6 September 2019 Sikandar 48 Objectives  After completing this lesson, you should be able to do the following:  Describe the main database objects  Create tables  Describe the datatypes that can be used when specifying column definition  Alter table definitions  Drop, rename, and truncate tables
  • 49. 6 September 2019 Sikandar 49 Database Objects Object Description Table Basic unit of storage; composed of rows and columns View Logically represents subsets of data from one or more tables Sequence Generates primary key values Index Improves the performance of some queries Synonym Gives alternative names to objects
  • 50. 6 September 2019 Sikandar 50 Naming Conventions Must begin with a letter Can be 1–30 characters long Must contain only A–Z, a–z, 0–9, _, $, and # Must not duplicate the name of another object owned by the same user Must not be an Oracle Server reserved word
  • 51. 6 September 2019 Sikandar 51 The CREATE TABLE Statement CREATE [GLOBAL TEMPORARY] TABLE [schema.]table (column datatype [DEFAULT expr][, ...]);  You must have :  CREATE TABLE privilege  A storage area  You specify:  Table name  Column name, column datatype, and column size
  • 52. 6 September 2019 Sikandar 52 Referencing Another User’s Tables  Tables belonging to other users are not in the user’s schema.  You should use the owner’s name as a prefix to the table.
  • 53. 6 September 2019 Sikandar 53 The DEFAULT Option … hiredate DATE DEFAULT SYSDATE, …  Specify a default value for a column during an insert. • Legal values are literal value, expression, or SQL function. • Illegal values are another column’s name or pseudocolumn. • The default datatype must match the column datatype.
  • 54. 6 September 2019 Sikandar 54 Creating Tables SQL> CREATE TABLE dept 2 (deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13)); Table created. • Confirm table creation. SQL> DESCRIBE dept Name Null? Type --------------------------- -------- --------- DEPTNO NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13)  Create the table.
  • 55. 6 September 2019 Sikandar 55 Tables in the Oracle Database  User Tables  Collection of tables created and maintained by the user  Contain user information  Data Dictionary  Collection of tables created and maintained by the Oracle server  Contain database information
  • 56. 6 September 2019 Sikandar 56 Querying the Data Dictionary • View distinct object types owned by the user. • View tables, views, synonyms, and sequences owned by the user. SQL> SELECT * 2 FROM user_tables; SQL> SELECT DISTINCT object_type 2 FROM user_objects; SQL> SELECT * 2 FROM user_catalog; • Describe tables owned by the user.
  • 57. 6 September 2019 Sikandar 57 Datatypes Datatype Description VARCHAR2(size) Variable-length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable-length numeric data DATE Date and time values LONG Variable-length character data up to 2 gigabytes CLOB Single-byte character data up to 4 gigabytes RAW and LONG RAW Raw binary data BLOB Binary data up to 4 gigabytes BFILE Binary data stored in an external file; up to 4 gigabytes
  • 58. 6 September 2019 Sikandar 59 Creating a Table by Using a Subquery CREATE TABLE table [(column, column...)] AS subquery;  Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option.  Match the number of specified columns to the number of subquery columns.  Define columns with column names and default values.
  • 59. 6 September 2019 Sikandar 60 SQL> CREATE TABLE dept30 2 AS 3 SELECT empno, ename, sal*12 ANNSAL, hiredate 4 FROM emp 5 WHERE deptno = 30; Table created. Creating a Table by Using a Subquery Name Null? Type ---------------------------- -------- ----- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) ANNSAL NUMBER HIREDATE DATE SQL> DESCRIBE dept30
  • 60. 6 September 2019 Sikandar 61 The ALTER TABLE Statement ALTER TABLE table ADD (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype]...);  Use the ALTER TABLE statement to:  Add a new column  Modify an existing column  Define a default value for the new column
  • 61. 6 September 2019 Sikandar 62 Adding a Column DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ---------- -------- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... “…add a new column into DEPT30 table…” DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ---------- -------- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... JOB JOB New column
  • 62. 6 September 2019 Sikandar 63 Adding a Column EMPNO ENAME ANNSAL HIREDATE JOB --------- ---------- --------- --------- ---- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81 ... 6 rows selected. SQL> ALTER TABLE dept30 2 ADD (job VARCHAR2(9)); Table altered. • The new column becomes the last column.  You use the ADD clause to add columns.
  • 63. 6 September 2019 Sikandar 64 Modifying a Column SQL> ALTER TABLE dept30 2 MODIFY (ename VARCHAR2(15)); Table altered.  You can change a column’s datatype, size, and default value.  A change to the default value affects only subsequent insertions to the table.
  • 64. 6 September 2019 Sikandar 65 Dropping a Column SQL> ALTER TABLE dept30 2 DROP COLUMN job ; Table altered. You use the DROP COLUMN clause drop columns you no longer need from the table.
  • 65. 6 September 2019 Sikandar 66 SET UNUSED Option ALTER TABLE table (column); ALTER TABLE table COLUMN column; OR ALTER TABLE table DROP UNUSED COLUMNS; SET UNUSED SET UNUSED  You use the SET UNUSED option to mark one or more columns as unused.  You use the DROP UNUSED COLUMNS option to remove the columns that are marked as UNUSED.
  • 66. 6 September 2019 Sikandar 67 Dropping a Table SQL> DROP TABLE dept30; Table dropped.  All data and structure in the table is deleted.  Any pending transactions are committed.  All indexes are dropped.  You cannot roll back this statement.
  • 67. 6 September 2019 Sikandar 68 Changing the Name of an Object SQL> RENAME dept TO department; Table renamed.  To change the name of a table, view, sequence, or synonym, you execute the RENAME statement.  You must be the owner of the object.
  • 68. 6 September 2019 Sikandar 69 Truncating a Table SQL> TRUNCATE TABLE department; Table truncated.  The TRUNCATE TABLE statement:  Removes all rows from a table  Releases the storage space used by that table  You cannot roll back row removal when using TRUNCATE.  Alternatively, you can remove rows by using the DELETE statement.
  • 69. 6 September 2019 Sikandar 70 Adding Comments to a Table SQL> COMMENT ON TABLE emp 2 IS 'Employee Information'; Comment created.  You can add comments to a table or column by using the COMMENT statement.  Comments can be viewed through the data dictionary views.  ALL_COL_COMMENTS  USER_COL_COMMENTS  ALL_TAB_COMMENTS  USER_TAB_COMMENTS
  • 70. 6 September 2019 Sikandar 71 Summary Statement Description CREATE TABLE Creates a table ALTER TABLE Modifies table structures DROP TABLE Removes the rows and table structure RENAME Changes the name of a table, view, sequence, or synonym TRUNCATE Removes all rows from a table and releases the storage space COMMENT Adds comments to a table or view
  • 71. 6 September 2019 Sikandar 72 End END OF LESSON 05 (slides adapted from M Ali Shahid’s original slides)