Structured Query Language: Features of SQL
Structured Query Language: Features of SQL
Features of SQL:-
1.SQL can be used a range of users, including those with little or no programming experience.
2.It is not a procedural language.
3.It reduces the amount of time required for creating and maintaining system.
SQL Delimiters:-
Delimiters are symbols or compound symbols which have a special meaning within SQL and
PL/SQL statements.
+Addition
- Substraction
* Multiplication
/ Division
= > < Relational
( ) Expression or list
; Terminator
Components of SQL
1.DDL(Data Definition Language):
It is a set of SQL commands used to create,modify and delete database structures but not
data.
These statements are immediate,they are not susceptible to Rollback.
Every DDL command would commit all the updates as every DDL command implicitly
issues a commit command to the database.
2.DML(Data Manipulation Language):
It is the area of SQL that allows changing data within the database.
3.DCL(Data Control Language):
It is the component of SQL statements that control access to data and to the database.
DCL statements are grouped with DML statements.
4.DQL(Data Query Language):
It is the component of SQL statements that allows getting data from the database and
imposing ordering upon it.It includes ‘select’ statement.
Examples of DDL,DML,DCL and DQL command:-
DDL:
Create: To create objects in the database.
Alter: Alters the structure of database.
Drop: Delete objects from the database.
Rename: Rename objects in database.
Truncate: Removes all records along with space allocated for the records.
Comment: Add comment to data dictionary.
Grant: Give users access privileges with grant command.
DML:
Insert: Inserts data into a table.
Update: Updates existing data within a table.
Delete: Delete all records from a table,the space for the record remains.
Call: Calls a PL/SQL or Java subprogram.
Lock: Table control concurrency.
DCL:
Commit: Saves works done.
Savepoint: Identify a point in a transaction to which you can later rollback.
Rollback: Restore database to original since the last commit.
Set transaction: Change transaction option like what rollback segment to use.
DQL:
Select: Retrieve data from the database.
Table Fundamentals:-
Table is a database object that holds user data.Each table has multiple columns and each column
of a table have a specific data type associated with them.
DATE
This data type is used to represent date and time.The standard format is DD-MON-YY as in 21-
JUN-04.Datetime stores date in the 24-hour format.
NUMBER
The number data type is used to store numbers(fixed or floating point).Numbers of vertically any
magnitude may be stored up to 38 digits of precision.Valid values are 0 and positive and
negative numbers with magnitude 1.0E-130 to 9.9..E1.25.
LONG
This data type is used to store variable length character strings containing up to 2GB.Long data
can be used to store arrays of binary data in ASCII format.Only one long value can be defined
per table.
1.CREATE COMMAND
The create table command defines each column of the table uniquely.Each column has a
minimum of three attributes a name and data type and size(i.e column width).Each table column
definition is a single clause in the create table syntax.Each table column definition is seperated
from the other by a comma.Finally,the SQL statement is terminated with a semicolon.
Rules for creating tables:
A name can have maximum upto 30 characters.
Alphabets from A-Z,a-z and numbers from 0-9 are allowed.
A name should begin with an alphabet.
The use of the special characters like-is allowed and also recommended.
SQL reserved words not allowed.
Syntax:
Create table tablename(columnName1 Datatype(size),columnName2
Datatype(size),………..columnNamen Datatype(size));
2.ALTER COMMAND
Modifying the structure of tables:-
The structure of a table can be modified by using the Alter table command.With Alter table
command it is possible to add or delete columns,create or destroy indexes,change the data types
of existing columns or rename columns or the table itself.
Alter table works by making a temporary copy of the original table.The alteration is performed
on the copy then the original table is deleted and the new one is renamed.
3. DROP COMMAND
Drop table statement can be used to destroy a table and releasing the storage space held
by the table.
Dropping a table deletes all the data stored (records) in the table and all the indexes
associated with it.
We cannot roll back the drop statement.
Syntax:
Drop table <Table Name>;
4.RENAME COMMAND
Oracle allows renaming of tables. The rename operation is done automatically, which
means that no other thread is can access any of the tables while the rename process is
running.
To rename a table alter and drop privileges on the original table and create and insert
privileges on the new table are required.
Syntax:
Rename <Table Name> to <New Name>;
5.TRUNCATE COMMAND
Truncate table statement removes all rows from a table and releases all the storage space
used by that table.
The difference between Truncate and Delete statement is:
Truncate operation drop and recreate the table which is much faster than deleting rows
one by one.
Truncate does not generate roll back Information.
Truncate operations are not transaction safe. (i.e. an error will allow if an active
transaction or an active table lock exist.)
Syntax:
Truncate table <Table Name>;
1.INSERT COMMAND
Once table is created,the most natural thing to do is load this table with data to be manipulated
later.When inserting a single row of data into the table the insert operation-
1.creates a new row(empty) in the database table.
2.loads the values passed(by the SQL insert) into the column specified.
Syntax:
Insert into <tablename> (<columnname1>,<columnname2>)
values(<expression1>,<expression2>);
Characters expressions placed within the insert into statement must be enclosed in single quotes.
In the insert into SQL sentence,table columns and values have one to one relationship(i.e the first
value described is inserted into the first column and the second column and so on).
2.DELETE COMMAND
The delete command deletes rows from the table that satisfies the condition provided by its
where clause and returns the number of records deleted.The verb delete in SQL is used to
remove either all rows from a table or a set of rows from a table.
Syntax:
For all rows
delete from <tablename>;
We cannot delete a row that contains a primary key that is used as a foreign key in other table.
3.UPDATE COMMAND
Update command is used to change or modify data values in a table.
Update is used to either update all the rows from a table,a select set of rows from a table.
Syntax:
For all rows
Update <tablename>
Set <columnname1> = <expression1>,<columnname2> = <expression2>;
I/O Constraint
The Input/output data constraint can be further divided into distinctly different
constraints:
i. Primary Key Constraint
ii. Unique Key Constraint
iii. Foreign Key Constraint
2.Foreign Key
Foreign Key represents relationship between tables.
A Foreign Key is a column (or a group of columns) whose values are derived from the
primary key or unique of some other table.
A table in which foreign key is defined is called a foreign table or detail table.
The table that defines the primary or unique key and is referenced by the foreign key is
called the primary table or master table.
Foreign key can be defined in either a create table statement or an Alter table statement.
The master table can be referenced in the foreign key definition by using the clause
‘References’ when defining the foreign key, column attributes in the detail table.
The constraint of the foreign key establishes a relationship between the records (i.e.
Column data across a master and a detail table. This relationship ensures:
*Records cannot be inserted into a detail table if corresponding records in the master
table does not exists.
*Records of the master table cannot be deleted if corresponding records in the detail table
actually exist.
Foreign Key constraints:
*Rejects an insert /or update of a value does not currently exist in the master key table.
*Rejects a delete from the master table if corresponding records in the table exists.
*If on delete cascade option is set a delete operation in the master table will trigger a
delete operation for corresponding records in all detail tables.
*if on delete set Null option is set a delete operation in the master table will set the value
held by the foreign key of the detail table to Null.
Ex:
Create table Account (a_no char (20) primary key, branch_name char(20),balance integer,
foreign key (branch_name) references branch (branch_name));
Unique constraint can be defined either at the table level or column level.
Syntax:
<Column Name><Data type>(<Size>) Unique.
Ex:
Create table Customer ( c_id char(20) unique, c_name char(20),c_address char(20));
R_Owner The owner of the table referred by the foreign key constraint.
Multiple columns can be selected by specifying the column names separated by commas.
Arithmetic operators can be used in select statement.The order of precedence is * / + -
Ex: select ename,salary,12*salary
From emp;
2.WHERE CLAUSE
We can restrict the rows returned by using the where clause.
Syntax:
Select * | {[distinct] column | expression [alias]..}
From table
Where condition(s);
Where clause contains a condition that must be met and it directly follows the from clause.
If condition is true the row meeting the condition is returned.
In the syntax;
Where: restricts the query to rows that meet a condition.
Condition: is composed of column names, expressions constants and a comparison operator.
3.ORDER BY CLAUSE
The order by clause can be used to sort the rows. Order by must be the last clause of SQL
statement.
Syntax:
Select expr
From table
Where condition
Order by {column,expr} {Asc [desc]};
4.GROUP BY CLAUSE
Group by clause to divide the rows in a table into groups.
Syntax:
Select column, group-function (column)
From table
Where condition
Group by group_by_expression
Order by Column.
Using where clause we can exclude rows before dividing them into groups.
Columns alias cannot be used in group by.
When using the group by clause, make sure that all columns in the select list that are not
group functions are included in the Group by clause.
Ex:
Select department_id, Avg(salary)
From employee
Group by department_id.
Average will be calculated for each department.
You can return summary results for groups and subgroups by listing more than one group
by column.
Ex:
Select did, Job_id, sum(salary)
From emp
Using the count Function
5.HAVING CLAUSE
Having clause can be used to satisfy which groups are to be displayed. Thus, further restricting
the groups on the basis of aggregate of Information.
Syntax:
Select column, group function
From table
Where condition
Group by group_by_expression
Having group_conditoin
Order by column
Oracle server performs the following steps when you use the Having clause
1. Rows are grouped
2. Group function is applied to the group
3. The groups that match the criteria in the having clause are displayed.
Ex:
Select did, Avg(Sal)
From emp
Group by did
Having max (Sal)>1000;
6.ORACLE FUNCTUIONS
Functions are a very powerful feature of SQL and can be used to do the following.
perform calculations on data.
modify individual data items.
manipulate output for groups of rows.
convert column data types.
1.CHARACTER FUNCTIONS:
Accepts character data as input and can return both character and numeric values.Character
values can be divided into;
2.NUMBER FUNCTIONS:
Number functions accepts numeric input and returns numeric values.
Ex:
I.Round(column|expression,n)
Rounds the column,expression or value to n decimal places or if n is omitted,no decimal places.
If n is negative,numbers to left of the decimal point are rounded.
II.Trunc(column|expression,n)
Truncates the column expression or value to n decimal places or if n is omitted then n defaults to
zero.
III.Mod(m,n)
Returns the remainder of m divided by n.
19-oct-2000
Sysdate : is a date function that returns the current database server date and time.
Sysdate can be used as any other column name.
Ex: select sysdate from dual;
4.CONVERSION FUNCTION:
Data type conversions can be either:
Implicit Data type conversion;
Explicit Data type conversion.
To_char: (number | date, [fmt], [nLsparams]) converts a number or date value to a varchar 2
characters string with format model fmt. nLsparam (Number Conversion) specifies the following
characters which are returned by numbers format elements.
Decimal Character
Group Separator
Local currency symbol
International currency symbol
If nLsparams or any other parameter is omitted, this function uses default parameter values for
the session.
To_Number: (Char,[fmt],[nLsparams])
Converts a character string containing digits to a number in the format specified by the optional
format model fmt.
To_Date:(char,[fmt][nLsparams]
Converts a character string representing a date to a date value according to a fmt specified. If
fmt is omitted the format is DD-MON-YY.
5.GENERAL FUNCTION:
These Functions work with any data type and pertain to using nulls
NVL( expr1, expr2)
Converts a null value to an actual value
NVL Function
NVL converts a null to an actual value.
Syntax:
NVL(expr1,expr2)
Expr1 is the source value or expression that may contain null
Expr2 is the target value for converting the null.
Data types that can be used are at date, character and number.
Ex:
NVL(commisiion-pet,0)
NVL(hire_date, ’01-JAN-97’)
NVL(Job-id, ‘No Job Yet’)
7.GROUP FUNCTIONS
Group Functions operate on sets of rows to give one result per group.
Type of group functions
o Avg
o Max
o STDDEV
o VARIANCE
o Count
o Min
o Sum
Avg(costinct [All] n)-Average value of n ignoring null values
Count({*|Distinct|All}expr})-Number of rows,where expr evaluate to something other
than null.
Max(Distinct|All]expr)
Maximum value of expr, ignoring null values.
Min(Distinct|All]expr)
Minimum value of expr, ignoring null values.
Stddiv([Distinct|All]x)
Standard derivation of n ignoring null value
Sum([Distinct|All]n)
Sum value of n, ignoring null value.
variance([Distinct|All]x)
Variance of n, ignoring null value
Count(expr)
Returns the non_null values in the column identified by expr.
Count(Distinct expr)
Returns the number of unique, non_null values in the column identified by expr.
*All operator can be used with relational operator it serves as And operator
>All means more than maximum value in the list
<All means less than the minimum value
=All is meangingless because no value can be equal to all values in the list
iii.CORRELATED SUBQUERY
In Correlated subquery the inner query can reference columns from the outer subquery .the inner
query is executed once fro each row in the outer query
EXISTS AND NOT EXISTS OPERATOR
The Exist and Not exist can be used in correlated queries.
The Exist operator checks if the inner query returns at least one rowit returns true or false
Not exist check if the inner query does not return a row,it is opposite of exist operator.
VI.PL/SQL
There many disadvantages of SQL:
1.SQL does not have any procedural capabilities i.e.,SQL does not provide the programming
techniques of condition checking looping and branching.
2.SQL statements are passed to the oracle engine one at a time.
While processing an SQL sentence if an error occurs, the oracle engine displays its own error
messages.
*PL/SQL is a superset of SQL,
*PL/SQL is a block structured language that enables developers to combine the power of SQL
with procedural statements.
Advantages of PL/SQL:
1.PL/SQL sends an entire block of SQL statements to the oracle engine all in one go.
2.PL/SQL also permits dealing with errors as required, and facilitates displaying user-friendly
messages when errors are encountered.
3.PL/SQL allows declaration and use of variables in block code. There variables can be used
to store intermediate results of a quiery for later processing or calculate values and insert them
into an oracle table later.
4.Application written in PL/SQL are portable to any computer hardware and os.
2.Begin Section:
It consists of a set of SQL and PL/SQL statements, which describe processes that have to be
applied to table data, actual data manipulation, retrieval, looping and branching constructs are
specified in this section.
3.Exception Section: This
section deals with handling of errors that arises during exception of data manipulation statement
which make up the PL/SQL code block.
4.End Section: This
marks the end of a PL/SQL block.
PL/SQL VARIABLES
Variables in PL/SQL blocks are named variables.A variable mane must begin with a character
and can be followed by a maximum of 29 characters.
Assigning values to variables
The assigning of a value to a variable can be done in two ways:
1)Using tha assignment operator:=
2)Selecting or fetching table data values into variables.
Displaying message
DBMS-OUT PUT:This a package that include a number of procedures and function that
accumulate information in a buffer so that it can be retruved later.These function can also be
used to display message.
Put-line
It put a plece of information in the package buffer followed by an end of line marke.It can be
used to display a message.
To display message the server output should be on.
CONTROL STRUCTURES
The flow of control statement can be classified into following categories
1)conditional control
2)interative control
3)sequential control
1)CONDITIONAL CONTROL
PL/SQL allows the use of an IF statement to control the execution of a block of code.
Syntax
If condition then
Action
ELSE condition then
Action
ELSE
Action
ENDIF
2)ITERATIVE CONTROL
Iterative control indicate the ability to repeat or skip sections of code block.A loop marks of
sequence of statement that has to be repeated. A conditional statement that controls the number
of times a loop is executed always a companies loops
Syntax:Loop
Loop
<sequence of statement>
End loop;
Syntax:While loop
Syntax
While condition
Loop
Action
End loop
For loop
Syntax:For loop
For variable in[Reverse] start..end
Loop
<Action>
End loop
3)SEQUENTIAL CONTROL
Goto statement change the flow of control within apl/SQL block.This statement allows execution
of a section of code which is not in the normal flow of control.
Syntax
Goto <codeblockname>
Variable declaration;
Constant declaration;
Begin
Pl/sql program body
Exception
Exception plo/sql block;
End;
Deleting a stored procedure/Function
Syntax:
Drop procedure<procedure Name>;
Drop function<function Name>;
VIII.CURSORS
The oracle engine used a work area for its internal processing in order to execute an SLQ
statement They work are is private to SQL operation and is called cursor.
The data that is stored in the cursor that is called the active data set.
The values that is retruved from the table are held in a cursor opened in memory by the oracle
engine.
This data is then transferred to the chent machine via network
In order to hold this data, a cursor is opened at the chent end.
Types of cursors
Cursor are classified depending on the circumstances under which they are opened.
If the oracle engine opened a cursor for its internal processing it is known as impuclt cursor.
A cursor opened for processing data through a PL?SQL block on demand is known as expucrt
cursor.
General cursor atttibutes
When an oracle engine creats an impuct or expuct cursor, cursor control variables are also
created to control the execution of cursor.
These are a set of four system variables which keep track of the current status of cursor .
The cursor variables can be accessed and used in PL/SQL code block.
EXPLICT CURSOR:
When individual records in a table have to be processed inside a PL/SQL code a cursor is
used.Thus cursor will be declared and mapped to an SQL query in the declare section of the
PL/SQL block and used within its executable section.
Cursor declaration:
A cursor must be named and a query has to be mapped to it.
Three commands are used to control the cursor subsequently are OPEN,FETCH, and CLOSE
Open:
Initialization of a cursor takes place via the open statement
It defines a private SQL area named after the cursor name.
Executes the query associated with cursor.
Retrieves table data and populate them in private SQL area in memory.
Sets the cursor row pointer in Active Data Sets to the first record .
SYNTAX FOR CREATING A CURSOR:
Parameterized cursors:
The contents of the parameterized cursor will constantly change depending upon the value
passed to the parameter.
Syntax:
Cursor or cursorname(variable name Datatype) is
<select statement>
Opening:
Open cursorname(value/variable/expression)
IX.Database Triggers:
-Database triggers is stored in the database and is called automatically when a triggering event
occurs. A user cannot call a trigger explicitly.
-Triggering event is based on data manipulation language (DML) statement such as insert,
update or delete.
-A trigger can be created to fire before or after the triggering event.
-Execution of triggers is also known as firing the trigger.
Syntax:
Create [or replace] trigger triggername
Before [after|instead of triggering event on table|]
[for each row]
[when condition]
Declare
Declaration statement
Begin
Executable statement
Exception
Exception handling statement
End;
-Triggers are very useful for generating values for derived column keeping track of table access
preventing invalid entries, performing validity checks and maintaining security.
-Restrictions on triggers
->Triggers cannot use transaction control language statements such as commit, rollback or
savepoint.
->Variables in a triggers cannot be declared with long or long raw data type.-Instead of trigger
is based on view and it is a row trigger.
X.Views:
-A view is an oracle object that gives the user a logical view of data from an underlying table or
tables.
-You can restrict what users can view by allowing them to see only a few columns from a table.
-Views can be either simple view or complex view.
a)Simple view:
It is based on a one table. It can contain group function. Data manipulation is always possible.
b)Complex view:
It is based on one or more tables. It may contain group function. Data manipulation is not always
possible
Syntax:
Create [or replace] view viewname [column aliases]
As <query expression>
[With check option [constraints constraintsname]]
[With read only]
XI.Index:
-An index is another oracle object that is used for faster retrieval of rows from a table.
-Index can be created explicitly by using the create index statement.
-Once an index is created the user does not have to open or use the index with a command or a
statement the oracle serer uses the index to search for a row rather than scanning through the
entire table.
-Indexing reduces both search time and disk I/O.
-All indexes are maintained separately from the tables on which they are bared.
-Creating and removing an index does not affect the table at all.
-When a table is dropped all indexes based on that table are also removed.
Implicit indexes:
Implicit indexes are created when the primary key or unique constraints is defined such indexes
get the name of the constraints.
Explicit indexes:
A user can create explicit indexes based on non primary key or non unique columns or on any
combinations of columns for faster table access.
Simple indexes:
It is defined on a single column.
Composite indexes:
It is based on the combination of columns.
Syntax-for creating index
Create index indexname
On tablename(column1,column2……);
-Information of indexes is stored in user_indexes table.
-ex:
Create index stuidx
On student(last, first)
Index created
-Select index_name,table_name
From user_indexes
Where table_name=’student’
Gives result as
Index_name Table_name
Student_studentid_pk Student
Stu_idx Student
-First index was created automatically for the primary key constraints.
-Every insertion and deletion in a table updates the index which is added overhead on the system.
Rebuilding of an index:
-When a table goes through many changes(insertion, deletion, updating). Its advisable to rebuild
indexes based on that table
-Rebuilding compacts index data and improves performance.
Alter index stu_idx Rebuild;
XII.Transactions:
-In oracle the transaction starts with the first executable SQL statement that you issue.
-Transaction ends when one of the following occurs
->A comment or rollback transaction control statement is used.
->A DDL (create, alter, drop, rename or truncate) statement is executed (automatic
commit)
->A DCL (grant or revoke) statement is execution (automatic commit)
->A user properly exists (commit)
->The system crashes (rollback)
-Once a transaction ends, the new transaction starts with your next executable SQL statement.
-There is an environment variable Autocommit by default. It is set to OFF a user can set it to ON
or immediate by typing
Set Autocommit ON
Set Autocommit immediate
-When Autocommit is on every DML statement is written to the disk as soon as it is executed.
Every DML statement is committed implicitly and no rollback occurs with autocommit.
-Autocommit can be toggled back to off for an explicit commit.
-If system crashes any statement after the last commit are rolled back, so partial changes to tables
are not permanently written.
TCL (Transaction Control Language):
There are three TCL statements
a)Commit:
Ends the current transaction and write all changes permanently to the disk.
b)Savepoint n:
Makes a point in the current transaction.
XIII.PRIVILEGES
A user access needs s to be controlled in a shared multi-user oracle environment. Security can be
classified into two types.
a)System Security:
system security defines access to the database at the system level. It is implemented by assigning
a username and password allocation disk spaces and providing a user with the ability.
b)Database Security:
Database security defines a user access to various objects and the task a user can perform on
them.
-DBA can create users with create user statement. Once a user is created and a password
assigned the user needs privileges to do anything.
Syntax-for creating user
Create user username [profile profilename]
Identified by password
[Default tablespace tablespacename]
[Temporary tablespace tablespacename]
[Password expire] [Account unlock];
-A user can change his own password with the password command.
-DBA assigns privileges based on the level of a views or on a user or on a users needs these
levels are called Roles.
-Roles are created by DBA.
-Object privileges specifies what a user can do with a database object such as table, sequence or
view. These are basic 11 objects privileges and each object has a set of privileges out of a total of
11 privileges.
1) Alter (table, sequence)
2) Insert (table, view)
3) Update (table, view)
4) Delete (table, view)
5) Select (table, view, and sequence)
6) References (table, view)
7) Index (table)
8) Execute (procedure, function, and package)
9) Under (view, user defined type)
10) Read (directory)
11) Write (directory)
-A user has his objects in his own schema. An owner has all possible privileges on the owner’s
objects. A user (owner) can grant privileges on objects from his own schema to other users or
rolls.
Syntax:
o/p-Grant succeeded
o/p-Grant succeeded
Revoke:
The revoke statement takes privileges not only from the granter but also from the users granted
privileges by the granter. If with grant option is given.
Syntax:
Revoke object privileges
On objectname
From user/role/public
[Cascade constraints]
-Ex:
Revoke ALL
On employee
From xman
XIV.Locking:
-Oracle uses automatic locking in the least restrictions to provide sharing of data with integrity.
-Oracle has two lock classes
a) Share lock
b) Exclusive lock
-Shared mode lock is used when users requires only a read on the data item.
-Exclusive mode lock is used when users want to insert, update and delete data items.
Syntax:
Lock table tablename in Share/Exclusive mode nowait
-Ex:
To lock emp in Exclusive mode
Lock table emp in Exclusive mode
Releasing locks:
A lock is released when either of the following occurs
->The transactions is committed successfully using commit.
->Rollback is performed
->Rollback to a savepoint will release lock set after the specified savepoint.
Syntax:
Select columnnames
From tablename
[Where condition]
For update of columnnames
[Nowait];
-Use of columnnames in for update of does not that the locking is at the column level. The entire
row is locked. Column names are just used for information.
-Nowait clause, tell the user instantaneously if another user has already locked the row if it is
omitted (Nowait clause) then we have to wait for any rows that have been locked by other
application to be released, you will not be able to do any processing on those rows until then.
-Ex:
Select ename, salary, commission
From emp
Where cid=544
For update of salary, commission
Nowait