Unit 2 Advanced SQL
Unit 2 Advanced SQL
1. Char
The char datatype consist character as alpha, numeric and alpha-numeric.
Capacity :
255 bytes Default and minimum size is 1 byte.
Syntax :
Fieldname Char(size)
2. Varchar
The varchar datatype consist character as alpha, numeric and alpha-numeric.
Capacity :
2000 bytes
Syntax :
Fieldname Varchar(size)
3. Varchar2
The varchar2 datatype consist character as alpha, numeric and alpha-numeric.
Capacity :
4000 bytes
Syntax :
Fieldname Varchar2(size)
4. Number
The number datatype consists only numeric.
Capacity :
38 digit
Syntax :
Fieldname number(p) p – precision
Fieldname number(p,s) p – precision, s – scale
Example:
Fieldname Number(7,2) 50000.20 7– precision and 2 – scale
5. Date
The date datatype consist only date in proper oracle format.
Format : dd-mon-yyyy
Syntax: Date
6. Blob
BLOB data type same as BFILE data type to store unstructured binary object into Operating
System file. BLOB type fully supported transactions are recoverable and replicated Capacity.
Capacity :
the blob capacity is system dependent
Syntax :
Fieldname blob(size)
8. CLOB
CLOB stands for character large object. You use CLOB to store single-byte or multibyte
characters with the maximum size is 4 gigabytes
Note that CLOB supports both fixed-with and variable-with character sets.
9. NCLOB
NCLOB is similar to CLOB except that it can store the Unicode characters.
10. LONG
This data type is used to store large text data up to the maximum size of 2GB. These are
mainly used in the data dictionary.
LONG data type is used to store character set data.
ROWID Pseudocolumn
For each row in the database, the ROWID pseudocolumn returns the address of the row.
Oracle Database rowid values contain information necessary to locate a row:
The data object number of the object
The data block in the data file in which the row resides
The position of the row in the data block (first row is 0)
The data file in which the row resides (first file is 1). The file number is relative to the
tablespace.
Usually, a rowid value uniquely identifies a row in the database. However, rows in different
tables that are stored together in the same cluster can have the same rowid.
Values of the ROWID pseudocolumn have the data type ROWID or UROWID. Refer to
"Rowid Data Types" and "UROWID Data Type" for more information. Rowid values have
several important uses:
They are the fastest way to access a single row.
They can show you how the rows in a table are stored.
They are unique identifiers for rows in a table.
You should not use ROWID as the primary key of a table. If you delete and reinsert a row
with the Import and Export utilities, for example, then its rowid may change. If you delete a
row, then Oracle may reassign its rowid to a new row inserted later. Although you can use the
ROWID pseudocolumn in the SELECT and WHERE clause of a query, these pseudocolumn
values are not actually stored in the database. You cannot insert, update, or delete a value of
the ROWID pseudocolumn.
Example This statement selects the address of all rows that contain data for employees in
department 20:
SELECT ROWID, last_name FROM employees WHERE department_id = 20;
DUAL Table
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 one row with a value
X. Selecting from the DUAL table is useful for computing a constant expression with the
SELECTstatement. Because DUAL has only one row, the constant is returned only once.
2|Page
Unit – 2 Advanced SQL
Alternatively, you can select a constant, pseudocolumn, or expression from any table, but the
value will be returned as many times as there are rows in the table.
An example of using the DUAL table would be:
SYSDATE
03/JUL/16
Functions
Scalar functions (in contrast to data functions) do not aggregate data or compute aggregate statistics.
Instead, scalar functions compute and substitute a new data value for each value associated with a data
item.
String Scalar Functions Description
Ascii (s) Returns an ASCII numeric representation
of string s.
Example:
Ascii ("AZ") = 65
Concat (s1, s2) Returns text strings s1 and s2
concatenated.
Example:
Concat ("interactive","reporting") =
interactivereporting
Initcap (s) Returns string s with the first letter of each
word capitalized, and remaining characters
in lower case.
Example:
Initcap ("santa fe") = Santa Fe
Instr (s1,s2,n,m) Returns position of mth occurrence of
string s2 in string s1, beginning at position
number n. If n is negative, the count is
made backwards from the end of s1. If no
values are found, 0 is returned.
Examples:
Instr ("Mississippi",'s',5,2) = 7
Instr ( City, 'a', -2, 1 )
Length (s) Returns character count of string s.
Example:
Length ("Pittsburgh") = 10
Lower (s) Returns string s in lower case.
Example:
Lower ("CD-Rom") = cd-rom
Ltrim (s1,s2) Trims string s1 from the left, up to the first
character not included in string s2.
Example:
Ltrim ("Mr. Jones", "Mr. ") = Jones
Replace (s1,s2,s3) Returns string item s1 with all occurrences
of string s2 replaced by string s3. The
default for s3 deletes each occurrence of
s2.
Example:
Replace (customer,"Mrs.","Ms.") =
replaces Mrs. with Ms. for all values of
customer containing `Mrs.'
3|Page
Unit – 2 Advanced SQL
5|Page
Unit – 2 Advanced SQL
create table orders(oid number primary key,cid number,constraint fine foreign key(cid)
references customer(cid),prod_nm varchar(15),order_date date);
INDEX
6|Page
Unit – 2 Advanced SQL
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 discusses a certain topic, you
first refer to the index, which lists all the topics alphabetically and are then referred to one or
more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data
input, with the UPDATE and the 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 an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate
entries in the column or combination of columns on which there is an index.
The CREATE INDEX Command
The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name (COLUMN_NAME);
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as
follows.
CREATE INDEX index_name
ON table_name (column_name);
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.
CREATE UNIQUE INDEX index_name on table_name (column_name);
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as
follows.
CREATE INDEX index_name
On table_name (column1, column2);
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.
7|Page
Unit – 2 Advanced SQL
Indexes should not be used on columns that contain a high number of NULLvalues.
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them. Different types of Joins are as follows:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
8|Page
Unit – 2 Advanced SQL
StudentCourse
table1: First table. table2: Second table matching_column: Column common to both the
tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
Example Queries(INNER JOIN) This query will show the names and age of students
enrolled in different courses.
9|Page
Unit – 2 Advanced SQL
Output:
B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the
table on the right side of the join. For the rows for which there is no matching row on the
right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
table1: First table. table2: Second table matching_column: Column common to both the
tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.
Output:
10 | P a g e
Unit – 2 Advanced SQL
C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right
side of the join and matching rows for the table on the left side of the join. For the rows for
which there is no matching row on the left side, the result-set will contain null. RIGHT JOIN
is also known as RIGHT OUTER JOIN.
table1: First table. table2: Second table matching_column: Column common to both the
tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.
Output:
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both tables. For the rows for which there
is no matching, the result-set will contain NULL values.
table1: First table. table2: Second table matching_column: Column common to both the tables.
11 | P a g e
Unit – 2 Advanced SQL
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
An alternative way of achieving the same result is to use column names separated by commas
after SELECT and mentioning the table names involved, after a FROM clause.
12 | P a g e
Unit – 2 Advanced SQL
To get item name and item unit columns from foods table and company name, company city
columns from company table, after a CROSS JOINING with these mentioned tables, the following
SQL statement can be used:
13 | P a g e
Unit – 2 Advanced SQL
14 | P a g e
Unit – 2 Advanced SQL
MySQL Subquery
A subquery in MySQL is a query, which is nested into another SQL query and embedded
with SELECT, INSERT, UPDATE or DELETE statement along with the various operators.
We can also nest the subquery with another subquery. A subquery is known as the inner
query, and the query that contains subquery is known as the outer query. The inner query
executed first gives the result to the outer query, and then the main/outer query will be
performed. MySQL allows us to use subquery anywhere, but it must be closed within
parenthesis. All subquery forms and operations supported by the SQL standard will be
supported in MySQL also.
Let us understand it with the help of an example. Suppose we have a table named
"employees" that contains the following data:
15 | P a g e
Unit – 2 Advanced SQL
Following is a simple SQL statement that returns the employee detail whose id matches in a
subquery:
SELECT emp_name, city, income FROM employees
WHERE emp_id IN (SELECT emp_id FROM employees);
Let us see an example of another comparison operator, such as equality (=) to find employee
details with maximum income using a subquery.
It will give the output where we can see two employees detail who have maximum income.
16 | P a g e
Unit – 2 Advanced SQL
Syntax:
INSERT INTO table_name
SELECT *
FROM table_name
WHERE VALUE OPERATOR
To understand more clearly let's take the above mentioned Employee table and also consider
that a new employee table i.e. EmployeeNew is available in the database and run the below
mentioned query and observe the output.
Example:
INSERT INTO EmployeeNew
SELECT * FROM Employee
WHERE emp_id IN (
SELECT emp_id
FROM Employee );
The final result of the above query i.e. the EmployeeNew table would look like below:
17 | P a g e
Unit – 2 Advanced SQL
EmployeeNew:
121 | Lisa Carol | 27 | Finance |30000 | USA |
122 | Farooq Shaikh | 29 | HR| 20000 | USA |
123 | Nastya Henry | 28 | Technology | 45000 | UK |
124 | Christine Maybach | 30 | Research | 50000 | USA|
125 | Ryan Renolds | 27 | Research | 50000 | Canada |
Here, the EmployeeNew table is empty and the above query copies all the columns from the
Employee table to the EmployeeNew table. Let's break the query statements to understand
clearly.
The INSERT statement specifies that the new data is added to this table i.e. EmployeeNew
table. As we are copying all the data from the Employee table to the EmployeeNew table,
there is no need to specify the column name in the INSERT statement otherwise you would
need to mention the column name in which you want to add the data.
Syntax:
UPDATE Employee
SET column_name = new_value
WHERE Operator (
SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE ... );
To understand more clearly let's take the above mentioned Employee table and also consider
that a new employee table i.e. EmployeeNew is available in the database and run the below
mentioned query and observe the output.
Example:
UPDATE Employee
SET emp_salary = emp_salary * 2
WHERE emp_age IN (
SELECT emp_age
FROM EmployeeNew
WHERE emp_age > 27 );
The final result of the above query would look like the below:
Employee:
| 121 | Lisa Carol | 27 | Finance | 30000 | USA |
| 122 | Farooq Shaikh | 29 | HR | 40000 | USA |
| 123 | Nastya Henry | 28 | Technology | 90000 | UK |
| 124 | Christine Maybach | 30 | Research | 100000|USA |
| 125 | Ryan Renolds | 27 | Research | 50000 | Canada |**
In this example, the Employee table is updated using UPDATE and SET. Here, the SET
clause defines the new value for the emp_salary column which is being modified by the
18 | P a g e
Unit – 2 Advanced SQL
UPDATE statement. As you can see in the subquery, the employees having age greater than
27 are filtered out and this result set is passed on to the outer query. The outer query updates
the emp_salary column while considering the result set of the subquery i.e. salary of all the
Employees having an age greater than 27 will increase by two times as mentioned in the outer
query.
To understand more clearly let's take the above mentioned Employee table and also consider
that a new employee table i.e. EmployeeNew is available in the database that is mentioned
above in the article and run the below mentioned query and observe the output.
The final result of the above query i.e. the Employee table would look like the below:
| 121 | Lisa Carol | 27 | Finance | 30000 | USA |
| 122 | Farooq Shaikh | 29 | HR | 20000 | USA |
| 123 | Nastya Henry | 28 | Technology | 45000 | UK |
In this example, the DELETE statement is used to delete the rows from the Employee table
with the help of EmployeeNew table. Firstly, the subquery is executed and the employees
from the EmployeeNew table whose department is "Research" are fetched out and this result
set is passed on to the outer query.
The outer query then deletes the records from the Employee table who is in the Research
department. Note that not all the records that are present in the EmployeeNew and Employee
table are deleted but only those records or employees who are in the Research department are
deleted.
create table orders(oid number primary key,cid number,constraint fine foreign key(cid)
references customer(cid),prod_nm varchar(15),order_date date);
select nm from customer where cid not in (select cid from orders);
20 | P a g e
Unit – 2 Advanced SQL
6) update deptdetails set empid=(select empid from empdetails where empid=105) where
empid=106;
7) delete from deptdetails where empid not in (select empid from empdetails);
21 | P a g e