Apznza 1
Apznza 1
Basics of SQL
SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS).
It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables.
All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server
use SQL as their standard database language.
SQL allows users to query the database in a number of ways, using English-
like statements.
Structure query language is not case sensitive. Generally, keywords of SQL
are written in uppercase.
When an SQL command is executing for any RDBMS, then the system
figure out the best way to carry out the request and the SQL engine
determines that how to interpret the task.
In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher etc.
When an SQL command is executing for any RDBMS, then the system
figure out the best way to carry out the request and the SQL engine
determines that how to interpret the task.
In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher, classic, etc.
DDL, DQL, DML, DCL, TCL
SQL uses certain commands like Create, Drop, Insert, etc. to carry out the
required tasks.
These SQL commands are mainly categorized into four categories as:
1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language
CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, AGE INT NOT NULL, ADDRESS CHAR (25), PRIMARY KEY (ID));
2. Alter table
The ALTER TABLE statement in Structured Query Language allows you to
add, rename, and delete columns of an existing table.
This statement also allows database users to add and remove various SQL
constraints on the existing tables.
Any user can also change the name of the table using this statement.
ALTER TABLE ADD Column
In many situations, you may require to add the columns in the existing table.
Instead of creating a whole table or database again you can easily add single
and multiple columns using the ADD keyword.
The above syntax only allows you to add a single column to the existing table.
If you want to add more than one column to the table in a single SQL
statement, then use the following syntax:
Syntax: ALTER TABLE table_name
ADD (column_Name1 column-definition,
column_Name2 column-definition,
.....
column_NameN column-definition);
3. Rename table
In some situations, database administrators and users want to change the
name of the table in the SQL database because they want to give a more
relevant name to the table.
Any database user can easily change the name by using the RENAME
TABLE and ALTER TABLE statement in Structured Query Language.
4. 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.
5. Drop table
A SQL DROP TABLE statement is used to delete a table definition and all
data from a table.
This is very important to know that once a table is deleted all the information
available in the table is lost forever, so we have to be very careful when using
this command.
Syntax: DROP TABLE table_name;
Example: DROP TABLE STUDENTS;
DML COMMAND
1. 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 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.
The second method specifies both the column name and values which you
want to insert.
2. UPDATE
SQL UPDATE statement is used to change the data of the records held by
tables. Which rows is to be update, it is decided by a condition. To specify
condition, we use WHERE clause.
3. DELETE
The DELETE statement is used to delete rows from a table. If you want to
remove a specific row from a table, you should use WHERE condition.
But if you do not specify the WHERE condition it will remove all the rows
from the table.
Defining constraints –
CREATE TABLE students ( S_Id int NOT NULL, LastName varchar (255)
NOT NULL, FirstName varchar (255), Address varchar (255),
City varchar (255), PRIMARY KEY (S_Id) ) ;
Second table:
O_Id OrderNo S_Id
1 99586465 2
2 78466588 2
3 22354846 3
4 57698656 1
The "S_Id" column in the "Students" table is the PRIMARY KEY in the
"Students" table.
The "S_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
Example: To create a foreign key on the "S_Id" column when the "Orders"
table is created:
CREATE TABLE Orders( O_Id int NOT NULL, Order_No int NOT NULL,
PRIMAY KEY(O_Id), S_Id int REFERENCES Students(S_Id));
Step 3: Execute the SELECT query to check the data in the Student table.
select * from student;
output:
SID SNAME
1 jackson
2 harry
3 allen
Step 6: Execute the SELECT query to check the data in the Course table.
select * from course;
CID CNAME SID
101 DBMS 1
102 OS 2
103 JAVA 3
Step 7: DELETE FROM Student table
[consider a case – If student left the college his information will be also
deleted from course table.]
Step 8: Execute the SELECT query to check the data in the Student table
select * from student;
Output:
SID SNAME
2 harry
3 allen
Step 9: Execute the SELECT query to check the data in the Course table.
select * from course;
output:
CID CNAME SID
102 OS 2
103 JAVA 3
Check constraint
The CHECK constraint is used to limit the value range that can be placed in a
column.If you define a CHECK constraint on a column it will allow only
certain values for this column
The following SQL creates a CHECK constraint on the "Age" column when
the "Persons" table is created. The CHECK constraint ensures that the age of
a person must be 18, or older:
CREATE TABLE Persons (ID int NOT NULL, LastName varchar (255)
NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18));
insert into Persons Values(1,'DOE', 'JOHN',17);
Output:
ORA-02290: check constraint (SQL_BBLCKZTWJFHBEZNMKTPAIWQWC.SYS_C00106131955)
violated ORA-06512: at "SYS.DBMS_SQL", line 1721
IN, BETWEEN and LIKE operator
IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
The following SQL statement selects all customers that are located in
"Germany", "France" or "UK":
BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can
be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
The following SQL statement selects all products with a price between 10
and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
To display the products outside the range of the previous example, use NOT
BETWEEN:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple characters
The underscore sign (_) represents one, single character
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERECustomerNameLIKE Finds any values that have "or" in any
'%or%' position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are
at least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are
at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and
ends with "o"
Aggregate functions
SQL aggregation function is used to perform the calculations on multiple
rows of a single column of a table. It returns a single value.
It is also used to summarize the data.
1. COUNT FUNCTION
COUNT function is used to Count the number of rows in a database table.
It can work on both numeric and non-numeric data types.
COUNT function uses the COUNT(*) that returns the count of all the rows in
a specified table.
COUNT(*) considers duplicate and Null.
Sample table:
PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Output:
3
Example: COUNT () with GROUP
BY SELECT COMPANY, COUNT
(*) FROM PRODUCT_MAST GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST
GROUP BY COMPANY HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns.
It works on numeric fields only.
Example: SUM ()
SELECT SUM(COST) FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3;
Output:
320
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. 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.
4. 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.
1 John 20 US 20
2 Stephan 26 Dubai 90
3 David 27 Bangkok 70
4 Alina 29 UK 35
5 Kathrin 34 Bangalore 85
Example: Find Name of student having maximum percentage.
select NAME from Student where PER IN (select MAX(PER) FROM Student);
Join
Refer unit-2 notes for theory and practical-6 for SQL Syntax
PL/SQL
PL/SQL is a block structured language. The programs of PL/SQL are logical
blocks that can contain any number of nested sub-blocks.
Pl/SQL stands for "Procedural Language extension of SQL" that is used in
Oracle. PL/SQL is integrated with Oracle database (since version 7).
The functionalities of PL/SQL usually extended after each release of Oracle
database. Although PL/SQL is closely integrated with SQL language, yet it
adds some programming constraints that are not available in SQL.
Advantages of PL/SQL
PL/SQL gives high productivity to programmers as it can query, transform,
and update data in a database.
PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented data types.
Applications written in PL/SQL are fully portable.
PL/SQL provides high security level.
PL/SQL provides access to predefined SQL packages.
PL/SQL provides support for Object-Oriented Programming.
PL/SQL provides support for developing Web Applications and Server Pages.
PL/SQL Procedures
The PL/SQL stored procedure or simply a procedure is a PL/SQL block
which performs one or more specific tasks. It is just like procedures in other
programming languages.
The procedure contains a header and a body.
Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.
Example-1: The following example creates a simple procedure that displays the
string 'Hello World!' on the screen when executed.
The above procedure named 'greetings' can be called with the EXECUTE
keyword as −
EXECUTE greetings;
BEGIN
greetings;
END;
/
The above call will display −
Hello World
PL/SQL procedure successfully completed.
Example-2: In this example, we are going to insert record in user table. So you
need to create user table first.
Table creation:
create table user (id number (10), name varchar (100), primary
key(id)); Now write the procedure code to insert record in user table.
Procedure Code:
create or replace procedure "INSERTUSER"
(id IN NUMBER, name IN VARCHAR)
is
begin
insert into user values (id, name);
end;
Output:
Procedure created.
ID Name
101 ABC
PL/SQL Cursors
When an SQL statement is processed, Oracle creates a memory area known
as context area.
A cursor is a pointer to this context area. It contains all information needed
for processing the statement.
In PL/SQL, the context area is controlled by Cursor. A cursor contains
information on a select statement and the rows of data accessed by it.
There are two types of cursors:
o Implicit Cursors
o Explicit Cursors
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:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
3 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will find that the rows are
updated.
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.
Create procedure:
Execute the following program to retrieve the customer name and address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line (c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
PL/SQL Triggers
A trigger is a stored procedure in database which automatically invokes
whenever a special event in the database occurs.
For example, a trigger can be invoked when a row is inserted into a specified
table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the
trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the
trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired
Above SQL statement will create a trigger in the student database in which
whenever subjects marks are entered, before inserting this data into the
database, trigger will compute those two values and insert with the entered
values. i.e.,
mysql> insert into Student values (1, "ABCDE", 20, 50, 50, 0, 0);
Query OK, 1 row affected (0.09 sec)