Sample Copy. Not For Distribution.
i
Beginning with SQL
Sample Copy. Not For Distribution.
ii
Publishing-in-support-of,
EDUCREATION PUBLISHING
RZ 94, Sector - 6, Dwarka, New Delhi - 110075 Shubham Vihar, Mangla, Bilaspur, Chhattisgarh - 495001
Website: www.educreation.in
________________________________________________________________
© Copyright, Authors
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted, in any form by any means, electronic, mechanical, magnetic, optical, chemical, manual, photocopying, recording or otherwise, without the prior written consent of its writer.
ISBN: 978-1-61813-693-0
Price: 280.00
The opinions/ contents expressed in this book are solely of the authors and do not represent the opinions/ standings/ thoughts of Educreation or the Editors . The book is released by using the services of self-publishing house.
Printed in India
Sample Copy. Not For Distribution.
iii
Beginning
with SQL
A Simplified Approach
Dr. Parteek Bhatia
Associate Professor
Department of Computer Science and Engineering
Thapar University, Patiala, India
EDUCREATION PUBLISHING (Since 2011)
www.educreation.in
Sample Copy. Not For Distribution.
iv
Sample Copy. Not For Distribution.
v
Preface
It is by now a proven fact that automation and data applications bring about transparency in all
spheres of life. There is certainly a growing demand for database experts in the country. This book
is intended to fill this gap. This book on SQL has been specially designed to better equip the
learners for their University examination and placement interviews. This book is aimed at
beginners, but it will give you enough information to get mastery on the subject.
Most software written today relies on relational databases such as
Oracle/MySQL/DB2/SQL Server etc. In this book, you'll learn the SQL
language using Oracle, i.e., the most widely used Database Software in the
world.
This book covers the basics of database fundamentals, non procedural nature
of SQL, Creation of tables, performing insert, update, delete and retrieve
operations on tables, joining of tables, grouping of data, inbuilt functions, sub
queries, database objects like view, sequence and indexes. These concepts are
covered through lot of examples to make the learning fun and exciting.
The main strength of the book is explanation with the practical examples so that
learners can grasp the contents easily. Each chapter contains Brain Storming
Session on number of practical problems and Hands-On Session to promote
learning by doing approach. This book provides a good number of multiple
choice questions for preparation of placements, quizzes and competitive exams.
Your suggestions for further improvement of the book are very valuable and kindly mail your
suggestions at [email protected].
I hope that you enjoy learning from this book as much as I enjoyed writing it.
Dr. Parteek Bhatia
2017
Sample Copy. Not For Distribution.
vi
Acknowledgements
Beginning with SQL is an evolving project, which could not have been possible
without the contribution and support of scores of people.
I would like to express here, my gratitude to the students of Thapar University,
Patiala; DAV College, Amritsar and from other institutes to whom I got the
opportunity to interact during different sessions. They provided the much
needed motivation without which this book would have been impossible.
I am deeply grateful for the guidance and support provided by my mentors Mr.
M.L. Aeri, Mr. O.P. Bhardwaj, Dr. R.K. Sharma, Dr. Seema Bawa, Dr.
Maninder Singh and my friends Dr. Amandeep Gupta and Dr. Deepak Garg
during writing of this book.
I owe much to the Department of Computer Science and Engineering,
Thapar University for providing all the resources that helped me to attain the
requisite level of excellence to complete this book.
My family members stood by me firm as rocks all through the period when
the book was being researched and written. I acknowledge here the debt of
gratitude I owe my parents, Mr. Ved Kumar; Mrs. Jagdish Bhatia and Mr Dalip
Singh and Mrs Joginder Kaur for their constant encouragement. And lastly I
would like to thank my wife Dr. Sanmeet Kaur, and sons Rahat and Rishan for
their forbearance and the patience they displayed for such an extended period of
time, without which I would never have been able to complete the task. I would
like to acknowledge contribution of my son Rahat in preparing the index of the
book.
Sample Copy. Not For Distribution.
vii
About the Author
Dr. Parteek Bhatia is Associate Professor in the
Department of Computer Science and Engineering at
Thapar University, Patiala. He has more than eighteen
years of academic experience, including six years at
D.A.V College Amritsar. He has earned his B.Tech
from SLIET and MS from BITS Pilani. He has
completed his Ph.D on "UNL Based Machine
Translation System for Punjabi Language" from Thapar
University. He has published more than 75 research
papers and articles in Journals, Conferences and
Magazines of repute. His research work with UNDL
foundation, Geneva, Switzerland involved participation
in Advanced UNL School at Alexandria, EGYPT in
2012 and at Geneva, Switzerland in 2013 and 2014. He
is a winner of Gold Medal at International competition UNL Olympiad II, UNL
Olympiad III and UNL Olympiad IV conducted by UNDL Foundation Geneva
in year 2013 and 2014. He has authored six books including Simplified
Approach to DBMS, Simplified Approach to Visual Basic and Simplified
Approach to Oracle. He has successfully completed research Project on
Development of Indradhanush: An Integrated WordNet for Bengali, Gujarati,
Kashmiri, Konkani, Oriya, Punjabi and Urdu Sponsored By Department of
Information Technology, Ministry of Communication and Information
Technology, Govt. of India. He is acting as Principle Investigator for DST
sponsored research project on “Automatic generation of Sign Language from
Hindi Text for Communication and Education of Hearing Impaired People”. He
is working as working as Co-PI for development of Mini MOOCS under a
research project funded by Royal Academy of Engineers (UK). His research
interests are NLP, Machine Learning and Human Computer Interaction.
sites.google.com/site/parteekbhatia
Sample Copy. Not For Distribution.
viii
Dedicated to
My Parents Mr. Ved Kumar & Mrs. Jagdish Bhatia
Supportive Wife Dr. Sanmeet Kaur
Loving Sons Rahat & Rishan
By Parteek Bhatia…
Sample Copy. Not For Distribution.
ix
Contents
CHAPTER 1: BEGINNING WITH SQL 1-7
1.1 Introduction to Structured Query Language
1.2 SQL Fundamentals
1.2.1 Data Definition Language (DDL) statements
1.2.2 Data Manipulation Language (DML) statements
1.2.3 Data Control Language (DCL)
1.2.4 Transaction Control Language (TCL) statements
1.3 Data types of SQL
CHAPTER 2: INVOKING SQL*PLUS 8-15
2.1 SQL*PLUS Interface
CHAPTER 3: PERFORMING BASIC OPERATIONS OF
DATABASE WITH SQL 16-26
3.1Beginning with Performing Basics operations of database
CHAPTER 4: BASIC SELECT STATEMENT 27-58
4.1 Databases used in examples
4.2 SELECT Statement
4.3 Use of Wildcard(*) character
4.4 Elimination of Duplication with DISTINCT Clause
4.5 The Oracle table „DUAL‟
4.6 Limiting Rows
4.7 Special Operators
4.8 Working with NULL Values
4.9 ORDER BY Clause
4.10 Changing Column Headings with Column Aliases
Sample Copy. Not For Distribution.
x
4.11 Column Concatenation
4.12 Pattern matching
4.13 Using Set Operators
4.13.1 Union operator
4.13.2 Union All Operator
4.13.3 Intersect operator
4.13.4 Minus operator
4.14 Oracle‟s Pseudo columns
4.14.1 CURRVAL and NEXTVAL
4.14.2 ROWID
4.14.3 Rownum
4.15 Accepting Values at Runtime
CHAPTER 5: INBUILT FUNCTIONS 59-84
5.1 Functions in SQL*PLUS
5.1.1 Single Row Functions
5.1.2 Multi row or Group Functions in SQL
CHAPTER 6: GROUPING OF DATA 85-95
6.1 Grouping Data with GROUP BY
6.2 Grouping by more than one column
6.3 Restricting Group Results with HAVING clause
CHAPTER 7: JOINING OF TABLES 96-111
7.1 Joining of tables for multiple table Queries
7.2 Types of Joins
Sample Copy. Not For Distribution.
xi
7.2.1 Cartesian product
7.2.2 Inner Join
7.2.2.1 Equality Joins
7.2.2.2 Non-Equality Join
7.2.3 Outer Joins
7.2.3.1 Left/Right-Outer join
7.2.4 Self-Join
CHAPTER 8: SUB QUERIES 112-129
8.1 Using a Sub-query to solve a problem
8.2 Types of Subquries
8.2.1 Single-Row Sub queries
8.2.2 Multiple-Row Sub-queries
8.2.3 Multiple-column Subquries
8.3 Correlated Sub-queries
8.4 Using special operators in Sub-queries
8.4.1 EXISTS Operator
8.4.2 ANY Operator
8.4.3 ALL Operator
CHAPTER 9: MANAGING TABLES 130-156
9.1 Introduction to tables
9.2 Structure of table: Design tables before creating them
9.3 Table creation rules
9.4 Create Table Statement
9.5 Creating table from an existing Table9.6 Role of Constraints to
achieve data integrity
9.6.1 Column Constraints
Sample Copy. Not For Distribution.
xii
9.6.2 Table Constraints
9.7 Types of Constraints
9.7.1 NOT NULL constraint
9.7.2 Unique constraint
9.7.3 Primary key constraint
9.7.4 Check constraint
9.7.5 Default constraint
9.7.6 Foreign key constraint
9.8 Creating a Table with rows from another table
9.9 Required Permissions to Create a Table
9.10 To display information about Table
9.11 The user_constraints table
9.12 Altering Tables
9.12.1 To ADD new columns
9.12.2 To MODIFY columns
9.12.3 The DROP option
9.12.4 Drop column option
9.13 Removing Tables
9.14 Available tables as Data Dictionary
CHAPTER 10: DATABASE OBJECTS, DCL AND TCL
STATEMENTS 157-177
10.1 Creation of View
10.2 Types of views
10.2.1 Horizontal views
10.2.2 Vertical views
10.2.3 Row/column subset views
Sample Copy. Not For Distribution.
xiii
10.2.4 Grouped views
10.2.5 Joined views
10.3.Data Manipulation in View
10.3.1 Updating a view
10.4 Dropping a View
10.5 Views with CHECK Option
10.6 Advantages of views
10.7 Disadvantages of views
10.8 Sequences: Database Object
10.9 Index: Database Object
10.9.1 Uses of Indexing
10.9.2 Types of Indexes
10.9.3 Creation of Simple Duplicate Index
10.9.4 Creation of Composite Duplicate Index
10.9.5 Creation of Simple Unique Index
10.9.6 Creation of Composite Unique Index
10.9.7 Dropping of existing Indexes
10.9.8 Problem Caused by too many Indexes
10.10 Index Guidelines
10.11 Oracle Index schemes
10.12 TRANSACTION CONTROL LANGUAGE
STATEMENTS
10.13 DATA CONTROL LANGUAGE STATEMENTS
10.13.1 GRANT Command
10.13.2 REVOKE Command
10.14 Creation and Management of User Accounts
Sample Copy. Not For Distribution.
xiv
10.14.1 Steps to create user
10.14.2 Altering User Account
10.14.3 Deleting User Account
10.15 Oracle Tree Walking
Index 178
Sample Copy. Not For Distribution.
Beginning with SQL ________________________________________________________________________
1
Chapter Objectives In this chapter you will learn
Non procedural capabilities of SQL
Classification of SQL statements
Data types of Oracle _________________________________________________________________
1.1 Introduction to Structured Query Language
Structured Query Language usually refereed as SQL, it is a non procedural
language, where a user need not write a program to perform his desired database
task (insert, update, delete and retrieve) but he has to provide his request for the
task in a structured manner to the system and system takes care of his request,
i.e., it process its request and provide the desired result without writing a single
line of code.
In other words, user has to provide the information to computer “what is
require to be perform”, but need not to provide the details about “how to
perform the task”. User does not write the procedure/algorithm/program to get
the result simply he has to provide his request in a structured manner, that‟s why
it is called as Structured Query Language.
While in procedural languages like C, user has to write the
procedure/algorithm/program for task he wishes to execute on the computer.
Even to find the sum of two numbers user has to write the program while in non-
procedural language like SQL user need not to write the program.
Thus, due to non procedural nature of SQL it make it very simple and easy to
use. This is the major reason for the popularity of SQL because it is simple, easy
to use and without writing the programs user is able to perform all database
tasks, i.e., insert, update, delete and retrieve without writing the programs.
01 BEGINNING WITH SQL
Sample Copy. Not For Distribution.
Parteek Bhatia ________________________________________________________________________
2
But, this non-procedural nature of SQL has a limitation, it has limited
capabilities, because in non-procedural language we cannot make the use of if
statement, Looping statement etc. and sometimes it is difficult to implement
whole business logic with SQL. To add procedural capabilities to SQL, SQL has
been extended to PL/SQL, i.e., Procedural Language/ Structured Query
Language. PL/SQL has capacities of procedural language, i.e., provision to use
conditional and looping statements etc. with non procedural capabilities of SQL.
In this chapter, we will discuss the basics of SQL while PL/SQL has been
discussed in Chapter 30. In this chapter, SQL statements of most commonly
used database software, i.e., Oracle has been discussed.
1.2 SQL Fundamentals
SQL is a simple and powerful language used to create, access, and manipulate
data and structure in the database. SQL is like plain English, easy to understand
and write. Oracle divides SQL statements into various categories, which are:
Data Definition Language
Data Manipulation Language
Data Control Language.
Transaction Control Language
Embedded SQL statements
1.2.1 Data Definition Language (DDL) statements
DDL statements are used to define, alter, or drop database objects.
The following table gives an overview about usage of DDL statements in
ORACLE:
S.No Need and Usage Example The SQL DDL
statement
1 Create schema objects Creation of table CREATE
2 Alter schema objects Alteration in
structure of table
ALTER
3 Delete schema objects Deletion of whole
table
DROP
4 Rename schema objects Renaming of table RENAME
1.2.2 Data Manipulation Language (DML) statements
Once the tables have been created, the DML statements enable users to query or
manipulate data in existing schemas objects. DML statements are normally the
most frequently used commands. The following table gives an overview about
the usage of DML statements in ORACLE.
Sample Copy. Not For Distribution.
Beginning with SQL ________________________________________________________________________
3
1.2.3 Data Control Language (DCL)
A privilege or right can either be granted to a user with the help of GRANT
statement. The privileges assigned can be SELECT, ALTER, DELETE,
EXECUTE, INSERT, INDEX etc. In addition to granting of privileges, you can
also revoke (taking it back) it by using REVOKE command.
S.No Need and Usage The SQL DCL
statement
1 Grant and take away privileges and roles GRANT
REVOKE
2 Add a comment to the data dictionary COMMENT
1.2.4 Transaction Control Language (TCL) statements
TCL statements manage the change made by DML statements, and group DML
statements into transactions. The following table gives an overview about the
usage of TCL statements in ORACLE.
S.No Need and Usage The SQL TCL
statement
1 Make a transaction‟s changes permanent COMMIT
2 Undo changes in a transaction, either since
the transaction started or since a savepoint
ROLLBACK
3 Set point to which transaction can be rolled
back
SAVEPOINT
4 Establish properties for a transaction SET
TRANSACTION
1.3 Data types of SQL
At this point, it is necessary to discuss the available data types in the Oracle
database. As we know that information in a database is maintained in the form
S.No Need and Usage The SQL DML
statement
1 Remove rows from tables or views DELETE
2 Add new rows of data into table or view INSERT
3 Retrieve data from one or more tables SELECT
4 Change column values in existing rows of a
table or view
UPDATE
Sample Copy. Not For Distribution.
Parteek Bhatia ________________________________________________________________________
4
of tables and each table consists of rows and columns, which stores data, and
therefore this data must have some data type i.e the type of data, which is stored
in a table.
The different data types available in SQL are:
Data types Description
VARCHAR2 Contains variable length text strings of up to 2,000
bytes
CHAR Contains fixed text strings of up to 255 bytes
NUMBER Contains numeric data
DATE Contains date data
RAW Contains binary data of up to 255 bytes
LONG Contains text data of up to 2 gigabytes
LONG RAW Contains binary data of up to 2 gigabytes
ROWID Contains disk location for table rows
BLOB Large binary object
CLOB Large character-based object
NCLOB Large single- or multi byte character-based object
BFILE Large external file
The most commonly used data types are:
char
varchar or varchar2
number
date
long
long raw/ raw
Let us now briefly describe these data types:
Let us now briefly describe these data types:
Char(n) : This data type is used to store character strings of fixed size. The size
of the character string is determined by the numeric value of n. This data type
can hold maximum of 255 characters. When Oracle stores data in a CHAR data
type, it will pad the value stored in the column up to the length of the column as
declared by the table with blanks.
Sample Copy. Not For Distribution.
Beginning with SQL ________________________________________________________________________
5
For example: If data type of address field is mentioned as CHAR(40) and
address information of a particular record complete in 20 characters, then
remaining 20 characters space is padded with blank characters.
Varchar(n)/Varchar2(n) : This data type is used to store variable length
alphanumeric data. It can store maximum of 2000 characters. In case of varchar
data type, Oracle will not store padded blank spaces if the value stored in a
column defined is less than length of the column as declared by the table with
data type VARCHAR2.
For example: If data type of address field is mentioned as VARCHAR(40) and
address information of a particular record complete in 20 characters, then
remaining 20 characters space is not padded with blank characters and memory
space of 20 characters is used for some other purposes and not wasted as
padded with blank characters.
Number (p,s) : This data type is used to store numbers fixed or floating point
.The precision (p) determines the length of the data while (s), the scale,
determines the number of places after the decimal. The NUMBER data type that
is used to store number data can be specified either to store integers or decimals
with the addition of a parenthetical precision indicator.
For example, if you had a column defined to be data type NUMBER(10,3),
the number 546.3832 would be stored as 546.383, because after the decimal
point we can store 3 digits. Let us consider another data type NUMBER (3,2),
the maximum number stored in this data type is 9.99, because it has a precision
as 3 and scale as 2. It means that the length of data is 3 including 2 after the
decimal point leaving only one before decimal point. Thus, it can accommodate
maximum number 9.99, but it cannot store 10, because it has 2 digits before the
decimal point.
What will be maximum number stored in data type NUMBER (7,3)? The
answer is 9999.999. I hope that you got the logic.
If we do not use scale then the default value is zero and if we don‟t use
precision then by default maximum value stored can be of precision up to 38
digits.
Date : This data type stores date values in a special format internal to Oracle. It
offers a great deal of flexibility to users who want to perform date manipulation
operations. There are also numerous functions that handle date operations more
complex than simple arithmetic. Another nice feature of Oracle‟s method for
data storage is that it is inherently millennium compliant. The default format in
which date is stored is DD-MON-YY. If we want to store date in other format
then we have to use the appropriate functions.
Sample Copy. Not For Distribution.
Parteek Bhatia ________________________________________________________________________
6
Long: The developer can declare columns to be of LONG data type, which can
stores up to 2 gigabytes of alphanumeric text data. The values of long data type
cannot be indexed and normal characters functions such as SUBSTR cannot be
applied to long values.
Long Raw/Raw : It is useful to store graphics and sound files when used in
conjunction with LONG to form the LONG RAW data type, which can
accommodate up to 2 gigabytes of data.
Note: A table cannot contain more than one Long column. They cannot be
indexed and no integrity constraints can be applied on them (except for NULL
and NOT NULL constraint).
LOB Type
The LOB (large object) data types BFILE, BLOB, CLOB, and NCLOB allow
storing blocks of unstructured data (such as text, graphic images, video clips,
and sound waveforms) up to four gigabytes in size. And, they allow efficient,
random, piece-wise access to the data.
***
Flashback
______________________________________________________
SQL is a simple and powerful language used to create, access, and manipulate
data and structure in the database. SQL statements into various categories, which
are: Data Definition Language, Data manipulation Language, Transaction
Control Statements and Embedded SQL statements.
DDL statements are used to define, alter, or drop database objects. Once the
tables have been created, the DML statements enable users to query or
manipulate data in existing schemas objects. TCL statements manage the change
made by DML statements, and group DML statements into transactions. The
SQL statements used to incorporate DDL, DML and transaction control
statements within the body of a procedural language program, are known as
Embedded SQL statements. The oracle corporation is the world‟s leading
supplier of software for information management and world‟s second largest
independent software company. Oracle is the top selling multi-user RDBMS.
Most commonly used data types of Oracle are: char, varchar or varchar2,
number, date, long, long raw/ raw.
***
Sample Copy. Not For Distribution.
Beginning with SQL ________________________________________________________________________
7
Review Questions
______________________________________________________
1. What are various categories in which we can divide the SQL
statements?
2. What are different data types of Oracle?
***
Hands on Session
Q1. SQL statements are divided into following categories
(a) DDL & DML (c) TCL
(b) DCL (d) ALL
Q2 Embedded SQL statements include
(a) DEFINE & OPEN (c) EXECUTE
(b) DECLARE (d) ALL
Q3. Oracle Data types include
(a) Varchar2 (c) Long
(b) BLOB (d) ALL
Solution Keys
1 d, 2 d, 3 d
***
Sample Copy. Not For Distribution.
Parteek Bhatia ________________________________________________________________________
8
Chapter Objectives In this chapter you will learn
SQL*PLUS Interface
Invoking SQL*PLUS from command line
Difference between SQL*PLUS and iSQL*PLUS
_________________________________________________________________
2.1 SQL*PLUS Interface
Oracle provides an interactive SQL tool called SQL*PLUS, which allows the
users to enter SQL commands and pass them to oracle Engine for execution.
SQL*PLUS is a character based interactive tool that runs in a GUI environment.
It is loaded on the client machine. This is the first tool to be used by most
programmers when they place their first step into ORACLE world.
Now commonly user, uses interactive SQL*Plus known as iSQL*Plus
through the browser. iSQL*Plus is an interactive interface (i refers to
interactive), to interact with Oracle engine through browser as depicted in figure
02 INVOKING SQL*PLUS
Sample Copy. Not For Distribution.
Beginning with SQL ________________________________________________________________________
9
Figure 2.1: Interaction with Oracle Server through SQL*PLUS and
iSQL*PLUS interface
In this interface user can execute both SQL and PL/SQL statements, that‟s why
it is known as SQL*PLUS (SQL+PL/SQL).
The actions need to be performed by user to invoke iSQL*PLUS has been
shown in figure 2.2.
Sample Copy. Not For Distribution.
Parteek Bhatia ________________________________________________________________________
10
Figure 2.2: Step 1- Selection of Oracle from list of programs
Sample Copy. Not For Distribution.
Beginning with SQL ________________________________________________________________________
11
Get Complete Book At Educreation Store
www.educreation.in
Sample Copy. Not For Distribution.
Sample Copy. Not For Distribution.