Unit 2 - SQL and PLSQL
Unit 2 - SQL and PLSQL
• CREATE TABLE is the keyword telling the database system what you want to do.
In this case, you want to create a new table. The unique name or identifier for the
table follows the CREATE TABLE statement.
• Then in brackets comes the list defining each column in the table and what sort of
data type it is. The syntax becomes clearer with the following example.
• A copy of an existing table can be created using a combination of the CREATE
TABLE statement and the SELECT statement.
• Example
• The following code block is an example, which creates a
CUSTOMERS table with an ID as a primary key and NOT NULL
are the constraints showing that these fields cannot be NULL
while creating records in this table −
Topics of SQL TABLE Statement
• SQL TABLE Variable: What TABLE variable can do?
• SQL CREATE TABLE: How to create a table using SQL query>
• SQL DROP TABLE: How to drop a table?
• SQL DELETE TABLE: How to delete all the records of a table?
• SQL RENAME TABLE: How to rename a table?
• SQL TRUNCATE TABLE: How to truncate a table?
• SQL COPY TABLE: How to copy a table?
• SQL TEMP TABLE: What is temporary table? What are the advantage of temporary table?
• SQL ALTER TABLE: How to add, modify, rename and drop column.
DROP or DELETE Table
• The SQL DROP TABLE statement is used to remove a table
definition and all the data, indexes, triggers, constraints and
permission specifications for that table.
• NOTE − You should be very careful while using this command
because once a table is deleted then all the information
available in that table will also be lost forever.
• Syntax
DROP TABLE table_name;
• Example
• Table: Cars
• Suppose, you want to change the above table name into "Car_2021_Details". For this,
you have to type the following RENAME statement in SQL:
RENAME Cars To Car_2021_Details ;
• After this statement, the table "Cars" will be changed into table name "Car_2021_Details".
Syntax of ALTER TABLE statement in
SQL
ALTER TABLE old_table_name RENAME TO new_table_name;
• Table : Bikes
• Suppose, you want to change the name of the above table into
"Bikes_Details" using ALTER TABLE statement. For this, you have to type
the following query in SQL:
ALTER TABLE Bikes RENAME TO Bikes_Details ;
• After this statement, the table "Bikes" will be changed into the table name
"Bikes_Details".
TRUNCATE TABLE
• A truncate SQL statement is used to remove all rows (complete data) from
a table. It is similar to the DELETE statement with no WHERE clause.
• TRUNCATE TABLE Vs DELETE TABLE
• Truncate table is faster and uses lesser resources than DELETE TABLE command.
• TRUNCATE TABLE Vs DROP TABLE
• Drop table command can also be used to delete complete table but it deletes table
structure too. TRUNCATE TABLE doesn't delete the structure of the table.
• TRUNCATE TABLE table_name;
• For example, you can write following command to truncate the data of
employee table
TRUNCATE TABLE Employee;
• Note: The rollback process is not possible after truncate table statement.
Once you truncate a table you cannot use a flashback table statement to
retrieve the content of the table.
COPY TABLE
• If you want to copy the data of one SQL table into another SQL
table in the same SQL server, then it is possible by using the
SELECT INTO statement in SQL.
• The SELECT INTO statement in Structured Query Language
copies the content from one existing table into the new table.
SQL creates the new table by using the structure of the existing
table.
• Syntax of SELECT INTO statement in SQL
SELECT * INTO New_table_name FROM old_table_name;
Examples of SELECT INTO statement in
SQL
• In this article, we have taken the following three different SQL examples which will help you how to
copy the content of one table into another table in SQL:
• Example 1: In this example, we have a table called Cars with three columns:
Table: Cars
• Suppose you want to copy the content of the above Car table into the new table Car_Details. For this, you have to type the following query in SQL:
SELECT * INTO Car_Details FROM Cars;
• Let's check the Car_Details table is created successfully or not in the database:
Table: Car_Details
TEMP TABLE
• The concept of temporary table is introduced by SQL server. It
helps developers in many ways:
• Temporary tables can be created at run-time and can do all
kinds of operations that a normal table can do. These temporary
tables are created inside tempdb database.
• There are two types of temp tables based on the behavior and
scope.
1.Local Temp Variable
2.Global Temp Variable
• Local Temp Variable
• Local temp tables are only available at current connection time.
It is automatically deleted when user disconnects from
instances. It is started with hash (#) sign.
Table: Cars
• Suppose, you want to add the new column Car_Model in the above
table. For this, you have to type the following query in the SQL:
ALTER TABLE Cars ADD Car_Model Varchar(20);
• This statement will add the Car_Model column to the Cars table.
SQL SELECT
• The most commonly used SQL command is SELECT
statement. It is used to query the database and retrieve
selected data that follow the conditions we want.
• In simple words, we can say that the select statement used to
query or retrieve data from a table in the database.
• Let's see the syntax of select statement.
• From the above example, select the first name of all the students. To do so, query
should be like this:
SELECT first_name FROM student_details;
• Note: the SQL commands are not case sensitive. We can also write the above SELECT
statement as:
select first_name from student_details;
• Now, you will get following data:
SELECT UNIQUE
• Actually, there is no difference between DISTINCT and UNIQUE.
• SELECT UNIQUE is an old syntax which was used in oracle
description but later ANSI standard defines DISTINCT as the official
keyword.
• After that oracle also added DISTINCT but did not withdraw the
service of UNIQUE keyword for the sake of backward compatibility.
• In simple words, we can say that SELECT UNIQUE statement is
used to retrieve a unique or distinct element from the table.
• Let's see the syntax of select unique statement.
SELECT UNIQUE column_name
FROM table_name;
• SQL SELECT DISTINCT statement can also be used for the same
cause.
SELECT DISTINCT
• The SQL DISTINCT command is used with SELECT key word
to retrieve only distinct or unique data.
• In a table, there may be a chance to exist a duplicate value and
sometimes we want to retrieve only unique values. In such
scenarios, SQL SELECT DISTINCT statement is used.
• Note: SQL SELECT UNIQUE and SQL SELECT DISTINCT
statements are same.
• Let's see the syntax of select distinct statement.
SELECT DISTINCT column_name ,column_name
FROM table_name;
Example
• This is an example that would sort the result in ascending order by NAME and SALARY.
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;
INSERT
• SQL INSERT statement is a SQL query. It is used to insert a
single or a multiple records in a table.
• There are two ways to insert data in a table:
1.By SQL insert into statement
1. By specifying column names
2. Without specifying column names
2.By SQL insert into select statement
1. Inserting data directly into a table
• You can insert a row in the table by using SQL INSERT INTO
command.
• There are two ways to insert values in a table.
• In the first method there is no need to specify the column name
where the data will be inserted, you need only their values.
INSERT INTO table_name
VALUES (value1, value2, value3....);
• The second method specifies both the column name and values
which you want to insert.
INSERT INTO table_name (column1, column2, column3....)
VALUES (value1, value2, value3.....);
• Let's take an example of table which has five records within it.
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (1, ABHIRAM, 22, ALLAHABAD);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (2, ALKA, 20, GHAZIABAD);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (3, DISHA, 21, VARANASI);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (4, ESHA, 21, DELHI);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (5, MANMEET, 23, JALANDHAR);
• It will show side table as the final result.
• Create a record in CUSTOMERS table by using this syntax also.
INSERT INTO CUSTOMERS
VALUES (6, PRATIK, 24, KANPUR);
• The following table will be as follow:
2) Inserting data through SELECT
Statement
• SQL INSERT INTO SELECT Syntax
INSERT INTO table_name
[(column1, column2, .... column)]
SELECT column1, column2, .... Column N
FROM table_name [WHERE condition];
• Note: when you add a new row, you should make sure that data
type of the value and the column should be matched.
• If any integrity constraints are defined for the table, you must
follow them.
Example
• The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table,
you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the
following code block.
SQL UPDATE with JOIN
• SQL UPDATE JOIN means we will update one table using another
table and join condition.
• Let us take an example of a customer table. I have updated
customer table that contains latest customer details from another
source system. I want to update the customer table with latest data.
In such case, I will perform join between target table and source
table using join on customer ID.
• Let's see the syntax of SQL UPDATE query with JOIN statement.
UPDATE customer_table
INNER JOIN
Customer_table
ON customer_table.rel_cust_name = customer_table.cust_id
SET customer_table.rel_cust_name = customer_table.cust_name
How to use multiple tables in SQL UPDATE statement with
JOIN
Let's take two tables, table 1 and table 2.
• If you have got a situation that you have multiple duplicate records in
a table, so at the time of fetching records from the table you should
be more careful. You make sure that you are fetching unique records
instead of fetching duplicate records.
• To overcome with this problem we use DISTINCT keyword.
• It is used along with SELECT statement to eliminate all duplicate
records and fetching only unique records.
• SYNTAX:
• The basic syntax to eliminate duplicate records from a table is:
1.SELECT DISTINCT column1, column2,....columnN
2.FROM table _name
3.WHERE [conditions]
EXAMPLE:
2.ORDER BY PERCENTAGE;
DELETE DATABASE
• You can easily remove or delete indexes, tables and databases with the
DROP statement.
• The DROP index statement is:
• Used to delete index in the table
DROP INDEX index_name ON table_name
• DROP DATABASE Statement:
• The drop database statement is used to delete a database.
1.DROP DATABASE database_name
Note:
• We should always note that in RDBMS, database name should be unique.
• We should always remember that DROP database command may be the
cause of loss of all information so we should always be careful while doing
this operation.
DELETE VIEW
• Before knowing about what is SQL delete view, it is important to know -
• What is SQL view?
• A view is a result set of a stored query on the data.
• The SQL view is a table which does not physically exist. It is only a virtual table.
• SQL VIEW can be created by a SQL query by joining one or more table.
• Syntax for SQL create view -
1.CREATE VIEW view_name AS
2.SELECT columns
3.FROM tables
4.WHERE conditions;
• If you want to delete a SQL view, It is done by SQL DROP command you should use the
following syntax:
• SQL DROP VIEW syntax:
1.DROP VIEW view_name
• Why use the SQL DROP VIEW statement?
• When a view no longer useful you may drop the view permanently. Also if a view needs
change within it, it would be dropped and then created again with changes in appropriate
places.
DELETE JOIN
• This is very commonly asked question that how to delete or update rows using join clause
• It is not a very easy process, sometimes, we need to update or delete records on the basis of complex WHERE
clauses.
• There are three tables which we use to operate on SQL syntax for DELETE JOIN.
• These tables are table1, table2 and target table.
• SQL Syntax for delete JOIN
1. DELETE [target table]
2. FROM [table1]
3. INNER JOIN [table2]
4. ON [table1.[joining column] = [table2].[joining column]
5. WHERE [condition]
• Syntax for update
1. UPDATE [target table]
2. SET [target column] = [new value]
3. FROM [table1]
4. INNER JOIN [table2]
5. ON [table1.[joining column] = [table2].[joining column]
6. WHERE [condition]
SQL JOIN
• 2.Payment table
1.SELECT Staff_ID, Staff_NAME, Staff_AGE, AMOUNT
2. FROM STAFF s, PAYMENT p
3. WHERE s.ID =p.STAFF_ID;
• This will produce the result like this:
OUTER JOIN
• In the SQL outer JOIN all the content of the both tables are
integrated together either they are matched or not.
• If you take an example of employee table
Outer join of two types:
1.Left outer join (also known as left join): this join returns all the rows
from left table combine with the matching rows of the right table. If you
get no matching in the right table it returns NULL values.
2.Right outer join (also known as right join): this join returns all the
rows from right table are combined with the matching rows of left table
.If you get no column matching in the left table .it returns null value.
LEFT JOIN
• The SQL left join returns all the values from the left table and it
also includes matching values from right table, if there are no
matching join value it returns NULL.
• BASIC SYNTAX FOR LEFT JOIN:
1.SELECT table1.column1, table2.column2....
2.FROM table1
3.LEFTJOIN table2
4.ON table1.column_field = table2.column_field;
• CUSTOMER TABLE:
• ORDER TABLE:
• The SQL right join returns all the values from the rows of right
table. It also includes the matched values from left table but if
there is no matching in both tables, it returns NULL.
• Basic syntax for right join:
1.SELECT table1.column1, table2.column2.....
2.FROM table1
3.RIGHT JOIN table2
4.ON table1.column_field = table2.column_field;
• Here we will join these two tables with SQL RIGHT JOIN:
1.SQL> SELECT ID,NAME,AMOUNT,DATE
2.FROM CUSTOMER
3.RIGHT JOIN ORDER
4.ON CUSTOMER.ID = ORDER.CUSTOMER_ID;
FULL JOIN
• The SQL full join is the result of combination of both left and right outer join and the join
tables have all the records from both tables. It puts NULL on the place of matches not
found.
• SQL full outer join and SQL join are same. generally it is known as SQL FULL JOIN.
• SQL full outer join:
• What is SQL full outer join?
• SQL full outer join is used to combine the result of both left and right outer join and returns
all rows (don't care its matched or unmatched) from the both participating tables.
• Syntax for full outer join:
1.SELECT *
2.FROM table1
3.FULL OUTER JOIN table2
4.ON table1.column_name = table2.column_name;
• Note:here table1 and table2 are the name of the tables participating in joining and
column_name is the column of the participating tables.
Let us take two tables to demonstrate full
outer join:
• table_A
• table_B
• Resulting table
Cross Join
• When each row of first table is combined with each row from the
second table, known as Cartesian join or cross join. In general words
we can say that SQL CROSS JOIN returns the Cartesian product of
the sets of rows from the joined table.
• We can specify a CROSS JOIN in two ways:
1.Using the JOIN syntax.
2.the table in the FROM clause without using a WHERE clause.
• SYNTAX of SQL Cross Join
1.SELECT * FROM [TABLE1] CROSS JOIN [TABLE2]
2.OR
3.SELECT * FROM [ TABLE1] , [TABLE2]
• Table1 – MatchScore
• Table2 - Departments
SQL Aggregate Functions
Example
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:10
Example: COUNT with WHERE
1.SELECT COUNT(*)
2.FROM PRODUCT_MAST;
3.WHERE RATE>=20;
Output:7
Example: COUNT() with DISTINCT
1.SELECT COUNT(DISTINCT COMPANY)
2.FROM PRODUCT_MAST;
Output:3
Example: COUNT() with GROUP BY
1.SELECT COMPANY, COUNT(*)
2.FROM PRODUCT_MAST
3.GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
SUM Function
• Sum function is used to calculate the sum of • Example: SUM() with GROUP BY
all selected columns. It works on numeric 1.SELECT SUM(COST)
fields only.
• Syntax 2.FROM PRODUCT_MAST
1.SUM() 3.WHERE QTY>3
2.or 4.GROUP BY COMPANY;
3.SUM( [ALL|DISTINCT] expression ) Output:
• Example: SUM() Com1 150
1.SELECT SUM(COST) Com3 170
2.FROM PRODUCT_MAST; • Example: SUM() with HAVING
Output: 1.SELECT COMPANY, SUM(COST)
670 2.FROM PRODUCT_MAST
• Example: SUM() with WHERE 3.GROUP BY COMPANY
1.SELECT SUM(COST) 4.HAVING SUM(COST)>=170;
2.FROM PRODUCT_MAST Output:
3.WHERE QTY>3; Com1 335
Output: Com3 170
320
AVG function
• The AVG function is used to calculate the average value of the numeric
type. AVG function returns the average of all non-Null values.
• Syntax
1.AVG()
2.or
3.AVG( [ALL|DISTINCT] expression )
• Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
MAX Function
• MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.
• Syntax
MAX()
or
MAX( [ALL|DISTINCT] expression )
• Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
30
MIN Function
• MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.
• Syntax
1.MIN()
2.or
3.MIN( [ALL|DISTINCT] expression )
• Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
SQL - Sub Queries
• A Subquery or Inner query or a Nested query is a query within another SQL query
and embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• There are a few rules that subqueries must follow −
1. Subqueries must be enclosed within parentheses.
2. A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
3. An ORDER BY command cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
4. Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
5. The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
6. A subquery cannot be immediately enclosed in a set function.
7. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Subqueries with the SELECT Statement
• Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
• Example
• Consider the CUSTOMERS table having the following records −
• This would produce the following result.
Subqueries with the INSERT Statement
• This would impact two rows and finally CUSTOMERS table would have the following records.
Subqueries with the DELETE Statement
• This would impact two rows and finally the CUSTOMERS table would have the following records.
Comparison Operators
• Comparison operators are used in the WHERE clause to determine which records to select. Here is
a list of the comparison operators that you can use in SQL:
PL/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.
• PL/SQL is one of three key programming languages embedded
in the Oracle Database, along with SQL itself and Java. This
tutorial will give you great understanding on PL/SQL to proceed
with Oracle database and other advanced RDBMS concepts.
PL/SQL Procedure
• Here:
• Function_name: specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents that value will be passed from outside and OUT represents that this parameter will be
used to return a value outside of the procedure.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
• Function_body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.
PL/SQL Function Example
Addition is: 33
Statement processed.
0.05 seconds
PL/SQL function example using table
Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers table.
Function created.
• To call a function you have to pass the required parameters along with function name and if function
returns a value then you can store returned value. Following program calls the function totalCustomers
from an anonymous block:
• After the execution of above code in SQL prompt, you will get the following result.
Total no. of Customers: 4
PL/SQL procedure successfully completed.
PL/SQL Drop Function
• a
Let's execute the following program to update the table and increase salary of each customer by 5000. Here,
SQL%ROWCOUNT attribute is used to determine the number of rows affected:
Create procedure:
1.DECLARE
2. total_rows number(2);
3.BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12.END;
13./
Output:
6 customers updated PL/SQL procedure successfully completed.
• select * from customers;
PL/SQL Explicit Cursors
• The Explicit cursors are defined by the programmers to gain more control
over the context area. These cursors should be defined in the declaration
section of the PL/SQL block. It is created on a SELECT statement which
returns more than one row.
• Following is the syntax to create an explicit cursor:Syntax of explicit cursor
• Following is the syntax to create an explicit cursor:
1.CURSOR cursor_name IS select_statement;;
• Steps:
• You must follow these steps while working with an explicit cursor.
1.Declare the cursor to initialize in the memory.
2.Open the cursor to allocate memory.
3.Fetch the cursor to retrieve data.
4.Close the cursor to release allocated memory.
1) Declare the cursor:
• It defines the cursor with a name and the associated SELECT statement.
• Syntax for explicit cursor declaration
1. CURSOR cursor_name IS
2. SELECT statement;
2) Open the cursor:
• It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the SQL
statements into it.
• Syntax for cursor open:
1. OPEN cursor_name;
3) Fetch the cursor:
• It is used to access one row at a time. You can fetch rows from the above-opened cursor as follows:
• Syntax for cursor fetch:
1. FETCH cursor_name INTO variable_list;
4) Close the cursor:
• It is used to release the allocated memory. The following syntax is used to close the above-opened
cursors.
• Syntax for cursor close:
1. Close cursor_name;
Example
• Create procedure:
• Execute the following program to retrieve the
customer name and address.
1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers
;
Output:
7. BEGIN
8. OPEN c_customers;
9. LOOP
1 Ramesh Allahabad
10. FETCH c_customers into c_id, c_name, c_a
ddr; 2 Suresh Kanpur
11. EXIT WHEN c_customers%notfound; 3 Mahesh Ghaziabad
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' 4 Chandan Noida
|| c_addr); 5 Alex Paris
13. END LOOP; 6 Sunita Delhi
14. CLOSE c_customers; PL/SQL procedure successfully completed.
15.END;
Trigger