SQL II Topic
SQL II Topic
SQL II Topic
Most of these have provided their own implementation extensions, thus enhancing
their RDBMS system features and making it a powerful tool. These RDBMS
systems, all use the popular SQL commands SELECT, UPDATE, DELETE, INSERT,
WHERE in similar format.
DDL Commands –
Create - Drop - Alter - Rename - Truncate
Name
Data type
Size(column width).
Each table column definition is a single clause in the create table syntax. Each table column
definition is separated from the other by a comma. Finally, the SQL statement is terminated
with a semicolon.
Syntax:
DROP TABLE <table_name>
Example:
DROP TABLE Student;
It will destroy the table and all data which will be recorded in it.
Syntax:
TRUNCATE TABLE <Table_name>
Example:
TRUNCATE TABLE Student;
Syntax:
RENAME <OldTableName> TO <NewTableName>
Example:
RENAME <Student> TO <Stu>
The old name table was Student now new name is the Stu.
The ALTER Table Command
By The use of ALTER TABLE Command we can modify our exiting table.
Syntax:
ALTER TABLE <table_name>
ADD (<NewColumnName> <Data_Type>(<size>),......n)
Example:
ALTER TABLE Student ADD (Age number(2), Marks number(3));
The Student table is already exist and then we added two more
columns Age and Marks respectively, by the use of above command.
Syntax:
ALTER TABLE <table_name> DROP COLUMN <column_name>
Example:
ALTER TABLE Student DROP COLUMN Age;
Syntax:
ALTER TABLE <table_name> MODIFY (<column_name> <NewDataType>(<NewSize>))
Example:
ALTER TABLE Student MODIFY (Name Varchar2(40));
The Name column already exist in Student table, it was char and size 30, now it is modified by
Varchar2 and size 40.
-------------------------------------------------------------------------------------
DML Commands –
Select - Insert - Update - Delete
Once data has been inserted into a table, the next most logical operation would
be to view what has been inserted. The SELECT SQL verb is used to achieve this.
eg: Select * from Student; It will show all the table records.
Note : Character expression placed within the insert into statement must be
enclosed in single quotes (').
DELETE Operation:
The DELETE command can remove all the rows from the table or a set of rows from the table.
eg: DELETE FROM student; It will DELETE all the rows from student table.
eg: DELETE FROM student WHERE reg_no='A101'; If condition will be satisfied then it will delete
a row from the table Register number A101 will be deleted from the table
If you want to delete table column then use ALTER TABLE command.
eg : ALTER TABLE student DROP COLUMN dob; The DOB column will be
deleted from the student table.
UPDATE Operation:
The UPDATE command is used to change or modify data values in a table and UPDATE
command can Update all the rows from the table or a set of rows from the table.
Course is a column name, suppose ant time you want to update something like that in
the student table course should be MCA for all students then you can use this type of
query. It will update all the rows in the table all rows will have MCA course.
you can use different-different types of condition in WHERE clause, eg salary updation, if salary has
increased someone's then simply multiply, addition you can do in salary column.
I will show example. Suppose someone's has increased salary by 10% then what should to do. See
example:
So SQL offers a feature called WHERE clause, which we can use to restrict the data
that is retrieved. The condition you provide in the WHERE clause filters the rows
retrieved from the table and gives you only those rows which you expected to see.
WHERE clause can be used along with SELECT, DELETE, UPDATE statements.
For Example: If you want to sort the employee table by salary of the employee,
the sql query would be.
SELECT name, salary FROM employee ORDER BY salary;
The query first sorts the result according to name and then displays it.
You can also use more than one column in the ORDER BY clause.
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort
the data in descending order, you must explicitly specify it as shown below.
FROM employee
The above query sorts only the column 'salary' in descending order and the column
'name' by ascending order.
If you want to select both name and salary in descending order, the query would be
as given below.
FROM employee
The constraints available in SQL are Foreign Key,Not Null, Unique, Check.
Constraints can be defined in two ways
1) The constraints can be specified immediately after the column definition. This is
called column-level definition.
2) The constraints can be specified after all the columns are defined. This is called
table-level definition.
1) SQL Primary key:
This constraint defines a column or combination of columns which uniquely
identifies each row in the table.
(column_name1,column_name2,..)
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
Referenced_Table_name(column_name)
REFERENCES referenced_table_name(column_name);
For Example:
1) Lets use the "product" table and "order_items".
( order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
product(product_id)
);
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
);
name char(20),
dept char(10),
age number(2),
gender char(1),
salary number(10),
location char(10),
);
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. SQL subquery
is usually added in the WHERE Clause of the SQL statement. Most of the time, a
subquery is used when you know how to search for a value using a SELECT
statement, but do not know the exact value in the database.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the
comparision operators like =, <, >, >=, <= etc.
SELECT
INSERT
UPDATE
DELETE
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. SQL Join is used for combining column from two or more tables by using values common to
both tables. JoinKeyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is(n-1) where n, is number of tables. A table can also join to itself known
as, Self Join.
Types of Join
The following are the types of JOIN that we can use in SQL.
Inner
Outer
Left
Right
This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a table
which consists of records which combines each row from the first table with each row of the second
table.
SELECT column-name-list
from table-name1
CROSS JOIN
table-name2;
ID NAME
1 abhi
2 adam
4 alex
The class_info table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
SELECT *
from class,
ID NAME ID Address
1 abhi 1 DELHI
2 adam 1 DELHI
4 alex 1 DELHI
1 abhi 2 MUMBAI
2 adam 2 MUMBAI
4 alex 2 MUMBAI
1 abhi 3 CHENNAI
2 adam 3 CHENNAI
4 alex 3 CHENNAI
This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.
SELECT column-name-list
from table-name1
INNER JOIN
table-name2
ID NAME
1 abhi
2 adam
3 alex
4 anu
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
The left outer join returns a result table with the matched data of two tables then remaining rows of
the lefttable and null for the right table's column.
Left Outer Join syntax is,
SELECT column-name-list
from table-name1
table-name2
on table-name1.column-name = table-name2.column-name;
select column-name-list
from table-name1,
table-name2
on table-name1.column-name = table-name2.column-name(+);
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
The right outer join returns a result table with the matched data of two tables then remaining rows of
the right table and null for the left table's columns.
Right Outer Join Syntax is,
select column-name-list
from table-name1
table-name2
on table-name1.column-name = table-name2.column-name;
select column-name-list
from table-name1,
table-name2
on table-name1.column-name(+) = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
The full outer join returns a result table with the matched data of two table then remaining rows of
both lefttable and then the right table.
Full Outer Join Syntax is,
select column-name-list
from table-name1
table-name2
on table-name1.column-name = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or
more tables can be seen. Views do not contain data of their own. They are used to
restrict access to the database or to hide data complexity. A view is stored as a
SELECT statement in the database. DML operations on a view like INSERT,
UPDATE, DELETE affects the data in the original table upon which the view is
based.
AS
SELECT column_list
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.
Single-Column Indexes:
A single-column index is one that is created based on only one table
column. 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:
Creating Sequence
increment by increment-value
maxvalue maximum-value
cycle|nocycle
initial-value specifies the starting value of the Sequence, increment-value is the value by which sequence
will be incremented and maxvalue specifies the maximum value until which sequence will increment
itself.cycle specifies that if the maximum value exceeds the set limit, sequence will restart its cycle from
the begining.No cycle specifies that if sequence exceeds maxvalue an error will be thrown.
cycle ;
What is PL/SQL?
PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of programming
languages.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of
SQL.
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL language
code can be stored in the client system (client-side) or in the database (server-side)
.
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants,
records and cursors, which are used to manipulate data in the execution section.
Placeholders may be any of Variables, Constants and Records, which stores data
temporarily. Cursors are also declared in this section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends
with END. This is a mandatory section and is the section where the program logic is
written to perform any task. The programmatic constructs like loops, conditional
statement and SQL statements form the part of execution section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION.
This section is optional. Any errors in the program can be handled in this section, so that
the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that
cannot be handled, the Block terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks
can be nested within other PL/SQL blocks. Comments can be used to document code.
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
Learning PL/SQL
Advantages of PL/SQL
These are the Advantages of PL/SQL
Block Structures: PL SQL consists of blocks of code, which can be nested within each
other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be
stored in the database and reused.
Procedural Language Capability: PL SQL consists of procedural language constructs
such as conditional statements (if else statements) and loops like (FOR loops).
Better Performance: PL SQL engine processes multiple SQL statements
simultaneously as a single block, thereby reducing network traffic.
Scalar types
Scalar data type haven't internal components. It is like a linear data type. Scales data
type divides into four different types character, numeric, boolean or date/time type.
INTEGER 38 digits
INT 38 digits
DEC 38 digits
This data types are used to
store fixed decimal points. You
DECIMAL 38 digits
can use based on your
requirements.
NUMERIC 38 digits
NATURALN
NATURALN/POSITIVEN data type prevent to assign
a NULL value.
POSITIVEN
Storage(Maximum
Data types Description
)
VARCHAR2 VARCHAR2 data type used to store variable strings data 32767 bytes
within predefined length.
VARCHAR2 Subtypes : Following sub type defines
same length value.
Sub Data types Description
STRING
We can access this data type.
VARCHAR
The ROWID data type represents the actual storage address of a row. And
ROWID table index identities as a logical rowid. This data type used to storing
backward compatibility. We strongly recommended to use UROWID data type.
Boolean data type stores logical values. Boolean data types doesn't take
any parameters.
Boolean Boolean data type store either TRUE or FALSE. Also store NULL, Oracle
treats NULL as an unassigned boolean variable.
You can not fetch boolean column value from another table.
Jan 1, 4712 BC
DATE data type stores valid date-time format with fixed length. to
DATE
Starting date from Jan 1, 4712 BC to Dec 31, 9999 AD. Dec 31, 9999
AD
TIMESTAMP data type stores valid date (year, month, day) with time (hour,
minute, second).