Professional Documents
Culture Documents
Database System 1 Lab
Database System 1 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
• SQLBy:-Gourav
can set permissions on tables, procedures, and views
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:
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
Data Type Syntax Explanation (if applicable)
By:-Gourav Kottawar 9
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).
By:-Gourav Kottawar 10
Data type Range Storage
- 1.79E+308 to -2.23E-
Depends on the value of
float 308, 0 and 2.23E-308 to
n
1.79E+308
- 3.40E + 38 to -1.18E -
real 38, 0 and 1.18E - 38 to 4 Bytes
3.40E + 38
By:-Gourav Kottawar 11
Where x is the number of
characters to store. This data type
character char(x)
is space padded to fill the number
of characters specified.
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
By:-Gourav Kottawar 14
NUMBER(12.4) => 12.4
• 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
P_Id LastName FirstName Address City
The table above contains three records (one for each person) and
five columns (P_Id, LastName, FirstName, Address, and City).
By:-Gourav Kottawar 16
• 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
• 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:
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
By:-Gourav Kottawar varchar(255), 25
City varchar(255),
CONSTRAINT uc_PersonsId UNIQUE (P_Id,LastName)
• 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)
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)
)
City varchar(255)
)
• 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);
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
PERSONS TABLE
ORDERS TABLE
By:-Gourav Kottawar 34
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.
By:-Gourav Kottawar 35
• 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
By:-Gourav Kottawar 39
• ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id);
By:-Gourav Kottawar 40
SQL> drop table room;
Table dropped.
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')
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.
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:
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
• And
By:-Gourav Kottawar 53
P_Id LastName FirstName Address City
Timoteivn
1 Hansen Ola Sandnes
10
By:-Gourav Kottawar 54
• SELECT LastName,FirstName FROM Persons
• The result-set will look like this:
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
By:-Gourav Kottawar 55
• The SQL SELECT DISTINCT Statement
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:
P_Id LastName FirstName Address City
Timoteivn
1 Hansen Ola Sandnes
10
By:-Gourav Kottawar 59
• This is correct:
This is wrong:
By:-Gourav Kottawar 60
• This is correct:
This is wrong:
By:-Gourav Kottawar 61
• Operators Allowed in the WHERE Clause
• With the WHERE clause, the following operators can be
used:
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
By:-Gourav Kottawar
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:
By:-Gourav Kottawar 63
• The result-set will look like this:
P_Id LastName FirstName Address City
By:-Gourav Kottawar 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:
By:-Gourav Kottawar 65
P_Id LastName FirstName Address City
By:-Gourav Kottawar 66
• SELECT * FROM Persons WHERE
LastName='Svendson'
AND (FirstName='Tove' OR FirstName='Ola');
• 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
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
• Using the % Wildcard
LIKE Operator
• 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:
FirstNam
P_Id LastName Address City
e
1 Hansen Ola Timoteivn 10 Sandnes
By:-Gourav Kottawar 74
• 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
• 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
• 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 78
• 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!
5
By:-Gourav Kottawar Tjessem Jakob 80
• 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‘;
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
By:-Gourav Kottawar 81
• 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
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.
• 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
By:-Gourav Kottawar 86
• This is correct:
This is wrong:
This is wrong:
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
By:-Gourav Kottawar 88
• 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:
P_Id LastName FirstName Address City
3
By:-Gourav Kottawar Pettersen Kari Storgt 20 Stavanger 89
• 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:
By:-Gourav Kottawar 90
• 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:
By:-Gourav Kottawar 91
• 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
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":
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
• 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.
Timoteivn
1 Hansen Ola Sandnes
10
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:
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen
By:-Gourav Kottawar
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
• 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
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
• Example 1:
• SELECT TRIM(' Sample ') from tablename;
• Result:
• 'Sample'
• Example 3:
• SELECT RTRIM(' Sample ');
• Result:
• ' Sample'
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
Length(region_
region_name
name)
East 4
East 4
West 4
By:-Gourav Kottawar West 4 121
• 5.Replace(str1, str2, str3): In str1, find where str2 occurs, and
replace it with str3.
region_name
Eastern
Eastern
West
West
By:-Gourav Kottawar 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 '||'.