Veena DBM S Module 3
Veena DBM S Module 3
Relational Databases
A relational database is based on tables (or relations) to store the data. The word
'relation' or 'table' is now more widely used in database systems. Within the unit
database the word 'table' will be used.
. A table holds related information. For example, a company holds details on
employees, sections, salaries, pensions, projects, etc. A relational database contains
many such tables.
A table is made up of rows (records) and columns (fields). Rows and columns, as
opposed to records and fields, are the names most commonly used when working
with database systems. An example table is shown below:
Employee Table
TRUNCATE–is used to remove all records from a table, including all spaces allocated for
CREATE
Create is a DDL SQL command used to create a table or a database in relational
database management system.
Creating a Table- Create command can also be used to create tables. When we create a
table, we have to specify the details of the columns of the tables too. We can specify
the names and data types of various columns in the create command itself.
Create table command will tell the database system to create a new table with the given
table name and column information.
If we are currently not logged into wer database in which we want to create the table
then we can also add the database name along with table name, using a dot operator .
For example, if we have a database with name Test and we want to create a
table Student in it, then we can do so using the following query:
Here we have listed some of the most commonly used data types used for columns in
tables.
VARCHAR Used for columns to store characters and integers, basically a string.
TEXT Used for columns to store text this is generally long in length. For
example, if we create a table for storing profile information of a
social networking website, then for about me section we can have a
column of type TEXT.
DROP
DROP command allows removing entire database objects from the database.
INSERT
To add data to a table the INSERT command is used.
The syntax of the INSERT command is given below:
INSERT into table-name values (data, data …);
EXAMPLE : Suppose we have the following fields in the table named as EMPLOYEE as
follows:
Now use the following query to insert values to these fields in table.
This query will add the data into the fields and will produce the following result:
10 Management E01
We can also write NULL in the reference of the field and NULL value is specified to
the field as the following query:
INSERT into EMPLOYEE values (10, ‘Management’, ‘E01’, null);
This will result the same as the above query.
EXAMPLE to insert default value to a column:
If some value is set then writing the default keyword for that very specific field, then
this value will be inserted into that column. Suppose the default value of the field
EMP_NAME is set as “John Abraham” then using the default keyword will insert this
name in the field. Consider the following query to understand this:
INSERT into EMPLOYEE values (10, ‘Management’, ‘E01’, default);
50 IT E25 Kate
To update the table we are going to use the following query:
50 IT E25 Kate
This will update entry in the column EMP_NO with DEPT_NO 30.
If the user wants to update a number of columns of the table then he can use the
following query:
Update employee set EMP_NO = E06, set Emp_Name = ‘Stuart’ where DEPT_NO = 30;
This query will update the entries in the column EMP_NO and Emp_Name with
DEPT_NO 30. The following result will be produced:
50 IT E25 Kate
It can be observed that the name Ali is changed to Stuart and E04 is changed to E06.
Delete
To delete a table row or some data from a table in the database the delete command is
used.
The syntax of delete command is as follows: DELETE from table-name;
EXAMPLE to delete all records from a table
To delete all records use the delete command. This will delete the attributes, indexes
etc. of the table but the table as a whole will not be deleted.
To delete all records from the table use the following SQL statement:
DELETE from Employee;
This query will delete all the records from the table named as Employee. This change
will be permanent and cannot be recovered.
EXAMPLE to delete a particular record from a table:
Suppose we have the following table named as EMPLOYEE:
50 IT E25 Kate
If we want to delete a specific record from the table then use the following query:
This query will delete the records where the department number is 40 from the table
named as employee. This will delete the whole row from the table. The following result
will be generated:
50 IT E25 Kate
Select
Select command is used to view the records from the table. To view all the columns and
all the rows ‘*’can be specified with the select statement. The name of the table is
required while specifying the select.
Syntax :- Select * from <tablename>;
EXAMPLE : SQL> select * from student;
Output:-
103 PQR 67 N7
Select statement is very flexible. If user needs to view only certain fields or columns,
then by specifying those names of the columns in the form of list, user can view the
required output.
The general form is as follows:
Select column1, column2, column3…… column n from <tablename>;
EXAMPLE : SQL> select rollno, name, marks from student;
Output:-
Allow a User to create table- To allow a user to create tables in the database, we can use the
below command,
Grant all privilege to a User- Sysdba is a set of privileges which has all the permissions in it.
So if we want to provide all the privileges to any user, we can simply grant them
the sysdba permission.
Grant permission to create any table- Sometimes user is restricted from creating come
tables with names which are reserved for system tables. But we can grant privileges to a user to
create any table using the below command,
Grant permission to drop any table- As the title suggests, if we want to allow user to drop
any table from the database, then grant this privilege to the user,
To take back Permissions- If we want to take back the privileges from any user, use
the REVOKE command.
Commands are used to manage transactions in the database. These are used to manage
the changes made to the data in a table by DML statements. It also allows statements to
be grouped together into logical transactions.
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made
by these commands are not permanent, until the current session is closed, the
changes made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax- COMMIT;
ROLLBACK command
This command restores the database to last committed state. It is also used
with SAVEPOINT command to jump to a save point in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and
realize that those changes were not required, then we can use
the ROLLBACK command to rollback those changes, if they were not committed using
the COMMIT command.
SAVEPOINT command
In short, using this command we can name the different states of our data in any table
and then rollback to that state using the ROLLBACK command whenever required.
id name
1 Abhi
2 Adam
4 Alex
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Use the ROLLBACK command to roll back the state of data to the savepoint B.
ROLLBACK TO B;
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Again use the ROLLBACK command to roll back the state of data to the savepoint A
ROLLBACK TO A;
SELECT * FROM class;
The table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
SELECT queries
SQL SELECT statement syntax- It is the most frequently used SQL command and has the
following general syntax
SELECT [DISTINCT| ALL ] { * | [fieldExpression [AS newName]} FROM tableName
[alias] [WHERE condition][GROUP BY fieldName(s)] [HAVING condition] ORDER BY
fieldName(s)
Here
SELECT is the SQL keyword that lets the database know that we want to retrieve data.
ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending order,
based on one or more columns. Some databases sort the query results in an ascending
order by default.
Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
We can use more than one column in the ORDER BY clause.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
dept_id total_salaries
500 119500
501 113000
category_id total_products
25 1
50 4
75 1
In this example, we have used the COUNT function to calculate the number of products for
each category_id and we have aliased the results of the COUNT function as total_products.
We have excluded any category_id values that are NULL by filtering them out in the WHERE
clause. Because the category_id is not encapsulated in the COUNT function, it must be listed
in the GROUP BY clause.
dept_id lowest_salary
500 57500
501 42000
In this example, we have used the MIN function to return the lowest salary for
each dept_id and we have aliased the results of the MIN function as lowest_salary. Because
the dept_id is not encapsulated in the MIN function, it must be listed in the GROUP BY
clause.
dept_id highest_salary
500 62000
501 71000
In this example, we have used the MAX function to return the highest salary for
each dept_id and we have aliased the results of the MAX function as highest_salary.
The dept_id column must be listed in the GROUP BY clause because it is not encapsulated in
the MAX function.
COUNT(customer_id)
6
In this example, the query will return 6 since there are 6 records in the customers table and
all customer_id values are NOT NULL (ie: customer_id is the primary key for the table).
COUNT(favorite_website)
5
This second example will return 5. Because one of the favorite_website values is NULL, it
would be excluded from the COUNT function calculation. As a result, the query will return 5
instead of 6.
Example - Using a Single Expression in the COUNT Function
To use the COUNT function with a single expression in a query.
In this example, we have a table called employees with the following data:
total
3
In this example, we will return the number of employees who have a salary above $50,000.
We have aliased the COUNT(*) as total to make our query results more readable.
Now, total will display as the column heading when the result set is returned.
dept_id total
500 2
501 1
In this example, the COUNT function will return the number of employees that make over
$50,000 for each dept_id. Because the dept_id column is not included in the COUNT
function, it must be listed in the GROUP BY clause.
Example - Using DISTINCT with the COUNT Function
to count only the unique values.
Using the same employees table as the previous example:
SQL statement:
SELECT COUNT(DISTINCT dept_id) AS total FROM employees WHERE salary > 50000;
total
2
In this example, the COUNT function will return the unique number of dept_id values that
have at least one employee that makes over $50,000.
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.
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
A view is a specific representation of data from one or more tables. The tables referred
in the views are known as Base tables.
Creating a view does not take any storage space as only the query is stored in the data
dictionary and the actual data is not stored anywhere.
For example: suppose that in the EMF table we want that 'Manager' should have access to
the detail of employee's names, job and department. But he should not have any access to
the salaries of all the employees. This can be done with the help of Views. We can create
View according to the individual's need. We will create the view for the manager under
which we do not include salary column. This helps the database administrator to limit the
access to different kinds of users.
Uses of Views
Reducing complexity.
Security is increased - sensitive information can be excluded from a view
In the Syntax, View _name specifies the name of the view and must follow the rules for
identifiers. Column_name specifies the name of the column to be used in view. If the
column_name option is not specified, then the view is created with the same columns as
specified in the select_statement. Select_statement specifies the SELECT Statement that
defines a view.
The view may use the data contained in other views and tables. WITH CHECK OPTION
forces the data modification statements to fulfill the criteria given in the SELECT
statement defining the view. It also ensures that the data is visible after the modifications
are made permanent. WITH READ ONLY restrict the DML operations to be performed on
the view.
Creating Views
To create a view in our schema, we must have the CREATE VIEW privilege.
To create a view in another user's schema, we must have the CREATE ANY VIEW system
privilege. We can acquire these privileges explicitly or through a role.
The owner of the view (whether it is we or another user) must have been explicitly
granted privileges to access all objects referenced in the view definition. The owner
For example, if the owner of the view has only the INSERT privilege for Scott's EMP table,
then the view can be used only to insert new rows into the EMP table, not to SELECT,
UPDATE, or DELETE rows.
Examples:
Consider the EMPLOYEES table and create a View for the 'RAMAN'; she cannot access the
Salary of all the employees.
On Execution the view with Name 'Raman' is created. Once we create a view now it is
assumed to be a Table. We can now perform the various DML operations on the View. But
make sure if we impose the CHECK OPTIONS, then we cannot perform any operation.
Remember that it will also copy the Records contained in the base table. Display all the
records in the view.
After execution this command will display all the records of EMP table as when view
created all the records automatically copied into the view. It will display all the records.
If we use read only option in the view while creation then we cannot perform any DML
operation on the view. If we try to do this then error message will encounter. WITH READ
ONLY restrict the DML operations to be performed on the view
Consider the EMPLOYEES table and create a view for the 'RAMANDEEP'; she cannot access
the Salary of all the employees. Use the constraint 'WITH READ ONLY.
SQL> create view ramandeep as select eid, name from employees with read only;
Modifying Views
We can use the OR REPLACE option to modify the view. If the view exists it will be
replaced with the new definition or a new view will be created. We can use Create or
Replace option to create views instead of dropping the view and recreating it as with this
option the privileges granted on the view are preserved, but the dependent stored
programs and view become invalid.
The view will become invalid whenever the base table is altered. Vie can recompile a view
using the Alter view statement, but oracle automatically recompiles the view once it is
accessed. On recompiling the dependent objects become invalid.
There are certain rules that have to be followed to perform the DML operations. They
are as under:
We cannot insert the rows into view if the base table has certain columns with NOT
NULL constraint that does not appear in the view.
If a view is defined with WITH CHECK OPTION, a row cannot be inserted into. or
updated in, the base table (using the view), if the view cannot select the row from the
base table.
If view contains WITH READ ONLY Constraint then we cannot perform any DML
operations.
Views can be used to rename the columns without effecting the base tables provided that
the number of columns in a view must match the number of columns specified in the select
statement.
Create a view RAMAN from the table employees with different column names,
After execution the view RAMAN will be created with the different column names.
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
A selection from the "Orders" table:
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Antonio
3 Antonio Moreno Taquería Mexico
Moreno
Then, we can create the following SQL statement (that contains an INNER JOIN), that
selects records that have matching values in both tables:
Example
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are records in the "Orders" table that do not have matches in
"Customers", these orders will not be shown!
The following SQL statement selects all orders with customer and shipper information:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement will select all customers, and any orders they might have:
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if
there are no matches in the right table (Orders).
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement will return all employees, and any orders they might have
placed:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement selects all customers, and all orders:
CustomerName OrderID
Alfreds Futterkiste
10382
10351
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers),
and all the rows from the right table (Orders). If there are rows in "Customers" that do not
have matches in "Orders", or if there are rows in "Orders" that do not have matches in
"Customers", those rows will be listed as well.
SQL Self JOIN
A self JOIN is a regular join, but the table is joined with itself.
Self JOIN Syntax
SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition;
A selection from the "Customers" table:
The following SQL statement matches customers that are from the same city:
Syntax- The syntax for a sub query when the embedded SQL statement is part of
the WHERE condition is as follows:
[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a
text operator such as "LIKE".
Region_Name Store_Name
East Boston
East New York
Example: Simple sub query- To use a sub query to find the sales of all stores in the West
region, we use the following SQL statement:
SELECT SUM (Sales) FROM Store_Information
WHERE Store_Name IN
(SELECT Store_Name FROM Geography
WHERE Region_Name = 'West');
Result:
SUM (Sales)
2050
In this example, instead of joining the two tables directly and then adding up only the
sales amount for stores in the West region, we first use the sub query to find out which
stores are in the West region, and then we sum up the sales amount for these stores.
In this example, the inner query and the outer query are independent of each other.
This type of sub query is called a simple sub query.
Correlated queries
In a SQL database query, a correlated sub query (also known as a synchronized sub
query) is a sub query (a query nested inside another query) that uses values from the
outer query. Because the sub query may be evaluated once for each row processed by
the outer query, it can be inefficient.
Example : Correlated sub query
If the inner query is dependent on the outer query, we will have a correlated sub
query. An example of a correlated sub query is shown below:
SELECT SUM (a1.Sales) FROM Store_Information a1
WHERE a1.Store_Name IN
(SELECT Store_Name FROM Geography a2
WHERE a2.Store_Name = a1.Store_Name);
Result:
SUM (Sales)
2750
Here, the inner query is used to make sure that SQL only sums up sales amount from stores
that appear in both the Store_Information and the Geography tables.
The WHERE clause in the inner query, where the condition involves a table from the outer
query.
Sub query – The inner query is executed only once. The inner query will get executed first
and the output of the inner query used by the outer query. The inner query is not
dependent on outer query.
Correlated sub query: – The outer query will get executed first and for every row of outer
query, inner query will get executed. So the inner query will get executed as many times as
number of rows in the result of the outer query. The outer query output can use the inner
query output for comparison. This means inner query and outer query dependent on each
other
AVG () Function
Average returns average value after calculating it from values in a numeric column.
Its general syntax is-- SELECT AVG(column_name) FROM table_name
SQL query to find average salary will be-- SELECT avg(salary) from Emp;
Result of the above query will be,
avg(salary)
8200
COUNT() Function
Count returns the number of rows present in the table either based on some condition or
without condition.
Its general syntax is-- SELECT COUNT(column_name) FROM table-name;
count(name)
Example of COUNT(distinct)
Consider the following Emp table
count(distinct salary)
FIRST() Function
First function returns first value of a selected column
Syntax for FIRST function is,--- SELECT FIRST(column_name) FROM table-name;
first(salary)
9000
LAST() Function
LAST function returns the return last value of the selected column.
Syntax of LAST function is,-- SELECT LAST(column_name) FROM table-name;
last(salary)
8000
MAX() Function
MAX function returns maximum value from selected column of the table.
Syntax of MAX function is,-- SELECT MAX(column_name) from table-name;
MAX(salary)
10000
MIN() Function
MIN function returns minimum value from a selected column of the table.
Syntax for MIN function is,-- SELECT MIN(column_name) from table-name;
MIN(salary)
6000
SUM() Function
SUM function returns total sum of a selected columns numeric values.
Syntax for SUM is,-- SELECT SUM(column_name) from table-name;
SUM(salary)
41000
Scalar Functions
Scalar functions return a single value from an input value. Following are some frequently
used Scalar Functions in SQL.
UCASE() Function
UCASE function is used to convert value of string column to Uppercase characters.
Syntax of UCASE,-- SELECT UCASE(column_name) from table-name;
UCASE(name)
ANU
SHANE
ROHAN
SCOTT
TIGER
LCASE() Function
LCASE function is used to convert value of string columns to Lowecase characters.
Syntax for LCASE is-- SELECT LCASE(column_name) FROM table-name;
LCASE(name)
anu
shane
rohan
scott
tiger
MID() Function
MID function is used to extract substrings from column values of string type in a table.
Syntax for MID function is,-- SELECT MID(column_name, start, length) from table-name;
MID(name,2,2)
nu
ha
oh
co
ig
ROUND() Function
ROUND function is used to round a numeric field to number of nearest integer. It is used on
Decimal point values.
Syntax of Round function is,- SELECT ROUND(column_name, decimals) from table-name;
ROUND(salary)
9001
8001
6000
10000
8000
Procedural SQL
PL/SQL is a combination of SQL along with the procedural features of programming
languages.
PL/SQL is a block structured language that enables developers to combine the
power of SQL with procedural statements. All the statements of a block are passed
to oracle engine all at once which increases processing speed and decreases the
traffic.
Disadvantages of SQL:
SQL doesn’t provide the programmers with a technique of condition checking,
looping and branching.
SQL statements are passed to Oracle engine one at a time which increases traffic and
decreases speed.
VEENA R C, Assistant Professor
Dept., of CSE, GST Page 12
GITAM University, Bangalore
SQL- Structured Query Language MODULE 3
SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
1. PL/SQL is basically a procedural language, which provides the functionality of
decision making, iteration and many more features of procedural programming
languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and
types, which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block
known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or operating
system where Oracle is operational.
6. PL/SQL Offers extensive error checking.
Differences between SQL and PL/SQL:
SQL PL/SQL
DECLARE
Declaration statements;
BEGIN
Executable statements
EXCEPTIONS
Exception handling statements
END;
Declare section starts with DECLARE keyword in which variables, constants,
Each PL/SQL subprogram has a name, and may also have a parameter list. Like
anonymous PL/SQL blocks, the named blocks will also have the following three
parts −
Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start
1 with the DECLARE keyword. It contains declarations of types, cursors, constants,
variables, exceptions, and nested subprograms. These items are local to the
subprogram and cease to exist when the subprogram completes execution.
Executable Part
2
This is a mandatory part and contains statements that perform the designated action.
Exception-handling
3
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
Where,
o procedure-name specifies the name of the procedure.
o [OR REPLACE] option allows the modification of an existing procedure.
o The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the
procedure.
o procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example- The following example creates a simple procedure that displays the string 'Hello
World!' on the screen when executed.
EXECUTE greetings;
The following table lists out the parameter modes in PL/SQL subprograms −
IN
OUT
IN OUT
This program finds the minimum of two values. Here, the procedure takes two numbers
using the IN mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23
This procedure computes the square of value of a passed value. This example shows how
we can use the same parameter to accept a value and then return another result.
Similarity: Both are used by the client-side applications to access different kinds of
databases on server side.
ODBC JDBC
We can use ODBC for any language like C,C++,Java We can use JDBC only for Java
etc. languages.
We can choose ODBC only windows platform. We can Use JDBC in any platform.
Mostly ODBC Driver developed in native languages JDBC Stands for java database
like C,C++. connectivity.
For Java applications it is not recommended to use For Java application it is highly
ODBC because performance will be down due to recommended to use JDBC because
internal conversion and applications will become there we no performance & platform
platform Dependent. dependent problem.
HAVING Clause:
The HAVING Clause enables us to specify conditions that filter which group results appear
in the results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause
places conditions on groups created by the GROUP BY clause.
Syntax
The HAVING clause must follow the GROUP BY clause in a query and must also precedes
the ORDER BY clause if used. The following code block has the syntax of the SELECT
statement including the HAVING clause −
SELECT column1, column2 FROM table1, table2
WHERE [conditions] GROUP BY column1, column2
HAVING [conditions] ORDER BY column1, column2;
Following is an example, which would display a record for a similar age count that would
be more than or equal to 2.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS
GROUP BY age HAVING COUNT (age) >= 2;
+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+--------+-----+---------+---------+
Just as with the UNION operator, the same rules apply when using the EXCEPT operator.
MySQL does not support the EXCEPT operator.
Syntax
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here, the given condition could be any given expression based on our requirement.
Example
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| 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 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
There are some special embedded SQL statements which are used to retrieve the data into
the program. There is a special SQL precompiler that accepts the combined source code
with other programming tools and converts them into an executable program
We can mix the SQL statements directly into general purpose programming language like C,
Java or Pascal. There are some techniques to embed SQL statements in the programming
languages.
1. The programming language in which the SQL statements are embedded is called the host
language. The SQL statements and host language statements make the source program
which is fed to a SQL precompiler for processing the SQL statements.
2. The host programming languages variables can be referenced in the embedded SQL
statements, which allows values calculated by the programs to be used by SQL
statements.
3. There are some special program variables which are used to assign null values to
database columns. These program variables support the retrieval of null values from the
database.
Explanation
1. The embedded SQL statement can be written in any case (lower or upper). Although
we should follow the convention of that programming language in which we are
embedding the SQL statements. For e.g., COBOL and FORTRAN are written in upper
case so, the SQL statements are also written in upper case, while in C, the SQL
statements are written in lower case as shown in above program.
2. Each embedded SQL statement begins with an introducer which indicates that it is a
SQL statement. For most of the programming language EXEC SQL is used as an
introducer.
3. Each embedded SQL statement ends with a terminator. There can be different
terminators for different programming languages. For example, there is END EXEC for
COBOL and a semicolon (;) for C.
4. The DECLARE TABLE statement is used to declare a table. With the use of DECLARE
TABLE statement our program specifies the column and data type explicitly.
5. When we type SQL statement, we may make an error. This error is displayed by the
interactive SQL program and we are prompted to type a new statement.
There can be two types of errors: compile time and runtime.
CURSORS
A cursor is a temporary work area created in system memory when an SQL statement
is executed.
A cursor is a set of rows together with a pointer that identifies a current row.
1. Declare Cursor: In this part we declare variables and return a set of values.
2. Open: This is the entering part of the cursor.
3. Fetch: Used to retrieve the data row by row from a cursor.
4. Close: This is an exit part of the cursor and used to close a cursor.
5. Deallocate: In this part we delete the cursor definition and release all the system
resources associated with the cursor.
Syntax of a Cursor
Cursor Scope- Microsoft SQL Server supports the GLOBAL and LOCAL keywords on the
DECLARE CURSOR statement to define the scope of the cursor name.
Data Fetch Option in Cursors- Microsoft SQL Server supports the following two
fetch options for data:
1. FORWARD_ONLY: Specifies that the cursor can only be scrolled from the first to the
last row.
2. SCROLL: It provides 6 options to fetch the data (FIRST, LAST, PRIOR, NEXT,
RELATIVE and ABSOLUTE).
Types of cursors- Microsoft SQL Server supports the following 4 types of cursors.
1. STATIC CURSOR: A static cursor populates the result set during cursor creation and
the query result is cached for the lifetime of the cursor. A static cursor can move
forward and backward.
2. FAST_FORWARD: This is the default type of cursor. It is identical to the static
except that you can only scroll forward.
3. DYNAMIC: In a dynamic cursor, additions and deletions are visible for others in the
data source while the cursor is open.
4. KEYSET: This is similar to a dynamic cursor except we can't see records others add.
If another user deletes a record, it is inaccessible from our record set.
Types of Locks - Locking is the process by which a DBMS restricts access to a row in a
multi-user environment. When a row or column is exclusively locked, other users are not
permitted to access the locked data until the lock is released. It is used for data integrity.
This ensures that two users cannot simultaneously update the same column in a row.
Example- Find the name and age of a sailor, specified by assigning a value to the host
variable c_sid
This query returns a collection of rows, not just one row. 'When executed interactively, the
answers are printed on the screen. If we embed this query in a C program by prefixing the
command with EXEC SQL, how can the answers be bound to host language variables? The
INTO clause is inadequate because we must deal with several rows. The solution is to use a
cursor:
This code can be included in a C program, and once it is executed, the cursor sinfo is
defined. Subsequently, we can open the cursor:
OPEN sinfo:
The value of c_minrating in the SQL query associated with the cursor is the value of this
variable when we open the cursor. (The cursor declaration is processed at compile-time,
and the OPEN command is executed at run-time.)
When the FETCH statement is executed, the cursor is positioned to point at the next row
(which is the first row in the table when FETCH is executed for the first time after opening
the cursor) and the column values in the row are copied into the corresponding host
variables. By repeatedly executing this FETCH statement (say, in a while-loop in the C
program), we can read all the rows computed by the query, one row at a time. Additional
parameters to the FETCH command allow us to position a cursor in very flexible ways
CLOSE s_info;
It can be opened again if needed, and the value of : c_minrating in the SQL query associated
with the cursor would be the value of the host variable c_minrating at that time
Properties of Cursors
The general form of a cursor declaration is:
DECLARE cursorname [INSENSITIVE] [SCROLL] CURSOR
[WITH HOLD]
FOR some query
[ ORDER BY order-item-list ]
[ FOR READ ONLY I FOR UPDATE ]
A cursor can be declared to be a read-only cursor (FOR READ ONLY) or, if it is a cursor on a
base relation or an updatable view, to be an updatable cursor (FOR UPDATE). If it is
updatable, simple variants of the UPDATE and DELETE commands allow us to update or
delete the row on which the cursor is positioned. For example, if sinfo is an updatable
cursor and open, we can execute the following statement:
This Embedded SQL statement modifies the rating value of the row currently pointed to by
cursor sinfo; similarly, we can delete this row by executing the next statement:
Creating Triggers
The syntax for creating a trigger is −
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the
previous chapters −
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire
for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
The following points need to be considered here −
OLD and NEW references are not available for table-level triggers, rather you can
use them for record-level triggers.
If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the
initial changes are applied and the table is back in a consistent state.
The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500
Constraints Triggers
A constraint is an object the database
engine uses to constrain data in one An AFTER trigger is a special type of SQL code
table or a relationship of tables in order block that executes when a DML statement
to maintain database integrity. These is executed against the table the trigger is
constraints include CHECK, UNIQUE, defined on
PRIMARY KEY, etc.
Constraints are used to maintain the Triggers are basically stored procedures
integrity and atomicity of database .in which automatically fired when any insert
other words it can be said they are used ,update or delete is issued on table
to prevent invalid data entry.
The main 5 constraints are NOT
NULL,PRIMARY KEY,FOREIGN
KEY,UNIQUE KEY and CHECK.
trigger effected only those row after which
Constraint affected all row of table. trigger applied
SQL triggers only can provide an extended validation and they cannot replace all the
validations. Some simple validations have to be done in the application layer. For
example, we can validate user’s inputs in the client side by using JavaScript or on the
server side using server-side scripting languages such as JSP, PHP, ASP.NET, and Perl.
SQL triggers are invoked and executed invisible from the client applications;
therefore, it is difficult to figure out what happens in the database layer.
SQL triggers may increase the overhead of the database server.