Introduction to Oracle RDBMS and SQL
Introduction to Oracle RDBMS and SQL
**************************************************************************
Oracle as RDBMS, SQL Commands and data types, Operators and Expressions,
Introduction to SQL * Plus, SQL Vs. SQL Plus
**************************************************************************
Table: Customers
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Rahul 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY. [A field is a
column in a table that is designed to maintain specific information about every
record in the table. OR A column is a vertical entity in a table that contains all
information associated with a specific field in a table.]
A record, also called a row of data, is each individual entry that exists in a table.
A NULL value in a table is a value in a field that appears to be blank, which means
a field with a NULL value is a field with no value. It is very important to
understand that a NULL value is different than a zero value or a field that
contains spaces. A field with a NULL value is one that has been left blank during
record creation.
1. The primary goal of a DBMS is to provide a way to store and retrieve database
information that is both convenient and efficient.
2. Database systems are designed to manage large bodies of information.
Management of data involves both defining structures for storage of
information and providing mechanisms for the manipulation of information. In
addition, the database system must ensure the safety of the information stored,
despite system crashes or attempts at unauthorized access. If data are to be
shared among several users, the system must avoid possible anomalous results.
Banking
Airlines
Railway
Universities
Telecommunication
Credit card transactions
Financial Institute
ORACLE as RDBMS
Features:
Concurrency
Read Consistency
Locking Mechanisms
SQL
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in relational database.
***************************************************************************
Query: -
A query is a statement requesting the retrieval of information. The portion of a DML that involves
information retrieval is called a query language.
***************************************************************************
Why SQL?
Allows users to access data in relational database management systems.
Allows users to define the data in database and manipulate that data.
History
1970 -- Dr. E. F. "Ted" of IBM is known as the father of relational databases. He
described a relational model for databases.
Benefits of SQL: -
o Non-Procedural language
o A language for all users
o Unified Language
o Common Language for all RDBMS
o Embedded SQL and Dynamic SQL
Notes:-
All the SQL statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all statements end
with a semicolon (;).
Important point to be noted is that SQL is case insensitive, which means
SELECT and select have same meaning in SQL statements, but MySQL makes
difference in table names. So if you are working with MySQL, then you need to
give table names as they exist in the database.
SQL is followed by unique set of rules and guidelines called Syntax.
WHERE [CONDITION|EXPRESSION];
DUAL is a table automatically created by Oracle database along with the data dictionary. Dual is in
the schema of the user SYS but is accessible by the name DUAL to all users. It has one column,
DUMMY, defined to be VARCHAR2(1), and contains on row with a value X.
**************************************************************************
SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP.
Command Description
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records
MERGE UPSERT operation (insert or update)
CALL Call a PL/SQL or Java subprogram.
EXPLAIN PLAN Explain access path to data
LOCK TABLE Control concurrency.
DQL - Data Query Language
SELECT Retrieves certain records from one or more tables
record from the table, then you are performing transaction on the table. It is
important to control transactions to ensure data integrity and to handle
database errors.
Command Description
COMMIT To save the changes.
ROLLBACK To rollback the changes.
SAVEPOINT Creates points within groups of transactions in which to ROLLBACK.
SET TRANSACTION Places a name on a transaction.
o Transactional control commands are only used with the DML commands
INSERT, UPDATE and DELETE only. They cannot be used while creating tables
or dropping them because these operations are automatically committed in the
database.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the
acronym ACID:
Atomicity: Ensures that all operations within the work unit are completed
successfully; otherwise, the transaction is aborted at the point of failure, and
previous operations are rolled back to their former state.
Consistency: Ensures that the database properly changes states upon a
successfully committed transaction.
Isolation: Enables transactions to operate independently of and transparent to
each other.
Durability: Ensures that the result or effect of a committed transaction persists
in case of a system failure.
**************************************************************************
Note:
In Oracle Documentation Type of SQL Statements section, they have referred to SELECT statement as “a
limited form of DML statement in that it can only access data in the database. It cannot manipulate data
in database, although it can operate on the accessed data before returning the results of the query. ”
Other venders may refer to SELECT as “SQL-Data Statements”, or more appropriately Data Query
Language (DQL).
Manipulation means play with data which means retrieve, store, modify, delete, insert, update, copy etc.
Data types define the type of value that goes into a table column. Every column
has a data type.
You would use these data types while creating your tables. You would choose a
particular data type for a table column based on your requirement.
o VARCHAR is synonymous with the VARCHAR2 data type. Both data type is
used to store alphanumeric data. It is always a good practice to use
VARCHAR2 instead of VARCHAR to avoid behavioral changes. In case of
Varchar the size is defined for each variable at the time of variable
declaration. But in case of Varchar2 Oracle will allocate memory only after
the variable is defined, i.e., Oracle will consider only the actual length of the
string that is stored in a variable for memory allocation rather than the size
that has been given for a variable in the declaration part. So, it is always
good to use VARCHAR2 instead of CHAR data type to optimize the memory
usage. Both varchar and varchar2 can store up to 255 characters.
Note: - Data type might have different names in different database. And even if the name is same, the
size and other details may be different!
ROWID
ROWID data type stores information related to the disk location of table rows.
They also uniquely identify the rows in your table.
The ROWID data type is stored as a hexadecimal.
**************************************************************************************
Operator: –
Arithmetic operators
Comparison operators
Logical operators
a) Airthmatic Operators:-
Example
Operator Description (Assume a=10 &
b=20)
+ (Addition) -Adds values on either side of the operator a + b will give 30
Subtracts right hand operand from left hand
- (Subtraction) a - b will give -10
operand
* (Multiplication) Multiplies values on either side of the operator a * b will give 200
/ (Division) Divides left hand operand by right hand operand b / a will give 2
Divides left hand operand by right hand operand
% (Modulus) b % a will give
and returns remainder
b) Comparison Operator:–
Example
Operator Description
(Assume a=10 & b=20)
Checks if the values of two operands are equal or not, if yes
= (a = b) is not true.
then condition becomes true.
Checks if the values of two operands are equal or not, if values
!= (a != b) is true.
are not equal then condition becomes true.
Checks if the values of two operands are equal or not, if values
<> (a <> b) is true.
are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of
> (a > b) is not true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right
< (a < b) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to
>= (a >= b) is not true.
the value of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the
<= (a <= b) is true.
value of right operand, if yes then condition becomes true.
Checks if the value of left operand is not less than the value of
!< (a !< b) is false.
right operand, if yes then condition becomes true.
Checks if the value of left operand is not greater than the value
!> (a !> b) is true.
of right operand, if yes then condition becomes true.
SQL> SELECT * FROM CUSTOMERS WHERE SALARY SQL> SELECT * FROM CUSTOMERS WHERE SALARY
!= 2000; <> 2000;
ID NAME AGE ADDRESS SALARY ID NAME AGE ADDRESS SALARY
2 Rahul 25 Delhi 1500.00 2 Rahul 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00 4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00 5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00 6 Komal 22 MP 4500.00
7 Muskan 24 Indore 10000.00 7 Muskan 24 Indore 10000.00
c) Logical Operators:–
Operator Description
ALL The ALL operator is used to compare a value to all values in another value set.
The AND operator allows the existence of multiple conditions in an SQL statement's
AND
WHERE clause.
The ANY operator is used to compare a value to any applicable value in the list
ANY
according to the condition.
The BETWEEN operator is used to search for values that are within a set of values,
BETWEEN
given the minimum value and the maximum value.
The EXISTS operator is used to search for the presence of a row in a specified table
EXISTS
that meets certain criteria.
The IN operator is used to compare a value to a list of literal values that have been
IN
specified.
The LIKE operator is used to compare a value to similar values using wildcard
LIKE
operators.
The NOT operator reverses the meaning of the logical operator with which it is used.
NOT
Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
The OR operator is used to combine multiple conditions in an SQL statement's WHERE
OR
clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
The UNIQUE operator searches every row of a specified table for uniqueness (no
UNIQUE
duplicates).
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 SQL> SELECT * FROM CUSTOMERS WHERE
AND SALARY >= 6500; NAME LIKE 'Ko%';
ID NAME AGE ADDRESS SALARY ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500.00 6 Komal 22 MP 4500.00
5 Hardik 27 Bhopal 8500.00
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 SQL> SELECT * FROM CUSTOMERS WHERE AGE
OR SALARY >= 6500; IS NOT NULL;
ID NAME AGE ADDRESS SALARY ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00 1 Ramesh 32 Ahmedabad 2000.00
2 Rahul 25 Delhi 1500.00 2 Rahul 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00 3 Kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00 4 Chaitali 25 Mumbai 6500.00
7 Muskan 24 Indore 10000.00 5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muskan 24 Indore 10000.00
SQL> SELECT * FROM CUSTOMERS WHERE AGE IN SQL> SELECT * FROM CUSTOMERS WHERE AGE
(25, 27); BETWEEN 25 AND 27;
ID NAME AGE ADDRESS SALARY ID NAME AGE ADDRESS SALARY
2 Rahul 25 Delhi 1500.00 2 Rahul 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00 4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00 5 Hardik 27 Bhopal 8500.00
SQL> SELECT * FROM CUSTOMERS WHERE AGE > ALL SQL> SELECT AGE FROM CUSTOMERS WHERE
(SELECT AGE FROM CUSTOMERS WHERE SALARY > EXISTS (SELECT AGE FROM CUSTOMERS
6500); WHERE SALARY > 6500);
ID NAME AGE ADDRESS SALARY AGE
1 Ramesh 32 Ahmedabad 2000.00 32
25
SQL> SELECT * FROM CUSTOMERS WHERE AGE > ANY
(SELECT AGE FROM CUSTOMERS WHERE SALARY > 23
6500); 25
ID NAME AGE ADDRESS SALARY 27
22
1 Ramesh 32 Ahmedabad 2000.00
24
2 Rahul 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
History
SQL Plus is the most basic Oracle Database utility, with a basic command line
interface, commonly used by users, administrators and programmers. The first
version of SQL Plus was called UFI (User Friendly Interface). UFI appeared in
Oracle database release up to version 4. After Oracle programmers had added new
features to UFI, its name became Advanced UFI. The name “Advanced UFI”
changed to “SQL Plus” with the release of version 5 of Oracle.
To start SQL*Plus, select the Run command from the Start menu, enter "sqlplus",
and select the OK button.
To connect to a database, enter the username and password. If necessary, you can
enter the CONNECT command to have SQL*Plus prompt you for a username and
password.
To run a SQL statement, type it, type a semicolon, and press the Enter key.
SELECT statement with WHERE, GROUP BY and HAVING, ORDER BY, DISTINCT
**************************************************************************
You also define Primary Key and other constraints when you create table.
Syntax: – CREATE TABLE table_name( column1 datatype NOT NULL,
column2 datatype,
column3 datatype, ..... ,
columnN datatype,
PRIMARY KEY( one or more columns)
);
Example: –
CREATE TABLE CUSTOMERS( ID NUMBER(4) NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE NUMBER(3) NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
Description of table:
Syntax: - DESC table_name; or Describe table;
Example: - DESC Customer; or Describe Customer;
**************************************************************************
Syntax: – There are two basic syntaxes of INSERT INTO statement as follows:
Example: –
INSERT INTO Teacher (EID, Name, Specialization, Address, MobileNo)
VALUES (1001, Arjun Saxena, C Programming, HNo 177 Mangla Bilaspur,
8794562189);
OR
INSERT INTO Teacher VALUES (1001, Arjun Saxena, C Programming, HNo 177
Mangla Bilaspur, 8794562189);
Example: -
INSERT INTO Teacher (EID, Name, Specialization, Address, MobileNo)
VALUES (&EID, &Name, &Specialization, &Address, &MobileNo);
UPDATE Statement: -
SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause
with UPDATE query to update selected rows, otherwise all the rows would be affected.
Syntax: –
UPDATE table_name SET column1 = value1, column2 = value2....,
columnN = valueN WHERE [condition];
Example: –
UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6;
Work Syntax
The basic syntax of ALTER TABLE to add a new ALTER TABLE table_name ADD
column in an existing table is as follows: column_name datatype;
The basic syntax of ALTER TABLE to DROP ALTER TABLE table_name DROP
COLUMN in an existing table is as follows: COLUMN column_name;
The basic syntax of ALTER TABLE to change the ALTER TABLE table_name MODIFY
DATA TYPE of a column in a table is as follows: column_name datatype;
The basic syntax of ALTER TABLE to change the ALTER TABLE table_name RENAME
Column Name in a table is as follows: COLUMN Old_name TO New_name;
The basic syntax of ALTER TABLE to add a NOT
ALTER TABLE table_name MODIFY
NULL constraint to a column in a table is as
column_name datatype NOT NULL;
follows:
ALTER TABLE table_name ADD
The basic syntax of ALTER TABLE to ADD
CONSTRAINT MyUniqueConstraint
UNIQUE CONSTRAINT to a table is as follows:
UNIQUE(column1, column2...);
The basic syntax of ALTER TABLE to ADD CHECK ALTER TABLE table_name ADD
CONSTRAINT to a table is as follows: CONSTRAINT MyUniqueConstraint
CHECK (CONDITION);
ALTER TABLE table_name ADD
The basic syntax of ALTER TABLE to ADD
CONSTRAINT MyPrimaryKey PRIMARY
PRIMARY KEY constraint to a table is as follows:
KEY (column1, column2...);
ALTER TABLE table_name
The basic syntax of ALTER TABLE to DROP
DROP CONSTRAINT
CONSTRAINT from a table is as follows:
MyUniqueConstraint;
ALTER TABLE table_name DROP
If you're using MySQL, the code is as follows:
INDEX MyUniqueConstraint;
The basic syntax of ALTER TABLE to DROP
ALTER TABLE table_name DROP
PRIMARY KEY constraint from a table is as
CONSTRAINT MyPrimaryKey;
follows:
ALTER TABLE table_name DROP
If you're using MySQL, the code is as follows:
PRIMARY KEY;
ALTER TABLE table_name RENAME TO
SQL ALTER TABLE Statement (Rename)
new_table_name;
Rename Statement:–
Syntax: – RENAME OldName to NewName;
Example: – Rename TEACHER to FACULTY;
DELETE Statement:
SQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause
with DELETE query to delete selected rows, otherwise all the records would be deleted.
Syntax: –
DELETE FROM table_name WHERE {CONDITION};
Example: -
Delete from TEACHER;
Note:
Delete and truncate both commands can be delete data of the table.
Delete is a DML command whereas truncate is a DDL command.
Truncate can be used to delete the entire data of the table without maintaining the integrity of
the table. On the other hand, delete statement can be used for deleting specific data.
*********************************************************
Data Integrity:
The following categories of the data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the format, or
the range of values.
Referential Integrity: Rows cannot be deleted which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into entity, domain,
or referential integrity.
*********************************************************
SQL Constraints:
Constraints are the rules enforced on data columns on table. These are used to
limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the database.
Constraints could be column level or table level. Column level constraints are
applied only to one column, whereas table level constraints are applied to the
whole table.
Example: -
The following SQL creates a new table called CUSTOMERS and adds five columns, three of
which, ID and NAME and AGE, specify not to accept NULLs:
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to
SALARY column in Oracle and MySQL, you would write a statement similar to the
following:
DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example:
If CUSTOMERS table has already been created, then to add a DFAULT constraint to
SALARY column, you would write a statement similar to the following:
UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the CUSTOMERS table, for example, you might want to prevent two or more
people from having identical age.
Example:
The following SQL creates a new table called CUSTOMERS and adds five columns. Here,
AGE column is set to UNIQUE, so that you cannot have two records with same age:
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE,
SALARY);
If you are using MySQL, then you can use the following syntax:
ALTER TABLE CUSTOMERS DROP INDEX myUniqueConstraint;
PRIMARY Key:
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already
exists, use the following SQL syntax:
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).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table
already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a referencing
key.
Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s).
CUSTOMERS table:
CREATE TABLE CUSTOMERS( ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
ORDERS table:
CREATE TABLE ORDERS ( ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table.
ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID) REFERENCES
CUSTOMERS (ID);
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns.
Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18
years:
CREATE TABLE CUSTOMERS( ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you
would write a statement similar to the following:
ALTER TABLE CUSTOMERS MODIFY AGE INT NOT NULL CHECK
(AGE >= 18 );
You can also use following syntax, which supports naming the constraint in multiple columns as well:
To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:
INDEX:
The INDEX is used to create and retrieve data from the database very quickly.
Index can be created by using single or group of columns in a table.
When index is created, it is assigned a ROWID for each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be careful while
creating index.
Selection of fields depends on what you are using in your SQL queries.
Example: For example, the following SQL creates a new table called CUSTOMERS and adds five
columns:
CREATE TABLE CUSTOMERS( ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
Gajendra Chourey Page 25
PRIMARY KEY (ID)
);
Now, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index_name ON table_name ( column1,
column2,...columnN);
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax:
CREATE INDEX idx_age ON CUSTOMERS ( AGE );
*******************************************
SELECT Statement:
o Select * FROM table_name;
WHERE Clause:-
WHERE clause is used to specify a condition while fetching the data from single table or joining
with multiple tables.
If the given condition is satisfied, then only it returns specific value from the table.
You would use WHERE clause to filter the records and fetching only necessary records.
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE
statement, etc.
Distinct Keyword:
DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the
duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While
fetching such records, it makes more sense to fetch only unique records instead of fetching
duplicate records.
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.
TOP:
TOP clause is used to fetch a TOP N number or X percent records from a table.
Syntax: SELECT TOP number|percent column_name(s) FROM table_name WHERE
[condition];
All the databases do not support TOP clause. For example MySQL supports LIMIT clause to fetch
limited number of records and Oracle uses ROWNUM to fetch limited number of records.
ORDER BY Clause: -
Order by clause is used with Select statement for arranging retrieved data in sorted order.
The Order by clause by default sort data in ascending order. Some database sorts query results
in ascending order by default.
Syntax: -
1. SELECT column1, column2....columnN FROM table_name
WHERE CONDITION ORDER BY column_name {ASC|DESC};
2. You can use more than one column in the ORDER BY clause.
SELECT column-list FROM table_name [WHERE condition] [ORDER BY
column1, column2, .. columnN] [ASC | DESC];
Aggregate Functions: -
Aggregate functions take a collection of values and return a single value as a result.
COUNT Function
o The SQL COUNT aggregate function is used to count the number of rows in a database
table.
Example:-
Employee
Id Name Work_date Daily_typing_pages
1 John 2019-01-24 250
2 Ram 2019-05-27 220
3 Jack 2019-05-06 170
3 Jack 2019-04-06 100
4 Jill 2019-04-06 220
5 Zara 2019-06-06 300
5 Zara 2019-02-06 350
Suppose based on the Employee table you want to count total number of rows in this table, then
you can do it as follows:
SELECT COUNT (*) FROM Employee;
Similarly, if you want to count the number of records for Zara, then it can be done as follows:
SELECT COUNT(*) FROM Employee WHERE name="Zara";
Output: - COUNT (*)
2
1 row in set
NOTE: All the SQL queries are case insensitive, so it does not make any difference if you give
ZARA or Zara in WHERE CONDITION.
MAX Function
o The MAX aggregate function allows us to select the highest (maximum) value for a
certain column.
Output: - MAX(daily_typing_pages)
350
You can find all the records with maxmimum value for each name using GROUP BY clause as
follows:
Id Name MAX(daily_typing_pages)
3 Jack 170
4 Jill 220
MIN Function:
o The MIN aggregate function allows us to select the lowest (minimum) value for a certain
column.
Example:- Suppose based on the above table you want to fetch minimum value of
daily_typing_pages, then you can do so simply using the following command:
Output: - MIN(daily_typing_pages)
100
You can find all the records with minimum value for each name using GROUP BY clause as
follows:
SELECT id, name, work_date, MIN(daily_typing_pages) FROM Employee GROUP
BY name;
Output: -
Id Name MIN(daily_typing_pages)
3 Jack 100
4 Jill 220
1 John 250
2 Ram 220
5 Zara 300
You can use MIN Function along with MAX function to find out minimum value as well.
Output: -
AVG Function
o The AVG aggregate function selects the average value for certain table column or SQL
AVG function is used to find out the average of a field in various records.
Example:- Suppose based on the above table you want to calculate average of all the
dialy_typing_pages, then you can do so by using the following command:
Output: - AVG(daily_typing_pages)
230.0000
You can take average of various records set using GROUP BY clause. Following example will take
average all the records related to a single person and you will have average typed pages by every
person.
Output: -
Name AVG(daily_typing_pages
Jack 135.0000
Jill 220.0000
John 250.0000
Ram 220.0000
Zara 325.0000
SUM Function
o The SUM aggregate function allows selecting the total for a numeric column or sum
takes a collection of values and returns the sum of the values.
Example: - Suppose based on the above table you want to calculate total of all the
dialy_typing_pages, then you can do so by using the following command:
You can take sum of various records set using GROUP BY clause. Following example will sum up all
the records related to a single person and you will have total typed pages by every person.
Output: -
Name SUM(daily_typing_pages)
Jack 270
Jill 220
John 250
Note: SQL is based on relational algebra, and QBE and Datalog are based on domain relational
calculus.
Group by clause is used to group the results of a SELECT query based on one or more
columns.
GROUP BY clause is used in collaboration with the SELECT statement to arrange identical
data into groups.
Syntax: -
SELECT column_name, function(column_name) FROM table_name
WHERE condition GROUP BY column_name;
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause. The GROUP BY clause must follow the conditions in the WHERE clause and
must precede the ORDER BY clause if one is used.
CUSTOMERS CUSTOMERS2
ID NAME AGE ADDRESS SALARY ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00 1 Ramesh 32 Ahmedabad 2000.00
2 Suresh 25 Delhi 1500.00 2 Ramesh 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00 3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00 4 Kaushik 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00 5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00 6 Komal 22 MP 4500.00
7 Muskan 24 Indore 10000.00 7 Muskan 24 Indore 10000.00
If you want to know the total amount of salary If you want to know the total amount of salary
on each customer, then GROUP BY query would on each customer, then GROUP BY query would
be as follows: be as follows:
Syntax:
The following is the position of the HAVING clause in a query:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
Syntax: -
Select column_name, function(column_name) FROM table_name
WHERE column_name condition GROUP BY column_name HAVING
function(column_name) condition;
The HAVING clause must follow the GROUP BY clause in a query and must also precede the
ORDER BY clause if used. The following is the syntax of the SELECT statement, including the
HAVING clause:
Syntax:
SELECT column1, column2 FROM table1, table2
WHERE [conditions] GROUP BY column1, column2
HAVING [conditions] ORDER BY column1, column2;
Example: -
Following is the example, which would display record for which similar age count would
be more than or equal to 2:
**************************************************************************
Table: Persons
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Operators:
BETWEEN:
The BETWEEN operator is used in a WHERE clause to select a range of data between two values.
The values can be numbers, text, or dates.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2;
Example:
BETWEEN
SELECT * FROM Persons
WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen';
Output:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
BETWEEN
SELECT * FROM Persons WHERE LastName
BETWEEN 'Hansen' AND 'Svendson';
Output
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
BETWEEN
SELECT * FROM Persons WHERE P_ID
BETWEEN 1 AND 3;
NOT BETWEEN:
The NOT BETWEEN operator is used in a WHERE clause to select a range of data not between
two values. The values can be numbers, text, or dates.
Example:
NOT BETWEEN
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen';
Output:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
NOT BETWEEN
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Svendson';
NOT BETWEEN
SELECT * FROM Persons WHERE P_ID NOT
BETWEEN 1 AND 2 ;
Output:
P_Id LastName FirstName Address City
3 Pettersen Kari Storgt 20 Stavanger
**************************************************************************
IN
The IN operator allows you to specify multiple values in a WHERE clause.
IN allows you to easily test if an expression matches any value in a list of values.
It is used to reduce the need for multiple OR conditions in a SELECT, INSERT, UPDATE, OR DELETE
statement.
Syntax:
SELECT column_name(s) FROM table_name
WHERE column_name IN(value1,value2,...);
Example:
IN
Output
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
IN
SELECT * FROM Persons
WHERE P_ID IN (1,3);
Output
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
NOT IN
IN
SELECT * FROM Persons
WHERE P_ID NOT IN (1,3);
Output:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
**************************************************************************
IS NULL
A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is
one that has been left blank during record creation.
Syntax:
SELECT Column_name(s) FROM table_name
WHERE column_name IS NULL;
Example:
SELECT CustomerName FROM Customers
WHERE Address IS NULL;
IS NOT NULL
Syntax:
SELECT Column_name(s) FROM table_name
WHERE column_name IS NOT NULL;
Example:
SELECT CustomerName FROM Customers
WHERE Address IS NOT NULL;
LIKE
SQL LIKE clause is used to compare a value to similar values using wildcard characters. There are
two wildcards used in conjunction with the LIKE operator:
The percent sign (%)
The underscore (_)
The percent sign represents zero, one, or multiple characters. The underscore represents a single
number or character. The symbols can be used in combinations.
Syntax:
SELECT * FROM table_name
WHERE column LIKE 'XXXX%';
or
SELECT * FROM table_name
WHERE column LIKE '%XXXX%;
or
SELECT * FROM table_name
WHERE column LIKE 'XXXX_';
or
SELECT * FROM table_name
WHERE column LIKE '_XXXX';
or
SELECT * FROM table_name
WHERE column LIKE '_XXXX_';
Example: Here are number of examples showing WHERE part having different LIKE clause with
'%' and '_' operators:
Statement Description
WHERE SALARY LIKE Finds any values that start with 200
'200%'
WHERE SALARY LIKE Finds any values that have 200 in any position
'%200%'
SQL allows the specification of an escape character. The escape character is used immediately
before a special pattern character to indicate that the special pattern character is to be treated like
a normal character. We define the escape character for a like comparison using the escape
keyword.
like ’ab\%cd%’ escape ’\’ matches all strings beginning with “ab%cd”.
like ’ab\\cd%’ escape ’\’ matches all strings beginning with “ab\cd”.
**************************************************************************
SOUNDEX()
The SOUNDEX() function returns a string that contains the phonetic representation of a string.
Example 1:
Output:
A subquery can have only one column in the SELECT clause, unless multiple columns are in the
main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The
GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such
as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB,
or NCLOB.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can
be used within the subquery.
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27);
This would impact two rows and finally CUSTOMERS table would have the following records:
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 125.00
2 Suresh 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 2125.00
6 Komal 22 MP 4500.00
7 Muskan 24 Indore 10000.00
You can rename a table or a column temporarily by giving another name known as alias. The
use of table aliases means to rename a table in a particular SQL statement. The renaming is a
temporary change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular SQL
query.
Oracle:
SELECT [Link], [Link], [Link], [Link] FROM CUSTOMERS C, ORDERS O WHERE [Link] =
[Link];
Alias for Columns: - The following SQL statement creates two aliases, one for the CustomerID
column and one for the CustomerName column:
The following SQL statement creates two aliases. Notice that it requires double quotation marks or
square brackets if the alias name contains spaces:
The following SQL statement creates an alias named "Address" that combine four columns
(Address, PostalCode, City and Country):
Example: - SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City
+ ', ' + Country AS Address FROM Customers;
Example (Oracle): - SELECT Name||' '|| Age ||' '|| Salary AS Customer_table
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
Alias for Tables: - The following SQL statement selects all the orders from the customer with
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the
table aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter):
INNER JOIN
The most frequently used and important of the joins is the INNER JOIN. They are also referred to
as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each
row of table2 to find all pairs of rows which satisfy the join- predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result
row.
Syntax:
Example:
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right
table. This means that if the ON clause matches 0 (zero) records in right table, the join will still
return a row in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from
the right table or NULL in case of no matching join predicate.
Syntax: -
Example: -
RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in left table, the join will still
return a row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from
the left table or NULL in case of no matching join predicate.
FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches
on either side.
Syntax: -
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;
Example: -
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;
SELF JOIN
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
Syntax: -
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Example: -
SELECT [Link], [Link], [Link]
FROM CUSTOMERS a, CUSTOMERS b
WHERE [Link] < [Link];
Result:
Syntax: -
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ];
Example: -
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;
Result: -
ID NAME AMOUNT DATE
1 Ramesh 3000 2009-10-08
1 Ramesh 1500 2009-10-08
1 Ramesh 1560 2009-11-20
1 Ramesh 2060 2008-05-20
2 Khilan 3000 2009-10-08
2 Khilan 1500 2009-10-08
2 Khilan 1560 2009-11-20
**************************************************************************
Union Clause
SQL UNION clause/operator is used to combine the results of two or more SELECT statements
without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number
of column expressions, the same data type, and have them in the same order, but they do not
have to be the same length.
Syntax:-
Syntax:-
SELECT column1 [, column2 ] FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ] FROM table1 [, table2 ]
[WHERE condition];
Example:-
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
LEFT JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID UNION ALL
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
RIGHT JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;
INTERSECT Clause
Syntax: -
SELECT column1 [, column2 ]
FROM table1 [, table2 ] [WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1 [, table2 ] [WHERE condition];
Example: -
EXCEPT Clause
The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows
from the first SELECT statement that are not returned by the second SELECT statement. This
means EXCEPT returns only rows, which are not available in second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator.
MySQL does not support EXCEPT operator.
Syntax: -
SELECT column1 [, column2 ]
FROM table1 [, table2 ][WHERE
condition]
EXCEPT
SELECT column1 [, column2 ]
************************************************************************
You can change the default Date format of oracle from “DD-MM-YYYY” to
something you like by issuing the following command:
************************************************************************
Initcap()
The initcap() function converts the first letter of each word in a string to upper case, and
converts any remaining characters in each word to lowercase.
Output:
UPPER(str)/UCASE(str)
Output:
LOWER(str)/ LCASE(str)
LOWER('QUADRATICALLY')
quadratically
LENGTH(str)
Returns the length of the string str measured in bytes. A multi-byte character counts as
multiple bytes. This means that for a string containing five two-byte characters,
LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
LENGTH(‘text’)
4
Example 2:
SELECT LENGTH(ename) from employee where eno='E33';
RTRIM(str)
LTRIM(str)
LTRIM(' barbar')
barbar
LPAD(str,len,padstr)
Returns the string str, left-padded with the string pad str to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
LPAD('hi',4,'??')
??hi
RPAD(str,len,padstr)
Returns the string str, right-padded with the string pad str to a length of len characters.
If str is longer than len, the return value is shortened to len characters.
RPAD('hi',5,'?')
hi???
CONCAT (str1,str2)
Returns the string that results from concatenating the arguments. May have one or more
arguments. If all arguments are non-binary strings, the result is a non-binary string. If
the arguments include any binary strings, the result is a binary string. A numeric
argument is converted to its equivalent binary string form; if you want to avoid that, you
can use an explicit type cast, as in this:
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the
string to_str. REPLACE() performs a case-sensitive match when searching for
from_str.
REPLACE('[Link]', 'w','Ww')
[Link]
REVERSE(str)
Returns the string str with the order of the characters reversed.
REVERSE('abcd')
dcba
ASCII(str)
Returns the numeric value of the leftmost character of the string str. Returns 0 if str is
the empty string. Returns NULL if str is NULL. ASCII() works for characters with
numeric values from 0 to 255.
ASCII('2')
50
************************************************************************
ABS(X)
The ABS() function returns the absolute value of X. Consider the following
SQRT(X)
This function returns the non-negative square root of X. Consider the following
example:
CEIL(X) / CEILING(X)
These functions return the smallest integer value that is not smaller than X. Consider
the following
FLOOR(X)
This function returns the largest integer value that is not greater than X.
ROUND(X) / ROUND(X, D)
This function returns X rounded to the nearest integer. If a second argument, D, is
supplied, then the function returns X rounded to D decimal places. D must be positive or
all digits to the right of the decimal point will be removed. Consider the following
example:
SELECT ROUND(3.46796) from dual;
SIGN(X)
This function returns the sign of X (negative, zero, or positive) as -1, 0, or 1.
SELECT SIGN(-3.46) from dual;
STD(expression) / STDDEV(expression)
The STD() function is used to return the standard deviation of expression. This is
equivalent to taking the square root of the VARIANCE() of expression. The following
example computes the standard deviation of the PRICE column in our CARS table:
GREATEST(n1,n2,n3,..........)
The GREATEST() function returns the greatest value in the set of input parameters (n1,
n2, n3, a nd so on). The following example uses the GREATEST() function to return the
largest number from a set of numeric values:
LEAST(N1,N2,N3,N4,......)
The LEAST() function is the opposite of the GREATEST() function. Its purpose is to
return the least-valued item from the value list (N1, N2, N3, and so on). The following
example shows the proper usage and output for the LEAST() function:
EXP(X)
This function returns the value of e (the base of the natural logarithm) raised to the
power of X.
LOG(B,X)
The single argument version of the function will return the natural logarithm of X. If it is
called with two arguments, it returns the logarithm of X for an arbitrary base B. Consider
the following example:
SELECT LOG(2,45) FROM DUAL;
MOD(N,M)
This function returns the remainder of N divided by M. Consider the following
example:
SELECT MOD(29,3) FROM DUAL;
************************************************************************
SYSDATE
Return the current system date and time of the operating system where the Oracle
Database resides.
CURRENT_DATE
Return the current date and time in the session time zone.
CURRENT_TIMESTAMP
Return the current date and time with time zone in the session time zone.
ADD_MONTHS
Add a number of months (n) to a date and return the same day which is n of months
away.
EXTRACT
Extract a value of a date time field e.g., YEAR, MONTH, DAY, … from a date time value.
FROM_TZ
Convert a timestamp and a time zone to a TIMESTAMP WITH TIME ZONE value.
LAST_DAY
Gets the last day of the month of a specified date.
LOCALTIMESTAMP
Return a TIMESTAMP value that represents the current date and time in the session time
zone.
MONTHS_BETWEEN
Example:
SELECT MONTHS_BETWEEN( DATE '2021-07-01', DATE '2021-01-01' )FROM DUAL;
Result:
NEW_TIME
Convert a date in one time zone to another.
NEXT_DAY
Get the first weekday that is later than a specified date.
ROUND
Return a date rounded to a specific unit of measure.
SESSIONTIMEZONE
Get the session time zone.
SYSTIMESTAMP
Return the system date and time that includes fractional seconds and time zone.
TO_CHAR
Convert a DATE or an INTERVAL value to a character string in a specified format.
TO_DATE
Convert a date which is in the character string to a DATE value.
Example: SELECT TO_DATE( '01 Jan 2021', 'DD MON YYYY' ) FROM DUAL;
Result:
TRUNC
Return a date truncated to a specific unit of measure.
Example: SELECT TRUNC(DATE '2017-07-16', 'MM') FROM DUAL;
Result:
TZ_OFFSET
Get time zone offset of a time zone name from UTC.
Syntax: TZ_OFFSET('timezone')
To find more time zone values, you can run the following query:
SELECT DISTINCT tzname FROM V$TIMEZONE_NAMES;
************************************************************************
1. NVL(expr1, expr2):
o In SQL, NVL() converts a null value to an actual value.
o Data types that can be used are date, character and number.
o Data type must match with each other i.e. expr1 and expr2 must of same
data type.
3. DECODE():
o Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-
ELSE statement.
o The DECODE function decodes an expression in a way similar to the IF-
THEN-ELSE logic used in various languages.
o The DECODE function decodes expression after comparing it to each search
value. If the expression is the same as search, result is returned.
o If the default value is omitted, a null value is returned where a search
value does not match any of the result values.
6. LNNVL():
o LNNVL evaluate a condition when one or both operands of the condition
may be null.
o The function can be used only in the WHERE clause of a query. It takes as
an argument a condition and returns TRUE if the condition is FALSE or
UNKNOWN and FALSE if the condition is TRUE.
o Now the above examples does not considered those employees who have no
commission at all.
o To include them as well we use LNNVL()
Gajendra Chourey Page 69
SELECT COUNT(*) FROM employee WHERE LNNVL(commission >= 500.00);
7. NANVL() :
o The NANVL function is useful only for floating-point numbers of type
BINARY_FLOAT or BINARY_DOUBLE.
o It instructs the Database to return an alternative value n2 if the input
value n1 is NaN (not a number). If n1 is not NaN, then database returns n1.
This function is useful for mapping NaN values to NULL.
Syntax: NANVL( n1 , n2 );
Example:
SELECT bin_float, NANVL(bin_float,0) FROM nanvl_demo;
Output:
Cause of Anomalies:
Anomalies are caused when there is too much redundancy in the database’s information.
Anomalies can often be caused when the tables that make up the database suffer from poor
construction.
Insertion Anomaly:
o An insertion anomaly is the inability to add data to the database due to absence of other
data.
o An insertion/Insert Anomaly occurs when certain attributes cannot be inserted into the
database without the presence of other attributes.
o For example, assume in Student table, Enrolment_Number column is defined as Not
NULL. If a new student is admitted but not immediately assigned enrolment number
then this student could not be entered into the database.
Deletion Anomaly:
o A deletion anomaly occurs when you delete record that may contain attributes that
shouldn’t be deleted.
o A deletion anomaly is the unintended loss of data due to deletion of other data.
Update Anomaly:
o An update anomaly is a data inconsistency that results from data redundancy and a
partial update.
**************************************************************************************
Views, which are kind of virtual tables, allow users to do the following:
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data such that a user can see and (sometimes) modify exactly what they need
and no more.
Summarize data from various tables which can be used to generate reports.
Creating View: -
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables, or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
You can include multiple tables in your SELECT statement in very similar way as you use them in normal SQL
SELECT query.
Example: -
CUSTOMERS
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muskan 24 Indore 10000.00
Now, following is the example to create a view from CUSTOMERS table. This view would be used to
have customer name and age from CUSTOMERS table:
Example:
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age FROM CUSTOMERS;
The following is an example of creating same view CUSTOMERS_VIEW with the WITH CHECK OPTION:
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE
column, because the view is defined by data that does not have a NULL value in the AGE column.
CUSTOMERS
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muskan 24 Indore 10000.00
This would ultimately delete a row from the base table CUSTOMERS and same would reflect in
the view itself. Now, try to query base table, and SELECT statement would produce the
following:
Result:
CUSTOMERS
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muskan 24 Indore 10000.00
Dropping Views:
Obviously, where you have a view, you need a way to drop the view if it is no longer
needed. The syntax is very simple as given below:
*********************************************************************************
The OR REPLACE phrase in the PL-SQL create synonym syntax above allows us to replace or
recreate any PL-SQL synonym (if already existing) for the same database object and without
using the drop command.
The PUBLIC phrase in the above PL-SQL create synonym syntax means that the synonym will be
accessible for all the valid users, but the user must have the sufficient privileges for the object to
use its synonym.
The SCHEMA phrase in the PL-SQL create synonym is the name of the schema where the
synonym will reside. It is an optional phrase, if omitted; oracle PL-SQL creates the synonym in
the current schema.
The SYNONYM_NAME in the above PL-SQL create synonym syntax is the name of the synonym.
The OBJECT_NAME in the above PL-SQL create synonym syntax is the name of the database
object for which the synonym is to be created.
Once we run the above PL-SQL CREATE SYNONYM command we can fetch the records of the
employee table as:
If the ‘employee_syn’ synonym already existed we can replace the synonym using the CREATE
OR REPLACE SYNONYM as:
The PUBLIC phrase in the above oracle PL-SQL drop synonym syntax allows us to drop a
public synonym, if we have specified public then we don’t have to specify a schema for the
PL-SQL synonym.
The FORCE phrase in the above oracle PL-SQL drop synonym syntax will drop the synonym
even if there are dependencies on it.
Example:
The above PL-SQL drop synonym command will drop the synonym ‘employee_syn’ from
the database.
*********************************************************************************
Index
Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table.
An index in a database is very similar to an index in the back of a book. For example, if
you want to reference all pages in a book that discuss a certain topic, you first refer to the
index, which lists all topics alphabetically and are then referred to one or more specific
page numbers.
An index helps speed up SELECT queries and WHERE clauses, but it slows down data
input, with UPDATE and INSERT statements.
Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the
index, to specify the table and which column or columns to index, and to indicate whether
the index is in ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there's an index.
Indexes should not be used on columns that contain a high number of NULL
values.
Single-Column Indexes:
A single-column index is one that is created based on only one table column.
The basic syntax is as follows:
Unique Indexes:
Unique indexes are used not only for performance, but also for data integrity. A
unique index does not allow any duplicate values to be inserted into the table.
The basic syntax is as follows:
Composite Indexes:
A composite index is an index on two or more columns of a table.
The basic syntax is as follows:
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter
conditions.
Should there be only one column used, a single-column index should be the choice. Should
there be two or more columns that are frequently used in the WHERE clause as filters, the
composite index would be the best choice.
Implicit Indexes:
Implicit indexes are indexes that are automatically created by the database
server when an object is created.
*********************************************************************************
COMMIT Command:
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
Syntax: - COMMIT;
Example: - Following is the example, which would delete records from the table having age = 25 and
then COMMIT the changes in the database.
ROLLBACK Command:
The ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database.
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
Syntax: - ROLLBACK;
Example: - Following is the example, which would delete records from the table having age = 25
and then ROLLBACK the changes in the database.
SAVEPOINT Command: -
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point
without rolling back the entire transaction.
Syntax: - SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.
Example: - Following is an example where you plan to delete the three different records from
the CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state:
Now that the three deletions have taken place, say you have changed your mind and decided
to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the
first deletion, the last two deletions are undone:
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo
transactions performed since the SAVEPOINT.
*********************************************************
Creating a User
Example:
Here we’re simply creating a books_admin account that is IDENTIFIED or authenticated by the
specified password.
GRANT Statement: -
With our new books_admin account created, we can now begin adding privileges to the account using
the GRANT statement.
GRANT is a very powerful statement with many possible options, but the core functionality is to
manage the privileges of both users and roles throughout the database.
Providing Roles
Typically, you’ll first want to assign privileges to the user through attaching the account to
various roles, starting with the CONNECT role:
In some cases to create a more powerful user, you may also consider adding
the RESOURCE role (allowing the user to create named types for custom schemas) or even
Gajendra Chourey Page 91
the DBA role, which allows the user to not only create custom named types but alter and
destroy them as well.
Assigning Privileges:
Next you’ll want to ensure the user has privileges to actually connect to the database and
create a session using GRANT CREATE SESSION.
We also need to ensure our new user has disk space allocated in the system to actually
create or modify tables and data, so we’ll GRANT TABLESPACE like so:
Table Privileges:
While not typically necessary in newer versions of Oracle, some older installations may
require that you manually specify the access rights the new user has to a specific schema
and database tables.
For example, if we want our books_admin user to have the ability to perform SELECT,
UPDATE, INSERT, and DELETE capabilities on the books table, we might execute the
following GRANT statement:
This ensures that books_admin can perform the four basic statements for the books table
that is part of the schema schema.
REVOKE: -
The REVOKE command removes user access rights or privileges to the database objects.
This command will REVOKE a SELECT privilege on employee table from Ravi.
DROP USER: -
Example:
The following statements could be run at midnight of the last day of every
month to count the products and quantities on hand in the Toronto warehouse
in the sample Order Entry (oe) schema. This report would not be affected by any
other user who might be adding or removing inventory to a different
warehouse.
COMMIT;
COMMIT;
Note:-
DELETE is used to remove existing records from the database. DELETE command is a DML statement so that it can
be rolled back.
DROP is used to delete the whole table, including its structure. DROP is a DDL command that lost the data
permanently, and it cannot be rolled back.
TRUNCATE is used to delete the whole records, but it preserves the table's schema or structure. TRUNCATE is a
DDL command, so it cannot be rolled back.