SlideShare a Scribd company logo
1 of 124
DBMS (LAB)
SQL/PLSQL
By:-Gourav Kottawar 1
• Introduction of SQL
• DDL, DML, DTL
• Basic Data Types
• Char, varchar/varchar2, long, number,
Fixed & floating point Date, CLOB, BLOB
By:-Gourav Kottawar 2
• What is SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL is an ANSI (American National Standards Institute)
standard
• What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
By:-Gourav Kottawar 3
• SELECT * FROM Persons;
• SQL is not case sensitive, Semicolon after
SQL Statements.
• Some database systems require a semicolon
at the end of each SQL statement.
• Semicolon is the standard way to separate
each SQL statement in database systems
that allow more than one SQL statement to
be executed in the same call to the server.
• We are using MS Access and SQL Server
2000 and we do not have to put a semicolon
after each SQL statement, but some
database programs force you to use it.
By:-Gourav Kottawar 4
• SQL DML and DDL
• SQL can be divided into two parts: The
Data Manipulation Language (DML) and
the Data Definition Language (DDL).
• The query and update commands form the
DML part of SQL:
• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a
database
By:-Gourav Kottawar 5
• The DDL part of SQL permits database
tables to be created or deleted. It also
define indexes (keys), specify links
between tables, and impose constraints
between tables. The most important DDL
statements in SQL are:
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
By:-Gourav Kottawar 6
• A Transaction Control Language (TCL) :
• is a computer language and a subset of SQL,
used to control transactional processing in a
database. A transaction is logical unit of work that
comprises one or more SQL statements, usually a
group of Data Manipulation Language (DML)
statements.
• Examples of TCL commands include:
• COMMIT to apply the transaction by saving the
database changes.
• ROLLBACK to undo all changes of a transaction.
• SAVEPOINT to divide the transaction into smaller
sections. It defines breakpoints for a transaction to
allow partial rollbacks.
By:-Gourav Kottawar 7
DATA TYPES IN SQL
By:-Gourav Kottawar 8
By:-Gourav Kottawar 9
Data
Type
Syntax Explanation (if applicable)
INTEGER INTEGER(p) Integer numerical (no decimal). Precision p
SMALLINT Integer numerical (no decimal). Precision 5
INTEGER
Integer numerical (no decimal). Precision
10
By:-Gourav Kottawar 10
Syntax
float [ ( n ) ]
Is a floating point number data with the following valid
values: - 1.79E + 308 through -2.23E - 308, 0 and 2.23E
-308 through 1.79E + 308. n is the number of bits used to
store the mantissa of the float number in scientific
notation and thus dictates the precision and storage size.
n must be a value from 1 through 53. The default value of
n is 53.
real
Is a floating point number data with the following valid
values: –3.40E + 38 through -1.18E - 38, 0 and 1.18E -
38 through 3.40E + 38. Storage size is 4 bytes. In SQL
Server, the synonym for real is float(24).
nvalue Precision Storage size
1-24 7 digits 4 bytes
25-53 15 digits 8 bytes
By:-Gourav Kottawar 11
Data type Range Storage
float
- 1.79E+308 to -2.23E-
308, 0 and 2.23E-308
to 1.79E+308
Depends on the value
of n
real
- 3.40E + 38 to -1.18E -
38, 0 and 1.18E - 38 to
3.40E + 38
4 Bytes
character char(x)
Where x is the number of
characters to store. This data
type is space padded to fill the
number of characters
specified.
character
varying
varchar2(x)
Where x is the number of
characters to store. This data
type does NOT space pad.
BOOLEAN BOOLEAN
Stores TRUE or FALSE values
date date
Stores year, month, and day
values.
time time
Stores the hour, minute, and
second values.
timestamp timestamp
Stores year, month, day, hour,
minute, and second values.By:-Gourav Kottawar 12
Difference between VARCHAR
and VARCHAR2
1. VARCHAR is going to be replaced by VARCHAR2 in
next version. So, Oracle suggests the use
VARCHAR2 instead of VARCHAR while declaring
datatype.
2. VARCHAR can store up to 2000 bytes of characters
while VARCHAR2 can store up to 4000 bytes of
characters.
3. If we declare datatype as VARCHAR then it will
occupy space for NULL values, In case of VARCHAR2
datatype it will not occupy any space.
By:-Gourav Kottawar 13
• Difference Between Number and Integer
• NUMBER always stores as we entered. Scale is -84 to 127.
But INTEGER rounds to whole number. The scale for
INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It
means, INTEGER is constrained number. The decimal place
will be rounded. But NUMBER is not constrained.
INTEGER(12,2) => 12
INTEGER(12.5) => 13
INTEGER(12.9) => 13
INTEGER(12.4) => 12
NUMBER(12,2) => 12.2
NUMBER(12.5) => 12.5
NUMBER(12.9) => 12.9
NUMBER(12.4) => 12.4By:-Gourav Kottawar 14
• Database Tables
• A database most often contains one or
more tables. Each table is identified by a
name (e.g. "Customers" or "Orders").
Tables contain records (rows) with data.
• Below is an example of a table called
"Persons":
By:-Gourav Kottawar 15
By:-Gourav Kottawar 16
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
The table above contains three records (one for each person)
and five columns (P_Id, LastName, FirstName, Address, and
City).
• The CREATE TABLE Statement
• The CREATE TABLE statement is used to
create a table in a database.
• SQL CREATE TABLE Syntax
• CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
By:-Gourav Kottawar 17
• CREATE TABLE Example
• Now we want to create a table called
"Persons" that contains five columns: P_Id,
LastName, FirstName, Address, and City.
• We use the following CREATE TABLE
statement:
• CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
By:-Gourav Kottawar 18
• The P_Id column is of type int and will hold
a number. The LastName, FirstName,
Address, and City columns are of type
varchar with a maximum length of 255
characters.
• The empty "Persons" table will now look
like this:
• The empty table can be filled with data
with the INSERT INTO statement.
By:-Gourav Kottawar 19
P_Id LastName FirstName Address City
• SQL Constraints
• Constraints are used to limit the type of data that
can go into a table.
• Constraints can be specified when a table is
created (with the CREATE TABLE statement) or
after the table is created (with the ALTER TABLE
statement).
• We will focus on the following constraints:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
By:-Gourav Kottawar 20
• SQL NOT NULL Constraint
• The NOT NULL constraint enforces a column to NOT accept
NULL values.
• The NOT NULL constraint enforces a field to always contain a
value. This means that you cannot insert a new record, or
update a record without adding a value to this field.
• The following SQL enforces the "P_Id" column and the
"LastName" column to not accept NULL values:
• CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
By:-Gourav Kottawar 21
• SQL UNIQUE Constraint
• The UNIQUE constraint uniquely identifies
each record in a database table.
• The UNIQUE and PRIMARY KEY
constraints both provide a guarantee for
uniqueness for a column or set of
columns.
• A PRIMARY KEY constraint automatically
has a UNIQUE constraint defined on it.
• Note that you can have many UNIQUE
constraints per table, but only one
PRIMARY KEY constraint per table.
By:-Gourav Kottawar 22
• SQL UNIQUE Constraint on CREATE TABLE
• The following SQL creates a UNIQUE constraint
on the "P_Id" column when the "Persons" table is
created:
• MySQL:
• CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
By:-Gourav Kottawar 23
• CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
By:-Gourav Kottawar 24
• CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
• To allow naming of a UNIQUE constraint, and for defining a UNIQUE
constraint on multiple columns, use the following SQL syntax:
• MySQL / SQL Server / Oracle / MS Access:
• CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonsId UNIQUE (P_Id,LastName)
)
By:-Gourav Kottawar 25
• SQL UNIQUE Constraint on ALTER TABLE
• To create a UNIQUE constraint on the "P_Id" column
when the table is already created, use the following SQL:
• MySQL / SQL Server / Oracle / MS Access:
• ALTER TABLE Persons
ADD UNIQUE (P_Id)
• To allow naming of a UNIQUE constraint, and for
defining a UNIQUE constraint on multiple columns, use
the following SQL syntax:
• MySQL / SQL Server / Oracle / MS Access:
• ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE
(P_Id,LastName)
By:-Gourav Kottawar 26
• To DROP a UNIQUE Constraint
• To drop a UNIQUE constraint, use the
following SQL:
• SQL Server / Oracle / MS Access:
• ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID
By:-Gourav Kottawar 27
• SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely
identifies each record in a database table.
• Primary keys must contain unique values.
• A primary key column cannot contain
NULL values.
• Each table should have a primary key, and
each table can have only one primary key.
• SQL PRIMARY KEY Constraint on
CREATE TABLE
By:-Gourav Kottawar 28
• The following SQL creates a PRIMARY KEY on the "P_Id"
column when the "Persons" table is created:
• MySQL:
• CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
• SQL Server / Oracle / MS Access:
• CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
) By:-Gourav Kottawar 29
• SQL PRIMARY KEY Constraint on
ALTER TABLE
• To create a PRIMARY KEY constraint on
the "P_Id" column when the table is already
created, use the following SQL:
• MySQL / SQL Server / Oracle / MS
Access:
• ALTER TABLE Persons
ADD PRIMARY KEY (P_Id)
By:-Gourav Kottawar 30
• MySQL / SQL Server / Oracle / MS Access:
• ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID
PRIMARY KEY (P_Id);
• Note: If you use the ALTER TABLE statement to
add a primary key, the primary key column(s)
must already have been declared to not contain
NULL values (when the table was first created).
By:-Gourav Kottawar 31
• To DROP a PRIMARY KEY Constraint
• To drop a PRIMARY KEY constraint, use
the following SQL:
• MySQL:
• ALTER TABLE Persons
DROP PRIMARY KEY
• SQL Server / Oracle / MS Access:
• ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
By:-Gourav Kottawar 32
• The FOREIGN KEY constraint SQL FOREIGN
KEY Constraint
• A FOREIGN KEY in one table points to a PRIMARY KEY
in another table.
• Let's illustrate the foreign key with an example. Look at
the following two tables:
• The "Persons" table:
By:-Gourav Kottawar 33
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
By:-Gourav Kottawar 34
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
PERSONS TABLE
ORDERS TABLE
35
Note that the "P_Id" column in the "Orders" table points to the
"P_Id" column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY
KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in
the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that
would destroy link between tables.
The FOREIGN KEY constraint also prevents that invalid data
is inserted into the foreign key column, because it has to be
one of the values contained in the table it points to.
By:-Gourav Kottawar
• CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES
Persons(P_Id)
)
By:-Gourav Kottawar 36
• CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES
Persons(P_Id)
)
By:-Gourav Kottawar 37
DROP TABLE
• Helps in removing the rows from the table.
• It is a DML command.
• The description (structure) of the table is
removed.
• The existence of the table is removed.
(Table cant be seen from in select * from tab).
Rollback though shows completed but table
view doesn’t come back.
AS IT IS A DML COMMAND ROLLBACK WILL
NOT WORK
By:-Gourav Kottawar 38
• ALTER table tablename
DROP column colname
SQL> alter table emp
2 drop column age;
drop column age
*
ERROR at line 2: ORA-00905: missing
keyword
ALTER-Drop column will work in Oracle 9i
and above version.By:-Gourav Kottawar 39
• ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id);
• ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
By:-Gourav Kottawar 40
SQL> drop table room;
Table dropped.
SQL> desc room; //description is not
available
ERROR:
ORA-04043: object room does not exist
By:-Gourav Kottawar 41
• The INSERT INTO Statement
• The INSERT INTO statement is used to insert a
new row in a table.
• SQL INSERT INTO Syntax:
• It is possible to write the INSERT INTO
statement in two forms.
• The first form doesn't specify the column names
where the data will be inserted, only their values:
• INSERT INTO table_name
VALUES (value1, value2, value3,...)
By:-Gourav Kottawar 42
• INSERT INTO Persons (P_Id, LastName,
FirstName)
VALUES (5, 'Tjessem', 'Jakob')
• The second form specifies both the column
names and the values to be inserted:
• INSERT INTO table_name (column1,
column2, column3,...)
VALUES (value1, value2, value3,...)
By:-Gourav Kottawar 43
• SQL INSERT INTO Example
• We have the following "Persons" table:
By:-Gourav Kottawar 44
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
:
Now we want to insert a new row in the "Persons" table.
We use the following SQL statement
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
• Insert Data Only in Specified Columns
• It is also possible to only add data in specific columns.
• The following SQL statement will add a new row, but
only add data in the "P_Id", "LastName" and the
"FirstName" columns:
• INSERT INTO Persons (P_Id, LastName, FirstName)
VALUES (5, 'Tjessem', 'Jakob')
• The "Persons" table will now look like this:
By:-Gourav Kottawar 45
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob
• The SQL SELECT Statement
• The SELECT statement is used to select data from a
database. The result is stored in a result table, called
the result-set.
• SQL SELECT Syntax
• SELECT column_name(s)
FROM table_name
• SELECT * FROM table_name
And
• ‘*’ Also called as Global Extraction Opearator
• Note: SQL is not case sensitive. SELECT is the same
as select.
• An SQL SELECT Example
• The "Persons" table:
By:-Gourav Kottawar 46
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
By:-Gourav Kottawar 47
• SQL CHECK Constraint on CREATE TABLE
• The following SQL creates a CHECK constraint
on the "P_Id" column when the "Persons" table
is created. The CHECK constraint specifies that
the column "P_Id" must only include integers
greater than 0.
• CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(25) NOT NULL,
FirstName varchar(25),
Address varchar(25),
City varchar(25)
)
By:-Gourav Kottawar 48
• To allow naming of a CHECK constraint,
and for defining a CHECK constraint on
multiple columns, use the following SQL
syntax:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND
City='Sandnes')
)
By:-Gourav Kottawar 49
• SQL CHECK Constraint on ALTER
TABLE
• To create a CHECK constraint on the "P_Id"
column when the table is already created, use
the following SQL:
• ALTER TABLE Persons
ADD CHECK (P_Id>0)
• To allow naming of a CHECK constraint, and for
defining a CHECK constraint on multiple
columns, use the following SQL syntax:
• ALTER TABLE Persons
ADD CONSTRAINT chk_Person CHECK
(P_Id>0 AND City='Sandnes')
By:-Gourav Kottawar 50
• To DROP a CHECK Constraint
• To drop a CHECK constraint, use the
following SQL:
• ALTER TABLE Persons
DROP CONSTRAINT chk_Person;
By:-Gourav Kottawar 51
• The DROP TABLE Statement
• The DROP TABLE statement is used to
delete a table.
DROP TABLE table_name
By:-Gourav Kottawar 52
• SQL SELECT Syntax
• SELECT column_name(s)
FROM table_name
• SELECT * FROM table_name
• And
• ‘*’ Also called as Global Extraction
Opearator
By:-Gourav Kottawar 53
P_Id LastName FirstName Address City
1 Hansen Ola
Timoteivn
10
Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
By:-Gourav Kottawar 54
• SELECT LastName,FirstName FROM
Persons
• The result-set will look like this:
By:-Gourav Kottawar
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
55
• The SQL SELECT DISTINCT Statement
• In a table, some of the columns may
contain duplicate values. This is not a
problem, however, sometimes you will
want to list only the different (distinct)
values in a table.
• The DISTINCT keyword can be used to
return only distinct (different) values.
By:-Gourav Kottawar 56
• SELECT DISTINCT column_name(s)
FROM table_name
• SELECT DISTINCT Example
• The "Persons" table:
SELECT DISTINCT City FROM Persons;
• The result-set will look like this:
• City
• Sandnes
• Stavanger
By:-Gourav Kottawar 57
• CLAUSES IN SQL The WHERE Clause
• SELECT column_name(s)
FROM table_name
WHERE column_name operator value
By:-Gourav Kottawar 58
• SELECT * FROM Persons
WHERE City='Sandnes'
• The result-set will look like this:
By:-Gourav Kottawar
P_Id LastName FirstName Address City
1 Hansen Ola
Timoteivn
10
Sandnes
2 Svendson Tove Borgvn 23 Sandnes
59
• This is correct:
SELECT * FROM Persons WHERE
FirstName='Tove‘ ;
This is wrong:
SELECT * FROM Persons WHERE
FirstName=Tove
By:-Gourav Kottawar 60
• This is correct:
SELECT * FROM Persons WHERE
Year=1965
This is wrong:
SELECT * FROM Persons WHERE
Year='1965'
By:-Gourav Kottawar 61
• Operators Allowed in the WHERE Clause
• With the WHERE clause, the following operators can
be used:
By:-Gourav Kottawar
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to
return for at least one of the columns
62
• Now we want to select only the persons
with the first name equal to "Tove" AND
the last name equal to "Svendson":
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE FirstName='Tove'
AND LastName='Svendson‘ ;
By:-Gourav Kottawar 63
• The result-set will look like this:
By:-Gourav Kottawar
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
64
• Now we want to select only the persons
with the first name equal to "Tove" OR the
first name equal to "Ola":We use the
following SELECT statement:
• SELECT * FROM Persons
WHERE FirstName='Tove'
OR FirstName='Ola‘ ;
By:-Gourav Kottawar 65
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
By:-Gourav Kottawar 66
• SELECT * FROM Persons WHERE
LastName='Svendson'
AND (FirstName='Tove' OR
FirstName='Ola');
• The result-set will look like this:
By:-Gourav Kottawar
P_Id LastName FirstNameAddress City
2 Svendson Tove Borgvn 23Sandnes
67
• SQL IN Operator
• The IN Operator
• The IN operator allows you to specify
multiple values in a WHERE clause.
• SQL IN Syntax:
• SELECT column_name(s)
FROM table_name
WHERE column_name IN
(value1,value2,...)
By:-Gourav Kottawar 68
• IN Operator Example
• The "Persons" table:
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE LastName IN
('Hansen','Pettersen')
• The result-set will look like this:
By:-Gourav Kottawar 69
_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
By:-Gourav Kottawar 70
• SQL BETWEEN Operator
• The BETWEEN operator is used in a
WHERE clause to select a range of data
between two values.
• The BETWEEN Operator
• The BETWEEN operator selects range of
data between two values. The values can
be numbers, text, or dates.
By:-Gourav Kottawar 71
• SQL BETWEEN Syntax:SELECT
column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
By:-Gourav Kottawar 72
LIKE Operator
• Using the % Wildcard
• 1.Now we want to select the persons living in a city that
starts with "sa" from the "Persons" table.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE City LIKE 'sa%'
• The result-set will look like this:
By:-Gourav Kottawar 73
P_Id LastName
FirstNam
e
Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
• 2. Next, we want to select the persons
living in a city that contains the pattern
"nes" from the "Persons" table.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE City LIKE '%nes%'
• The result-set will look like this
By:-Gourav Kottawar 74
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
• 3.Now we want to select the persons with
a first name that starts with any character,
followed by "la" from the "Persons" table.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE FirstName LIKE '_la'
• The result-set will look like this:
By:-Gourav Kottawar 75
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
• 4.Next, we want to select the persons with a
last name that starts with "S", followed by
any character, followed by "end", followed
by any character, followed by "on" from the
"Persons" table.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE LastName LIKE 'S_end_on'
• The result-set will look like this:
By:-Gourav Kottawar 76
_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
• Using the [charlist] Wildcard
• 5.Now we want to select the persons with
a last name that starts with "b" or "s" or "p"
from the "Persons" table.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE LastName LIKE '[bsp]%'
• The result-set will look like this:
By:-Gourav Kottawar 77
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
• 5.Next, we want to select the persons with
a last name that do not start with "b" or "s"
or "p" from the "Persons" table.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'
• The result-set will look like this:
By:-Gourav Kottawar 78
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
• The UPDATE Statement
• The UPDATE statement is used to update
existing records in a table.
• SQL UPDATE Syntax
• UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
By:-Gourav Kottawar 79
• Note: Notice the WHERE clause in the UPDATE syntax.
The WHERE clause specifies which record or records
that should be updated. If you omit the WHERE clause,
all records will be updated!
• SQL UPDATE Example :The "Persons" table
By:-Gourav Kottawar 80
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob
• Now we want to update the person "Tjessem,
Jakob" in the "Persons" table.
• We use the following SQL statement:
• UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob‘;
By:-Gourav Kottawar 81
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes
• The SQL SELECT DISTINCT Statement
• In a table, some of the columns may contain
duplicate values. This is not a problem,
however, sometimes you will want to list only
the different (distinct) values in a table.
• The DISTINCT keyword can be used to
return only distinct (different) values.
• SQL SELECT DISTINCT Syntax
• SELECT DISTINCT column_name(s)
FROM table_name
• SELECT DISTINCT Example
• The "Persons" table:
By:-Gourav Kottawar 82
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20
Stavange
r
By:-Gourav Kottawar 83
• CLAUSES IN SQL
• The WHERE Clause
• The WHERE clause is used to extract only
those records that fulfill a specified criterion.
– SQL WHERE Syntax
• SELECT column_name(s)
FROM table_name
WHERE column_name operator value
By:-Gourav Kottawar 84
• WHERE Clause Example
• The "Persons" table:
By:-Gourav Kottawar 85
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons
WHERE City='Sandnes'
Now we want to select only the persons living
in the city "Sandnes" from the table above.
We use the following SELECT statement:
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
By:-Gourav Kottawar 86
Quotes Around Text Fields
SQL uses single quotes around text values (most database
systems will also accept double quotes).
Although, numeric values should not be enclosed in
quotes.
• This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
• For numeric values:
• This is correct:
SELECT * FROM Persons WHERE Year=1965
This is wrong:
SELECT * FROM Persons WHERE Year='1965'
By:-Gourav Kottawar 87
• Operators Allowed in the WHERE
Clause
• With the WHERE clause, the following
operators can be used:
By:-Gourav Kottawar 88
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN
If you know the exact value you want to
return for at least one of the columns
• The AND operator displays a record if both the
first condition and the second condition is true.
• The OR operator displays a record if either the
first condition or the second condition is true.
• AND Operator Example
• The "Persons" table:
By:-Gourav Kottawar 89
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
• Now we want to select only the persons with the
first name equal to "Tove" AND the last name
equal to "Svendson":
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE FirstName='Tove'
AND LastName='Svendson‘
• The result-set will look like this:
By:-Gourav Kottawar 90
P_Id LastName FirstName Address City
2 Svendson Tove
Borgvn
23
Sandnes
• OR Operator Example
• Now we want to select only the persons with the
first name equal to "Tove" OR the first name
equal to "Ola":We use the following SELECT
statement:
• SELECT * FROM Persons
WHERE FirstName='Tove'
OR FirstName='Ola'
By:-Gourav Kottawar 91
• The result-set will look like this:
By:-Gourav Kottawar 92
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
Combining AND & OR
You can also combine AND and OR (use parenthesis to form
complex expressions).
Now we want to select only the persons with the last name
equal to "Svendson" AND the first name equal to "Tove" OR to
"Ola":
We use the following SELECT statement:
SELECT * FROM Persons WHERE
LastName='Svendson'
AND (FirstName='Tove' OR FirstName='Ola')
• SQL IN Operator
• The IN Operator
• The IN operator allows you to specify multiple values in a
WHERE clause.
• SQL IN Syntax:
• SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
By:-Gourav Kottawar 93
• IN Operator Example
• Now we want to select the persons with a last name
equal to "Hansen" or "Pettersen" from the table
above.
• We use the following SELECT statement:
• SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')
• The result-set will look like this:
By:-Gourav Kottawar 94
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
• SQL BETWEEN Operator
• The BETWEEN operator is used in a WHERE clause to
select a range of data between two values.
• The BETWEEN Operator
• The BETWEEN operator selects range of data between
two values. 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
•
•
• By:-Gourav Kottawar 95
• SELECT * FROM Persons
WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'
• The result-set will look like this:
By:-Gourav Kottawar 96
P_Id LastName FirstName Address City
1 Hansen Ola
Timoteivn
10
Sandnes
To display the persons outside the range in the
previous example, use NOT BETWEEN:
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
ORDER BY clause
• So far, we have seen how to get data out
of a table using SELECT and WHERE
commands. Often, however, we need to
list the output in a particular order. This
could be in ascending order, in
descending order, or could be based on
either numerical value or text value. In
such cases, we can use the ORDER BY
keyword to achieve our goal.
By:-Gourav Kottawar 97
• The syntax for an ORDER BY statement is
as follows:
• SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC,
DESC]
By:-Gourav Kottawar 98
• The [] means that the WHERE statement
is optional. However, if a WHERE clause
exists, it comes before the ORDER BY
clause. ASC means that the results will be
shown in ascending order, and DESC
means that the results will be shown in
descending order. If neither is specified,
the default is ASC.
By:-Gourav Kottawar 99
• For example, we may wish to list the
contents of Table Store_Information by
dollar amount, in descending order:
By:-Gourav Kottawar
store_name Sales Date
Los Angeles $1500 Jan-05-1999
Boston $700 Jan-08-1999
San
Francisco
$300 Jan-08-1999
San Diego $250 Jan-07-1999
100
• The GROUP BY Statement
• The GROUP BY statement is used in
conjunction with the aggregate functions to
group the result-set by one or more
columns.
• SQL GROUP BY Syntax:
• SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
By:-Gourav Kottawar 101
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
By:-Gourav Kottawar 102
• Now we want to find the total sum (total order) of each
customer.
• We will have to use the GROUP BY statement to group
the customers.
• We use the following SQL statement:
• SELECT Customer, SUM(OrderPrice)
FROM Orders
GROUP BY Customer
• The result-set will look like this:
By:-Gourav Kottawar
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
103
• We can also use the GROUP BY
statement on more than one column, like
this:
• SELECT
Customer,OrderDate,SUM(OrderPrice)
FROM Orders
GROUP BY Customer,OrderDate
By:-Gourav Kottawar 104
• Date functions in SQL
•
• 1. SYSDATE() Sysdate to diplay system
date.
•
• SQL> select sysdate from dual;
•
• SYSDATE
• ---------
• 23-NOV-10
• By:-Gourav Kottawar 105
• 2. LAST_DAY: Last_day to display last
day of the current/mentioned date.
•
• SQL> select last_day(sysdate) from
dual;
•
• LAST_DAY
• ---------
• 30-NOV-10
By:-Gourav Kottawar 106
• SQL> select last_day('06-nov-2010') from dual;
• LAST_DAY
• ---------
• 30-NOV-10
• 3. NEXT_DAY : to display next day of the mentioned
date,that is if today if 6th dec and today id Monday then
when will next day
• SQL> Select next_day('06-dec-2010','Monday') from
• dual;
•
By:-Gourav Kottawar 107
4. MONTHS_BETWEEN : Calculates the months between
the two dates.
• select months_between('02-feb-2010','03-Dec-2009')
from dual;
• MONTHS_BETWEEN('02-FEB-2010','03-DEC-2009')
-------------------------------------------
1.9677419
5. ADD_MONTHS adds month to the current date.
•
• SQL> select add_months(sysdate,4) from dual;
•
• ADD_MONTH
---------
• 23-MAR-11 By:-Gourav Kottawar 108
• SQL Aggregate Functions
• SQL aggregate functions return a single
value, calculated from values in a column.
• Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
By:-Gourav Kottawar 109
• SQL COUNT(*) Example
• SELECT COUNT(*) FROM Orders;
By:-Gourav Kottawar 110
• MANIPULATION in DATES in SQL
1. TOCHAR:
• To retrieve date in a format other than default format.
• select to_char (sysdate,'DD-MM-YY') from dual;
TO_CHAR(
--------
23-11-10
2.TO_DATE
•
• select to_date('06/07/2010','DD/MON/YY') from dual;
• TO_DATE('
• ---------
06/JUL/10
By:-Gourav Kottawar 111
• The MAX() Function
• The MAX() function returns the largest
value of the selected column.
• SQL MAX() Syntax:SELECT
MAX(column_name) FROM table_name
• SELECT MAX(OrderPrice) AS
LargestOrderPrice FROM Orders
By:-Gourav Kottawar 112
• SQL MIN() Function
• The MIN() function returns the smallest
value of the selected column.
• SQL MIN() Syntax:SELECT
MIN(column_name) FROM table_name
• SELECT MIN(OrderPrice) AS
SmallestOrderPrice FROM Orders
By:-Gourav Kottawar 113
• The SUM() Function
• The SUM() function returns the total sum
of a numeric column.
• SQL SUM() Syntax: SELECT
SUM(column_name) FROM table_name
• SELECT SUM(OrderPrice) AS
OrderTotal FROM Orders
By:-Gourav Kottawar 114
SQL STRING FUNCTION
1.SUBSTR
• Table Geography region_name
store_name East Boston East New York
West Los Angeles West San Diego
• Example 1:
• SELECT SUBSTR(store_name, 3)
FROM Geography
WHERE store_name = 'Los Angeles';
By:-Gourav Kottawar 115
• Result:
• 's Angeles'
• Example 2:
• SELECT SUBSTR(store_name,2,4)
FROM Geography
WHERE store_name = 'San Diego';
• Result:
• 'an D'
By:-Gourav Kottawar 116
• 2.LTRIM(str): Removes all white spaces
from the beginning of the string.
• 3.RTRIM(str): Removes all white spaces
at the end of the string.
• Example 1:
• SELECT TRIM(' Sample ') from
tablename;
• Result:
• 'Sample'
By:-Gourav Kottawar 117
• Example 2:
• SELECT LTRIM(' Sample ');
• Result:
• 'Sample '
• Example 3:
• SELECT RTRIM(' Sample ');
• Result:
• ' Sample'
By:-Gourav Kottawar 118
• 4. Length(str): Find the length of the
string str.
By:-Gourav Kottawar
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
119
• Example 1:
• SELECT Length(store_name)
FROM Geography
WHERE store_name = 'Los Angeles';
• Result:
• 11
By:-Gourav Kottawar 120
• Example 2:
• SELECT region_name,
Length(region_name)
FROM Geography;
• Result:
By:-Gourav Kottawar
region_name
Length(regio
n_name)
East 4
East 4
West 4
West 4
121
• 5.Replace(str1, str2, str3): In str1, find
where str2 occurs, and replace it with str3.
• SELECT REPLACE(region_name, 'ast',
'astern')
FROM Geography;
By:-Gourav Kottawar
region_name
Eastern
Eastern
West
West
122
• 6. CONCAT
• CONCAT(str1, str2, str3, ...):
Concatenate str1, str2, str3, and any other
strings together. Please note the Oracle
CONCAT() function only allows two
arguments -- only two strings can be put
together at a time using this function.
However, it is possible to concatenate
more than two strings at a time in Oracle
using '||'.
By:-Gourav Kottawar 123
• SELECT
CONCAT(region_name,store_name)
FROM Geography
WHERE store_name = 'Boston';
• Result:
'EastBoston'
• SELECT region_name || ' ' ||
store_name FROM Geography
WHERE store_name = 'Boston';
• Result:
'East Boston' By:-Gourav Kottawar 124

More Related Content

What's hot

Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)UC San Diego
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries InformationNishant Munjal
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMSkoolkampus
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Dfd examples
Dfd examplesDfd examples
Dfd examplesMohit
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQLKailash N
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Punjab University
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands1keydata
 
Introduction to Oracle Database
Introduction to Oracle DatabaseIntroduction to Oracle Database
Introduction to Oracle Databasepuja_dhar
 
How to Draw an Effective ER diagram
How to Draw an Effective ER diagramHow to Draw an Effective ER diagram
How to Draw an Effective ER diagramTech_MX
 

What's hot (20)

Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Java servlets and CGI
Java servlets and CGIJava servlets and CGI
Java servlets and CGI
 
DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMS
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
 
Dfd examples
Dfd examplesDfd examples
Dfd examples
 
Array in c#
Array in c#Array in c#
Array in c#
 
Sql operator
Sql operatorSql operator
Sql operator
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQL
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Oracle: DML
Oracle: DMLOracle: DML
Oracle: DML
 
Introduction to Oracle Database
Introduction to Oracle DatabaseIntroduction to Oracle Database
Introduction to Oracle Database
 
How to Draw an Effective ER diagram
How to Draw an Effective ER diagramHow to Draw an Effective ER diagram
How to Draw an Effective ER diagram
 

Viewers also liked (20)

Sql ppt
Sql pptSql ppt
Sql ppt
 
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick LearningOracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
 
DBMS Bascis
DBMS BascisDBMS Bascis
DBMS Bascis
 
Les07 (using the set operators)
Les07 (using the set operators)Les07 (using the set operators)
Les07 (using the set operators)
 
SQL Server Views
SQL Server ViewsSQL Server Views
SQL Server Views
 
Part 6 ddl dan dml (case studiies)
Part 6  ddl dan dml (case studiies)Part 6  ddl dan dml (case studiies)
Part 6 ddl dan dml (case studiies)
 
Dbms
DbmsDbms
Dbms
 
Sql a practical_introduction
Sql a practical_introductionSql a practical_introduction
Sql a practical_introduction
 
DDL DML sysytems
DDL DML sysytemsDDL DML sysytems
DDL DML sysytems
 
Dbms ii pr asg 31 1-2015
Dbms  ii pr asg 31 1-2015Dbms  ii pr asg 31 1-2015
Dbms ii pr asg 31 1-2015
 
Introduction of DBMS,RDBMS,SQL
Introduction of DBMS,RDBMS,SQLIntroduction of DBMS,RDBMS,SQL
Introduction of DBMS,RDBMS,SQL
 
Dbms project file
Dbms project fileDbms project file
Dbms project file
 
Dbms lab file format front page
Dbms lab file format front pageDbms lab file format front page
Dbms lab file format front page
 
Learn Kannada Lesson 1
Learn Kannada Lesson 1Learn Kannada Lesson 1
Learn Kannada Lesson 1
 
Introduction to mysql part 1
Introduction to mysql part 1Introduction to mysql part 1
Introduction to mysql part 1
 
1. SQL Basics - Introduction
1. SQL Basics - Introduction1. SQL Basics - Introduction
1. SQL Basics - Introduction
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
 
Kannada Basics
Kannada BasicsKannada Basics
Kannada Basics
 
Set operators
Set  operatorsSet  operators
Set operators
 
Sql
SqlSql
Sql
 

Similar to DBMS information in detail || Dbms (lab) ppt

Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql MengChun Lam
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command StatementsShaun Wilson
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptxMohamedNowfeek1
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxYashaswiniSrinivasan1
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systemsSHAKIR325211
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle Abrar ali
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleFarhan Aslam
 
SQL - Data Definition Language
SQL - Data Definition Language SQL - Data Definition Language
SQL - Data Definition Language Imam340267
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfssuserb5bb0e
 

Similar to DBMS information in detail || Dbms (lab) ppt (20)

Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command Statements
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
 
Database
Database Database
Database
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptx
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systems
 
Les09
Les09Les09
Les09
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
 
SQL - Data Definition Language
SQL - Data Definition Language SQL - Data Definition Language
SQL - Data Definition Language
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
 
2016 02 23_biological_databases_part2
2016 02 23_biological_databases_part22016 02 23_biological_databases_part2
2016 02 23_biological_databases_part2
 

More from gourav kottawar

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cppgourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cppgourav kottawar
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overviewgourav kottawar
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basicsgourav kottawar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sqlgourav kottawar
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesgourav kottawar
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overviewgourav kottawar
 
overview of database concept
overview of database conceptoverview of database concept
overview of database conceptgourav kottawar
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql databasegourav kottawar
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql databasegourav kottawar
 

More from gourav kottawar (20)

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cpp
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sql
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
 
overview of database concept
overview of database conceptoverview of database concept
overview of database concept
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql database
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

DBMS information in detail || Dbms (lab) ppt

  • 2. • Introduction of SQL • DDL, DML, DTL • Basic Data Types • Char, varchar/varchar2, long, number, Fixed & floating point Date, CLOB, BLOB By:-Gourav Kottawar 2
  • 3. • What is SQL? • SQL stands for Structured Query Language • SQL lets you access and manipulate databases • SQL is an ANSI (American National Standards Institute) standard • What Can SQL do? • SQL can execute queries against a database • SQL can retrieve data from a database • SQL can insert records in a database • SQL can update records in a database • SQL can delete records from a database • SQL can create new databases • SQL can create new tables in a database • SQL can create stored procedures in a database • SQL can create views in a database • SQL can set permissions on tables, procedures, and views By:-Gourav Kottawar 3
  • 4. • SELECT * FROM Persons; • SQL is not case sensitive, Semicolon after SQL Statements. • Some database systems require a semicolon at the end of each SQL statement. • Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server. • We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it. By:-Gourav Kottawar 4
  • 5. • SQL DML and DDL • SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL). • The query and update commands form the DML part of SQL: • SELECT - extracts data from a database • UPDATE - updates data in a database • DELETE - deletes data from a database • INSERT INTO - inserts new data into a database By:-Gourav Kottawar 5
  • 6. • The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are: • CREATE TABLE - creates a new table • ALTER TABLE - modifies a table • DROP TABLE - deletes a table By:-Gourav Kottawar 6
  • 7. • A Transaction Control Language (TCL) : • is a computer language and a subset of SQL, used to control transactional processing in a database. A transaction is logical unit of work that comprises one or more SQL statements, usually a group of Data Manipulation Language (DML) statements. • Examples of TCL commands include: • COMMIT to apply the transaction by saving the database changes. • ROLLBACK to undo all changes of a transaction. • SAVEPOINT to divide the transaction into smaller sections. It defines breakpoints for a transaction to allow partial rollbacks. By:-Gourav Kottawar 7
  • 8. DATA TYPES IN SQL By:-Gourav Kottawar 8
  • 9. By:-Gourav Kottawar 9 Data Type Syntax Explanation (if applicable) INTEGER INTEGER(p) Integer numerical (no decimal). Precision p SMALLINT Integer numerical (no decimal). Precision 5 INTEGER Integer numerical (no decimal). Precision 10
  • 10. By:-Gourav Kottawar 10 Syntax float [ ( n ) ] Is a floating point number data with the following valid values: - 1.79E + 308 through -2.23E - 308, 0 and 2.23E -308 through 1.79E + 308. n is the number of bits used to store the mantissa of the float number in scientific notation and thus dictates the precision and storage size. n must be a value from 1 through 53. The default value of n is 53. real Is a floating point number data with the following valid values: –3.40E + 38 through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38. Storage size is 4 bytes. In SQL Server, the synonym for real is float(24).
  • 11. nvalue Precision Storage size 1-24 7 digits 4 bytes 25-53 15 digits 8 bytes By:-Gourav Kottawar 11 Data type Range Storage float - 1.79E+308 to -2.23E- 308, 0 and 2.23E-308 to 1.79E+308 Depends on the value of n real - 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 38 to 3.40E + 38 4 Bytes
  • 12. character char(x) Where x is the number of characters to store. This data type is space padded to fill the number of characters specified. character varying varchar2(x) Where x is the number of characters to store. This data type does NOT space pad. BOOLEAN BOOLEAN Stores TRUE or FALSE values date date Stores year, month, and day values. time time Stores the hour, minute, and second values. timestamp timestamp Stores year, month, day, hour, minute, and second values.By:-Gourav Kottawar 12
  • 13. Difference between VARCHAR and VARCHAR2 1. VARCHAR is going to be replaced by VARCHAR2 in next version. So, Oracle suggests the use VARCHAR2 instead of VARCHAR while declaring datatype. 2. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters. 3. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space. By:-Gourav Kottawar 13
  • 14. • Difference Between Number and Integer • NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained. INTEGER(12,2) => 12 INTEGER(12.5) => 13 INTEGER(12.9) => 13 INTEGER(12.4) => 12 NUMBER(12,2) => 12.2 NUMBER(12.5) => 12.5 NUMBER(12.9) => 12.9 NUMBER(12.4) => 12.4By:-Gourav Kottawar 14
  • 15. • Database Tables • A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. • Below is an example of a table called "Persons": By:-Gourav Kottawar 15
  • 16. By:-Gourav Kottawar 16 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger The table above contains three records (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City).
  • 17. • The CREATE TABLE Statement • The CREATE TABLE statement is used to create a table in a database. • SQL CREATE TABLE Syntax • CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) By:-Gourav Kottawar 17
  • 18. • CREATE TABLE Example • Now we want to create a table called "Persons" that contains five columns: P_Id, LastName, FirstName, Address, and City. • We use the following CREATE TABLE statement: • CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); By:-Gourav Kottawar 18
  • 19. • The P_Id column is of type int and will hold a number. The LastName, FirstName, Address, and City columns are of type varchar with a maximum length of 255 characters. • The empty "Persons" table will now look like this: • The empty table can be filled with data with the INSERT INTO statement. By:-Gourav Kottawar 19 P_Id LastName FirstName Address City
  • 20. • SQL Constraints • Constraints are used to limit the type of data that can go into a table. • Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement). • We will focus on the following constraints: • NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY • CHECK • DEFAULT By:-Gourav Kottawar 20
  • 21. • SQL NOT NULL Constraint • The NOT NULL constraint enforces a column to NOT accept NULL values. • The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. • The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values: • CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) By:-Gourav Kottawar 21
  • 22. • SQL UNIQUE Constraint • The UNIQUE constraint uniquely identifies each record in a database table. • The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. • A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. • Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. By:-Gourav Kottawar 22
  • 23. • SQL UNIQUE Constraint on CREATE TABLE • The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created: • MySQL: • CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (P_Id) ) By:-Gourav Kottawar 23
  • 24. • CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) By:-Gourav Kottawar 24
  • 25. • CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) • To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax: • MySQL / SQL Server / Oracle / MS Access: • CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT uc_PersonsId UNIQUE (P_Id,LastName) ) By:-Gourav Kottawar 25
  • 26. • SQL UNIQUE Constraint on ALTER TABLE • To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following SQL: • MySQL / SQL Server / Oracle / MS Access: • ALTER TABLE Persons ADD UNIQUE (P_Id) • To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax: • MySQL / SQL Server / Oracle / MS Access: • ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) By:-Gourav Kottawar 26
  • 27. • To DROP a UNIQUE Constraint • To drop a UNIQUE constraint, use the following SQL: • SQL Server / Oracle / MS Access: • ALTER TABLE Persons DROP CONSTRAINT uc_PersonID By:-Gourav Kottawar 27
  • 28. • SQL PRIMARY KEY Constraint • The PRIMARY KEY constraint uniquely identifies each record in a database table. • Primary keys must contain unique values. • A primary key column cannot contain NULL values. • Each table should have a primary key, and each table can have only one primary key. • SQL PRIMARY KEY Constraint on CREATE TABLE By:-Gourav Kottawar 28
  • 29. • The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created: • MySQL: • CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) • SQL Server / Oracle / MS Access: • CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) By:-Gourav Kottawar 29
  • 30. • SQL PRIMARY KEY Constraint on ALTER TABLE • To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL: • MySQL / SQL Server / Oracle / MS Access: • ALTER TABLE Persons ADD PRIMARY KEY (P_Id) By:-Gourav Kottawar 30
  • 31. • MySQL / SQL Server / Oracle / MS Access: • ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id); • Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created). By:-Gourav Kottawar 31
  • 32. • To DROP a PRIMARY KEY Constraint • To drop a PRIMARY KEY constraint, use the following SQL: • MySQL: • ALTER TABLE Persons DROP PRIMARY KEY • SQL Server / Oracle / MS Access: • ALTER TABLE Persons DROP CONSTRAINT pk_PersonID By:-Gourav Kottawar 32
  • 33. • The FOREIGN KEY constraint SQL FOREIGN KEY Constraint • A FOREIGN KEY in one table points to a PRIMARY KEY in another table. • Let's illustrate the foreign key with an example. Look at the following two tables: • The "Persons" table: By:-Gourav Kottawar 33
  • 34. P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger By:-Gourav Kottawar 34 O_Id OrderNo P_Id 1 77895 3 2 44678 3 3 22456 2 4 24562 1 PERSONS TABLE ORDERS TABLE
  • 35. 35 Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy link between tables. The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign key column, because it has to be one of the values contained in the table it points to. By:-Gourav Kottawar
  • 36. • CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) By:-Gourav Kottawar 36
  • 37. • CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) ) By:-Gourav Kottawar 37
  • 38. DROP TABLE • Helps in removing the rows from the table. • It is a DML command. • The description (structure) of the table is removed. • The existence of the table is removed. (Table cant be seen from in select * from tab). Rollback though shows completed but table view doesn’t come back. AS IT IS A DML COMMAND ROLLBACK WILL NOT WORK By:-Gourav Kottawar 38
  • 39. • ALTER table tablename DROP column colname SQL> alter table emp 2 drop column age; drop column age * ERROR at line 2: ORA-00905: missing keyword ALTER-Drop column will work in Oracle 9i and above version.By:-Gourav Kottawar 39
  • 40. • ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id); • ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) By:-Gourav Kottawar 40
  • 41. SQL> drop table room; Table dropped. SQL> desc room; //description is not available ERROR: ORA-04043: object room does not exist By:-Gourav Kottawar 41
  • 42. • The INSERT INTO Statement • The INSERT INTO statement is used to insert a new row in a table. • SQL INSERT INTO Syntax: • It is possible to write the INSERT INTO statement in two forms. • The first form doesn't specify the column names where the data will be inserted, only their values: • INSERT INTO table_name VALUES (value1, value2, value3,...) By:-Gourav Kottawar 42
  • 43. • INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob') • The second form specifies both the column names and the values to be inserted: • INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) By:-Gourav Kottawar 43
  • 44. • SQL INSERT INTO Example • We have the following "Persons" table: By:-Gourav Kottawar 44 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger : Now we want to insert a new row in the "Persons" table. We use the following SQL statement INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger') P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger 4 Nilsen Johan Bakken 2 Stavanger
  • 45. • Insert Data Only in Specified Columns • It is also possible to only add data in specific columns. • The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns: • INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob') • The "Persons" table will now look like this: By:-Gourav Kottawar 45 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger 4 Nilsen Johan Bakken 2 Stavanger 5 Tjessem Jakob
  • 46. • The SQL SELECT Statement • The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. • SQL SELECT Syntax • SELECT column_name(s) FROM table_name • SELECT * FROM table_name And • ‘*’ Also called as Global Extraction Opearator • Note: SQL is not case sensitive. SELECT is the same as select. • An SQL SELECT Example • The "Persons" table: By:-Gourav Kottawar 46
  • 47. P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger By:-Gourav Kottawar 47
  • 48. • SQL CHECK Constraint on CREATE TABLE • The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0. • CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(25) NOT NULL, FirstName varchar(25), Address varchar(25), City varchar(25) ) By:-Gourav Kottawar 48
  • 49. • To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') ) By:-Gourav Kottawar 49
  • 50. • SQL CHECK Constraint on ALTER TABLE • To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL: • ALTER TABLE Persons ADD CHECK (P_Id>0) • To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax: • ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') By:-Gourav Kottawar 50
  • 51. • To DROP a CHECK Constraint • To drop a CHECK constraint, use the following SQL: • ALTER TABLE Persons DROP CONSTRAINT chk_Person; By:-Gourav Kottawar 51
  • 52. • The DROP TABLE Statement • The DROP TABLE statement is used to delete a table. DROP TABLE table_name By:-Gourav Kottawar 52
  • 53. • SQL SELECT Syntax • SELECT column_name(s) FROM table_name • SELECT * FROM table_name • And • ‘*’ Also called as Global Extraction Opearator By:-Gourav Kottawar 53
  • 54. P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger By:-Gourav Kottawar 54
  • 55. • SELECT LastName,FirstName FROM Persons • The result-set will look like this: By:-Gourav Kottawar LastName FirstName Hansen Ola Svendson Tove Pettersen Kari 55
  • 56. • The SQL SELECT DISTINCT Statement • In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. • The DISTINCT keyword can be used to return only distinct (different) values. By:-Gourav Kottawar 56
  • 57. • SELECT DISTINCT column_name(s) FROM table_name • SELECT DISTINCT Example • The "Persons" table: SELECT DISTINCT City FROM Persons; • The result-set will look like this: • City • Sandnes • Stavanger By:-Gourav Kottawar 57
  • 58. • CLAUSES IN SQL The WHERE Clause • SELECT column_name(s) FROM table_name WHERE column_name operator value By:-Gourav Kottawar 58
  • 59. • SELECT * FROM Persons WHERE City='Sandnes' • The result-set will look like this: By:-Gourav Kottawar P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 59
  • 60. • This is correct: SELECT * FROM Persons WHERE FirstName='Tove‘ ; This is wrong: SELECT * FROM Persons WHERE FirstName=Tove By:-Gourav Kottawar 60
  • 61. • This is correct: SELECT * FROM Persons WHERE Year=1965 This is wrong: SELECT * FROM Persons WHERE Year='1965' By:-Gourav Kottawar 61
  • 62. • Operators Allowed in the WHERE Clause • With the WHERE clause, the following operators can be used: By:-Gourav Kottawar Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern IN If you know the exact value you want to return for at least one of the columns 62
  • 63. • Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to "Svendson": • We use the following SELECT statement: • SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson‘ ; By:-Gourav Kottawar 63
  • 64. • The result-set will look like this: By:-Gourav Kottawar P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes 64
  • 65. • Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola":We use the following SELECT statement: • SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola‘ ; By:-Gourav Kottawar 65
  • 66. P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes By:-Gourav Kottawar 66
  • 67. • SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR FirstName='Ola'); • The result-set will look like this: By:-Gourav Kottawar P_Id LastName FirstNameAddress City 2 Svendson Tove Borgvn 23Sandnes 67
  • 68. • SQL IN Operator • The IN Operator • The IN operator allows you to specify multiple values in a WHERE clause. • SQL IN Syntax: • SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) By:-Gourav Kottawar 68
  • 69. • IN Operator Example • The "Persons" table: • We use the following SELECT statement: • SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') • The result-set will look like this: By:-Gourav Kottawar 69
  • 70. _Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 3 Pettersen Kari Storgt 20 Stavanger By:-Gourav Kottawar 70
  • 71. • SQL BETWEEN Operator • The BETWEEN operator is used in a WHERE clause to select a range of data between two values. • The BETWEEN Operator • The BETWEEN operator selects range of data between two values. The values can be numbers, text, or dates. By:-Gourav Kottawar 71
  • 72. • SQL BETWEEN Syntax:SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2 By:-Gourav Kottawar 72
  • 73. LIKE Operator • Using the % Wildcard • 1.Now we want to select the persons living in a city that starts with "sa" from the "Persons" table. • We use the following SELECT statement: • SELECT * FROM Persons WHERE City LIKE 'sa%' • The result-set will look like this: By:-Gourav Kottawar 73 P_Id LastName FirstNam e Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes
  • 74. • 2. Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons" table. • We use the following SELECT statement: • SELECT * FROM Persons WHERE City LIKE '%nes%' • The result-set will look like this By:-Gourav Kottawar 74 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes
  • 75. • 3.Now we want to select the persons with a first name that starts with any character, followed by "la" from the "Persons" table. • We use the following SELECT statement: • SELECT * FROM Persons WHERE FirstName LIKE '_la' • The result-set will look like this: By:-Gourav Kottawar 75 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes
  • 76. • 4.Next, we want to select the persons with a last name that starts with "S", followed by any character, followed by "end", followed by any character, followed by "on" from the "Persons" table. • We use the following SELECT statement: • SELECT * FROM Persons WHERE LastName LIKE 'S_end_on' • The result-set will look like this: By:-Gourav Kottawar 76 _Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes
  • 77. • Using the [charlist] Wildcard • 5.Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the "Persons" table. • We use the following SELECT statement: • SELECT * FROM Persons WHERE LastName LIKE '[bsp]%' • The result-set will look like this: By:-Gourav Kottawar 77 P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
  • 78. • 5.Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the "Persons" table. • We use the following SELECT statement: • SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%' • The result-set will look like this: By:-Gourav Kottawar 78 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes
  • 79. • The UPDATE Statement • The UPDATE statement is used to update existing records in a table. • SQL UPDATE Syntax • UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value By:-Gourav Kottawar 79
  • 80. • Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! • SQL UPDATE Example :The "Persons" table By:-Gourav Kottawar 80 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger 4 Nilsen Johan Bakken 2 Stavanger 5 Tjessem Jakob
  • 81. • Now we want to update the person "Tjessem, Jakob" in the "Persons" table. • We use the following SQL statement: • UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob‘; By:-Gourav Kottawar 81 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger 4 Nilsen Johan Bakken 2 Stavanger 5 Tjessem Jakob Nissestien 67 Sandnes
  • 82. • The SQL SELECT DISTINCT Statement • In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. • The DISTINCT keyword can be used to return only distinct (different) values. • SQL SELECT DISTINCT Syntax • SELECT DISTINCT column_name(s) FROM table_name • SELECT DISTINCT Example • The "Persons" table: By:-Gourav Kottawar 82
  • 83. P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavange r By:-Gourav Kottawar 83
  • 84. • CLAUSES IN SQL • The WHERE Clause • The WHERE clause is used to extract only those records that fulfill a specified criterion. – SQL WHERE Syntax • SELECT column_name(s) FROM table_name WHERE column_name operator value By:-Gourav Kottawar 84
  • 85. • WHERE Clause Example • The "Persons" table: By:-Gourav Kottawar 85 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger SELECT * FROM Persons WHERE City='Sandnes' Now we want to select only the persons living in the city "Sandnes" from the table above. We use the following SELECT statement: The result-set will look like this:
  • 86. P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes By:-Gourav Kottawar 86 Quotes Around Text Fields SQL uses single quotes around text values (most database systems will also accept double quotes). Although, numeric values should not be enclosed in quotes.
  • 87. • This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove • For numeric values: • This is correct: SELECT * FROM Persons WHERE Year=1965 This is wrong: SELECT * FROM Persons WHERE Year='1965' By:-Gourav Kottawar 87
  • 88. • Operators Allowed in the WHERE Clause • With the WHERE clause, the following operators can be used: By:-Gourav Kottawar 88 Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern IN If you know the exact value you want to return for at least one of the columns
  • 89. • The AND operator displays a record if both the first condition and the second condition is true. • The OR operator displays a record if either the first condition or the second condition is true. • AND Operator Example • The "Persons" table: By:-Gourav Kottawar 89 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
  • 90. • Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to "Svendson": • We use the following SELECT statement: • SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson‘ • The result-set will look like this: By:-Gourav Kottawar 90 P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes
  • 91. • OR Operator Example • Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola":We use the following SELECT statement: • SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola' By:-Gourav Kottawar 91
  • 92. • The result-set will look like this: By:-Gourav Kottawar 92 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes Combining AND & OR You can also combine AND and OR (use parenthesis to form complex expressions). Now we want to select only the persons with the last name equal to "Svendson" AND the first name equal to "Tove" OR to "Ola": We use the following SELECT statement: SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR FirstName='Ola')
  • 93. • SQL IN Operator • The IN Operator • The IN operator allows you to specify multiple values in a WHERE clause. • SQL IN Syntax: • SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) By:-Gourav Kottawar 93
  • 94. • IN Operator Example • Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table above. • We use the following SELECT statement: • SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') • The result-set will look like this: By:-Gourav Kottawar 94 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
  • 95. • SQL BETWEEN Operator • The BETWEEN operator is used in a WHERE clause to select a range of data between two values. • The BETWEEN Operator • The BETWEEN operator selects range of data between two values. 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 • • • By:-Gourav Kottawar 95
  • 96. • SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen' • The result-set will look like this: By:-Gourav Kottawar 96 P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes To display the persons outside the range in the previous example, use NOT BETWEEN: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen' The result-set will look like this: P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
  • 97. ORDER BY clause • So far, we have seen how to get data out of a table using SELECT and WHERE commands. Often, however, we need to list the output in a particular order. This could be in ascending order, in descending order, or could be based on either numerical value or text value. In such cases, we can use the ORDER BY keyword to achieve our goal. By:-Gourav Kottawar 97
  • 98. • The syntax for an ORDER BY statement is as follows: • SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC, DESC] By:-Gourav Kottawar 98
  • 99. • The [] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes before the ORDER BY clause. ASC means that the results will be shown in ascending order, and DESC means that the results will be shown in descending order. If neither is specified, the default is ASC. By:-Gourav Kottawar 99
  • 100. • For example, we may wish to list the contents of Table Store_Information by dollar amount, in descending order: By:-Gourav Kottawar store_name Sales Date Los Angeles $1500 Jan-05-1999 Boston $700 Jan-08-1999 San Francisco $300 Jan-08-1999 San Diego $250 Jan-07-1999 100
  • 101. • The GROUP BY Statement • The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. • SQL GROUP BY Syntax: • SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name By:-Gourav Kottawar 101
  • 102. O_Id OrderDate OrderPrice Customer 1 2008/11/12 1000 Hansen 2 2008/10/23 1600 Nilsen 3 2008/09/02 700 Hansen 4 2008/09/03 300 Hansen 5 2008/08/30 2000 Jensen 6 2008/10/04 100 Nilsen By:-Gourav Kottawar 102
  • 103. • Now we want to find the total sum (total order) of each customer. • We will have to use the GROUP BY statement to group the customers. • We use the following SQL statement: • SELECT Customer, SUM(OrderPrice) FROM Orders GROUP BY Customer • The result-set will look like this: By:-Gourav Kottawar Customer SUM(OrderPrice) Hansen 2000 Nilsen 1700 Jensen 2000 103
  • 104. • We can also use the GROUP BY statement on more than one column, like this: • SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate By:-Gourav Kottawar 104
  • 105. • Date functions in SQL • • 1. SYSDATE() Sysdate to diplay system date. • • SQL> select sysdate from dual; • • SYSDATE • --------- • 23-NOV-10 • By:-Gourav Kottawar 105
  • 106. • 2. LAST_DAY: Last_day to display last day of the current/mentioned date. • • SQL> select last_day(sysdate) from dual; • • LAST_DAY • --------- • 30-NOV-10 By:-Gourav Kottawar 106
  • 107. • SQL> select last_day('06-nov-2010') from dual; • LAST_DAY • --------- • 30-NOV-10 • 3. NEXT_DAY : to display next day of the mentioned date,that is if today if 6th dec and today id Monday then when will next day • SQL> Select next_day('06-dec-2010','Monday') from • dual; • By:-Gourav Kottawar 107
  • 108. 4. MONTHS_BETWEEN : Calculates the months between the two dates. • select months_between('02-feb-2010','03-Dec-2009') from dual; • MONTHS_BETWEEN('02-FEB-2010','03-DEC-2009') ------------------------------------------- 1.9677419 5. ADD_MONTHS adds month to the current date. • • SQL> select add_months(sysdate,4) from dual; • • ADD_MONTH --------- • 23-MAR-11 By:-Gourav Kottawar 108
  • 109. • SQL Aggregate Functions • SQL aggregate functions return a single value, calculated from values in a column. • Useful aggregate functions: • AVG() - Returns the average value • COUNT() - Returns the number of rows • FIRST() - Returns the first value • LAST() - Returns the last value • MAX() - Returns the largest value • MIN() - Returns the smallest value • SUM() - Returns the sum By:-Gourav Kottawar 109
  • 110. • SQL COUNT(*) Example • SELECT COUNT(*) FROM Orders; By:-Gourav Kottawar 110
  • 111. • MANIPULATION in DATES in SQL 1. TOCHAR: • To retrieve date in a format other than default format. • select to_char (sysdate,'DD-MM-YY') from dual; TO_CHAR( -------- 23-11-10 2.TO_DATE • • select to_date('06/07/2010','DD/MON/YY') from dual; • TO_DATE(' • --------- 06/JUL/10 By:-Gourav Kottawar 111
  • 112. • The MAX() Function • The MAX() function returns the largest value of the selected column. • SQL MAX() Syntax:SELECT MAX(column_name) FROM table_name • SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders By:-Gourav Kottawar 112
  • 113. • SQL MIN() Function • The MIN() function returns the smallest value of the selected column. • SQL MIN() Syntax:SELECT MIN(column_name) FROM table_name • SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders By:-Gourav Kottawar 113
  • 114. • The SUM() Function • The SUM() function returns the total sum of a numeric column. • SQL SUM() Syntax: SELECT SUM(column_name) FROM table_name • SELECT SUM(OrderPrice) AS OrderTotal FROM Orders By:-Gourav Kottawar 114
  • 115. SQL STRING FUNCTION 1.SUBSTR • Table Geography region_name store_name East Boston East New York West Los Angeles West San Diego • Example 1: • SELECT SUBSTR(store_name, 3) FROM Geography WHERE store_name = 'Los Angeles'; By:-Gourav Kottawar 115
  • 116. • Result: • 's Angeles' • Example 2: • SELECT SUBSTR(store_name,2,4) FROM Geography WHERE store_name = 'San Diego'; • Result: • 'an D' By:-Gourav Kottawar 116
  • 117. • 2.LTRIM(str): Removes all white spaces from the beginning of the string. • 3.RTRIM(str): Removes all white spaces at the end of the string. • Example 1: • SELECT TRIM(' Sample ') from tablename; • Result: • 'Sample' By:-Gourav Kottawar 117
  • 118. • Example 2: • SELECT LTRIM(' Sample '); • Result: • 'Sample ' • Example 3: • SELECT RTRIM(' Sample '); • Result: • ' Sample' By:-Gourav Kottawar 118
  • 119. • 4. Length(str): Find the length of the string str. By:-Gourav Kottawar region_name store_name East Boston East New York West Los Angeles West San Diego 119
  • 120. • Example 1: • SELECT Length(store_name) FROM Geography WHERE store_name = 'Los Angeles'; • Result: • 11 By:-Gourav Kottawar 120
  • 121. • Example 2: • SELECT region_name, Length(region_name) FROM Geography; • Result: By:-Gourav Kottawar region_name Length(regio n_name) East 4 East 4 West 4 West 4 121
  • 122. • 5.Replace(str1, str2, str3): In str1, find where str2 occurs, and replace it with str3. • SELECT REPLACE(region_name, 'ast', 'astern') FROM Geography; By:-Gourav Kottawar region_name Eastern Eastern West West 122
  • 123. • 6. CONCAT • CONCAT(str1, str2, str3, ...): Concatenate str1, str2, str3, and any other strings together. Please note the Oracle CONCAT() function only allows two arguments -- only two strings can be put together at a time using this function. However, it is possible to concatenate more than two strings at a time in Oracle using '||'. By:-Gourav Kottawar 123
  • 124. • SELECT CONCAT(region_name,store_name) FROM Geography WHERE store_name = 'Boston'; • Result: 'EastBoston' • SELECT region_name || ' ' || store_name FROM Geography WHERE store_name = 'Boston'; • Result: 'East Boston' By:-Gourav Kottawar 124