You are on page 1of 14

Advanced Database and SQL

with Oracle

Presented by: Shailesh Joshi

Accessing Oracle with Oracle Application Express


Go to https://apex.oracle.com/pls/apex/f?p=4550:1:0:::::
Enter YESM-SYSTEMS in Workspace
Enter Username and Password as per instructions in email
After Logging In

Click

Then Click

Set Rows Selector to a higher value like 200

Data Types in Oracle

VARCHAR2(n) character data (variable length upto


4000 characters)
CHAR(n) character data (fixed length 2000
Characters)

NUMBER numbers with/without a decimal point

DATE dates

TIMESTAMP date and time

BLOB/CLOB large pieces of binary/character data

Common Key Terminology

Key. A key is one or more data attributes that uniquely identify an entity.
In a physical database a key would be formed of one or more table columns
whose value(s) uniquely identifies a row within a relational table.
Composite key. A key that is composed of two or more attributes.
Natural key. A key that is formed of attributes that already exist in the real world.
For example, U.S. citizens are issued a Social Security Number (SSN) that is
unique to them. SSN could be used as a natural key, assuming privacy laws allow
it, for a Person entity (assuming the scope of your organization is limited to the
U.S.).
Surrogate key. A key with no business meaning.
Candidate key. An entity type in a logical data model will have zero or more
candidate keys, also referred to simply as unique identifiers. For example, if we
only interact with American citizens then SSN is one candidate key for the
Person entity type and the combination of name and phone number (assuming the
combination is unique) is potentially a second candidate key. Both of these keys
are called candidate keys because they are candidates to be chosen as the primary
key, an alternate key or perhaps not even a key at all within a physical data
model.
Primary key. The preferred key for an entity type.
Alternate key. Also known as a secondary key, is another unique identifier of a
row within a table.
Foreign key. One or more attributes in an entity type that represents a key, either
primary or secondary, in another entity type.

- See more at: http://agiledata.org/essays/keys.html

Create new table


CREATE TABLE <TABLE NAME>
(Col 1 datatype,
Col 2 datatype,
Col 3 datatype );
Null Value : The value that is unknown , missing or not applicable. It should not be
treated like a zero.
Forbidding Null values : sometimes you want to make sure a column does not end up
with any null values. e.g. Employee Name
Enter NOT NULL clause at the end of the column information.
CREATE TABLE <EMP>
(ENAME varchar(16) NOT NULL,
SAL number(10));
Insert new record
INSERT INTO <regions> (optional_column_names) VALUES (5, AUSTRALIA);

Delete record
DELETE FROM <regions> WHERE <region_id = 5>;
Update table
UPDATE <regions> SET <column_name> = <> WHERE <condition>;
Add a column
ALTER TABLE <regions> ADD <COLUMN_NAME> <DATA_TYPE>;
Delete column
ALTER TABLE <regions> DROP COLUMN <COLUMN_NAME>;

Show all columns of a table


SELECT * FROM < table name >;
Show a specific column/columns of a table
SELECT <col-name1>,<col-name2> FROM < table name >;
The order of selection determines the order of display.
Selecting Rows
If WHERE clause is specified , you get specific rows. If you dont specify it, all
rows will get selected .
In the WHERE clause you can compare any column value to :

A character constant using single quotes : WHERE ename = Sam


An arithmetic expression : WHERE deptno = 20
Another Column value : WHERE emp.deptno = dept.deptno
( This construct known as JOIN will be seen later )

Logical operators used in WHERE clause :


= , != , < , > , >= , <=
Other operators :
IN(list) , BETWEEN low AND high , IS NULL , LIKE , AND , OR
Select with like clause
SELECT * FROM employees where first_name like %Jen%;

Show selected records sorted in an ascending (asc) or descending (desc).


SELECT <col1>,<col2> FROM <table name> ORDER BY <col2> DESC/ASC;

Return number of rows


SELECT COUNT(column_name) FROM [table name];

Sum a column
SELECT SUM(column_name) FROM [table name];

Show unique records


SELECT DISTINCT manager_id FROM employees;

Modify Column Size


ALTER TABLE <table name> MODIFY <column name> <datatype(new sz)>
Truncate Table
TRUNCATE TABLE <table_name>
Removes all rows from a table. TRUNCATE TABLE is similar to the DELETE
statement with no WHERE clause (DELETE FROM <tablename>); however,
TRUNCATE TABLE is faster and uses fewer system and transaction log
resources.
Having Clause
The HAVING clause is used in combination with the GROUP BY clause. It can
be used in a SELECT statement to filter the records that a GROUP BY returns.
Select all departments who have total department level salary more than $5000
SELECT department_id, sum(salary) as "Payroll"
FROM employees
GROUP BY department_id
HAVING sum(salary) > 5000;
Select all departments with individual employees having salary more than $5000
and more than 5 employees in the department.
SELECT department_id, COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 5000
GROUP BY department_id
HAVING COUNT(*) > 5;
NOTE the difference between Total dept level salary and individual employee
salary in the two examples above.

Introduction to JOINS

Inner Join
It wont return any students who have been accepted at theschool but havent signed
up for any classes yet, nor will it return any classesthat are on the schedule but for
which no student has yet shown an interest.
Show me the students and their teachers who have the same first name.
(JOIN on the first name.)
Show me customers and employees who live in the same city. (JOIN on
the city name.)
Show me the vendors and the products they supply to us.
List the faculty staff and the subject each teaches.
I want to see all employees who report to a manager in department number 60
select last_name, first_name, department_name,
from employees
inner join departments
using (department_id)
order by (department_id);
Alternate Form
Select first_name, last_name, department_name
from employees
inner join departments
on (employees.department_id = departments.department_id)
order by (employees.department_id);

Outer Join
An OuterJoin asks your database system to return not only the rows that match on the
criteria you specify but also the unmatched rows from either one or both of
the two sets you want to link
You'll generally use the OUTER JOIN form that asks for all the rows from one table or
result set and any matching rows from a second table or result set. To do this, you
specify either a LEFT OUTER JOIN or a RIGHT OUTER JOIN.
Left Outer Join
Select all employees assigned to departments as well as those who are without a
department
------------------------------------------------------------------------------------------Select first_name, last_name, department_name
from employees
left outer join departments
using (department_id)
order by (department_id);

Right Outer Join


Select all departments having employees as well as those without any employees
------------------------------------------------------------------------------------------Select first_name, last_name, department_name
from employees
right outer join departments
using (department_id)
order by (department_name);

Why should QA professionals know SQL Basics?

SQL statements can be used to:


o Verify SQL statements used within the app
o Insert and remove test data
o Verify existence of data integrity on the DB
o Reveal corrupt data
Duplicate data
Orphan records
o Create and run automated tests in the DB backend
o Create test cases to protect against common DB hacks.

Sample Queries for Data Verification

Detecting duplicate data (using group by):


SELECT (last_name || first_name),
COUNT (last_name || first_name)
FROM Employees
GROUP BY (last_name || first_name)
HAVING COUNT (last_name || first_name) > 1;

Finding most recent data (using a subquery):


SELECT * FROM employees
WHERE hire_date =
(select max(hire_date) from employees);

Acquiring Test Data

Use SQL to populate tables:


create table regionstest1 as (select * from regions);
create table regionstest2 as (select * from regions where 1=2);

Using a Union:
SELECT (firstname || ' ' || lastname) as name,
city, postalcode into TestTable
FROM employees
UNION
SELECT companyname, city, postalcode
FROM customers

Test case: SQL Injection


Source : unixwiz.net/techtips/sql-injection.html

Turns this query:


Select username from user where username = someuser
and pass = somepass
Into this query:
Select username from user where username = or 1 = 1;
drop table users; -- and pass =
-----------------------------------------------------------------------------------------------What to test in Relational Databases
Source: www.agiledata.org

Functionality Testing
UI Screens, Stored procedures and triggers
Stored procedures and triggers should be tested just like application code would be.

Relationship Testing
Referential integrity (RI)
RI rules, in particular cascading deletes in which highly coupled "child" rows are deleted
when a parent row is deleted, should also be validated. Existence rules, such as a
customer row corresponding to an account row, must exist before the row can be
inserted into the Account table, and can be easily tested, too.

Data Quality Testing


Default values. Columns often have default values defined for them. Are the
default values actually being assigned. (Someone could have accidentally
removed this part of the table definition.)
Data invariants. Columns often have invariants, implemented in the forms of
constraints, defined for them. For example, a number column may be restricted
to containing the values 1 through 7. These invariants should be tested.
Validate the attribute size. Is the field size defined in the application is matching
with that in the db.

Performance Testing
Access time to read/write/delete a single row.
Access time for common queries returning multiple rows.
Access time for queries involving several tables.
Existence test for an index. Does the expected index exist or not?

Structural Testing
Table existence. We can check whether all the data from the application is
being inserted into the database properly, or not
View definitions. Views often implement interesting business logic. Things to
look out for include: Does the filtering/select logic work properly? Do you get
back the right number of rows? Are you returning the right columns? Are the
columns, and rows, in the right order?

You might also like