Showing posts with label Oracle. Show all posts
Showing posts with label Oracle. Show all posts

Feb 11, 2011

get Month from date Column

select to_char(open_ts,'yyyymm'),count(*)
from table name
group by to_char(open_ts,'yyyymm')
order by to_char(open_ts,'yyyymm')
or select to_char(sysdate,'mm') from dual;

Feb 7, 2011

Delete Duplicate rows and perftunning while doing delete for huge data


Here's how you remove the duplicate rows before the primary key or unique indexes can be created:

DELETE FROM our_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM our_table
GROUP BY column1, column2, column3... ;
Here column1, column2, column3 constitute the identifying key for each record.
Be sure to replace our_table with the table name from which you want to remove the duplicate rows. The GROUP BY is used on the columns that make the primary key for the table. This script deletes each row in the group after the first row.

OR

insert into EMP values ('1','20');
insert into EMP values ('2','30');
insert into EMP values ('2','30');
insert into EMP values ('3','40');
insert into EMP values ('4','50');
commit;

delete from EMP t1
where t1.rowid >
             ( select min(t2.rowID) from EMP t2
               where t1.col_A = t2.col_A
               and t1.col_B = t2.col_b)


OR

delete cea
where rowid in (
  select rid
  from (
    SELECT ROWID as rid,
           row_number() over (partition by academic_period, load_week, sub_academic_period, person_uid, course_number, course_reference_number) rn
    FROM cea
  )
  where rn > 1
)

OR

delete from emp
where rowid not in
(select max(rowid) from emp group by empno);

If you want to delete huge data then we need to use below syntax for better performance


ALTER SESSION ENABLE PARALLEL DML;

DELETE /*+ PARALLEL(12) */
FROM TABLE_NAME
WHERE COLUMN_NAME='CONDITION'

COMMIT;

ALTER SESSION DISABLE PARALLEL DML;

Aug 30, 2010

Orcl: SQL Joins

Different SQL JOINs

Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.
  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

Aug 29, 2010

Orcl: Rows to columns SQL

Rows to columns SQL:
ORDER_MODE   
ORDER_STATUS  
ORDER_TOTAL
direct
0
100
direct
1
200
online
0
300
online
1
400

 need to convert like this:
Order_MODE
STAT_0
STAT_1
direct
100
200
online
300
400

Method 1:

SQL> SELECT UPPER(o.order_mode) order_mode
                ,SUM(DECODE(o.order_status, 0, o.order_total)) stat_0
                ,SUM(DECODE(o.order_status, 1, o.order_total)) stat_1
   FROM                orders o
   GROUP BY o.order_mode
   ORDER BY 1

Method 2:

SQL> SELECT       UPPER(order_mode) , stat_0, stat_1
   FROM                (
               SELECT   o.order_mode,o.order_status
                      ,SUM(o.order_total) order_total
              FROM     orders o               GROUP BY o.order_mode, o.order_status
                                )
  PIVOT (  SUM(order_total) FOR order_status IN (0 stat_0, 1 stat_1) )
---------------------------------------------------------------------------------------------------
Columns to Rows:

COL_A  COL_B   COL_C
1                2               3

COL D
1
2
3

SELECT COL_A as COL_D from tbl
UNION ALL
SELECT COL_B as COL_D from tbl
UNION ALL
SELECT COL_C as COL_D from tbl;

with tt
  2  as
  3    (
  4      select 1 cola, 2 colb, 3 colc, 4 cold from dual
  5    )
-- End Of Data Part --
  6  select cola
  7  from tt
  8  union all
  9  select colb
 10  from tt
 11  union all
 12  select colc
 13  from tt
 14  union all
 15  select cold
 16  from tt;

      COLA
----------
         1
         2
         3
         4
OR another approach
SELECT * FROM unpivot_test;

        ID CUSTOMER_ID PRODUCT_CODE_A PRODUCT_CODE_B PRODUCT_CODE_C PRODUCT_CODE_D
---------- ----------- -------------- -------------- -------------- --------------
         1         101             10             20             30
         2         102             40                            50
         3         103             60             70             80             90
         4         104            100

4 rows selected.

SQL>
The UNPIVOT operator converts this column-based data into individual rows.

SELECT *
FROM   unpivot_test
UNPIVOT INCLUDE NULLS (quantity FOR product_code IN (product_code_a AS 'A', product_code_b AS 'B', product_code_c AS 'C', product_code_d AS 'D'));

        ID CUSTOMER_ID P   QUANTITY
---------- ----------- - ----------
         1         101 A         10
         1         101 B         20
         1         101 C         30
         1         101 D
         2         102 A         40
         2         102 B
         2         102 C         50
         2         102 D
         3         103 A         60
         3         103 B         70
         3         103 C         80
         3         103 D         90
         4         104 A        100
         4         104 B
         4         104 C
         4         104 D

Aug 28, 2010

Orcl: Primary,Forign,Surrogate,Unique Key


Primary key and unique are Entity integrity constraints
Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered

Unique key constraint is used to prevent the duplication of key values within the rows of a tableand allow null values. (In oracle, one null is not equal to another null)

Primary key can't be null but unique key can be null.

1)unique key can be null but primariy key cant be null.
2)primariy key can be refrenced to other table as FK.
3)we can have multiple unique key in a table but PK is one and only one.
4)PK in itself is unique key.

Surrogate Key: A system generated key with no business value. Usually implemented with database generated sequences.

If you have the EMPLOYEE table as the following:

CREATE TABLE EMPLOYEE ( SERIALNUMBER BIGINT NOT NULL,
FIRSTNAME CHAR(64),
LASTNAME CHAR(64),
SALARY DECIMAL(10, 2),
PRIMARY KEY (SERIALNUMBER))

 You can insert a row with the following statement:

INSERT INTO EMPLOYEE ( SERIALNUMBER, FIRSTNAME, LASTNAME,
SALARY) VALUES(NEXTVAL FOR EMPSERIAL, 'John', 'Smith', 99.99)

 Here you use the "NEXTVAL FOR EMPSERIAL" to obtain the unique value from the SEQUENCE






A foreign key is a field in a relational table that matches the primary key column of another table. The foreign key can be used to cross-reference tables

Feb 5, 2010

Orcl: DDL DML DCL in orcl


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

Informatica: DWH concepts

refer:
http://it.toolbox.com/wiki/index.php/Data_Warehouse_Concepts#Passive_Transformation

http://www.slideshare.net/dwiner/informatica-training-244742

Feb 1, 2010

Orcl: Generate Sequence Unique id's

View and Materialized views


Index

An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns.

Indexes are pointres that maps to the physical address of data. So by using indexes data manipulation becomes faster

View
A view is a logical entity. It is a SQL statement stored in the database in the system tablespace. Data for a view is built in a table created by the database engine in the TEMP tablespace.
View is a logical table. It is a physical object which stores data logically. View just refers to data that is stored in database tables.

Advantages of View:
• Views restrict access to the data because the view can display selective columns from the table.
• Views can be used to make simple queries to retrieve the results of complicated queries. For
Example, views can be used to query information from multiple tables without the user knowing How to write a join statement.
• Views provide data independence for ad hoc users and application programs. One view can be used to retrieve data from several tables.
• Views provide groups of user’s access to data according to their particular criteria.

Simple Views versus Complex Views
There are two classifications for views: simple and complex. The basic difference is related to the
DML (INSERT, UPDATE, and DELETE) operations.
• A simple view is one that:
– Derives data from only one table
– Contains no functions or groups of data
– Can perform DML operations through the view
• A complex view is one that:
– Derives data from many tables
– Contains functions or groups of data
– Does not always allow DML operations through the view

Performing DML Operations on a View
You can perform DML operations on data through a view if those operations follow certain rules.
You cannot remove a row from a view if it contains any of the following:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword
• The pseudocolumn ROWNUM keyword and 
   NOT NULL columns in the base tables that are not selected by the view


What is a materialized view?

A materialized view is a snapshot of data which could be refreshed at defined intervals. From the name, it is unclear that a materialized view can hold data, since views don’t. Views are nothing but a query stored in a Database. Whenever we do a select * from view, it runs the saved query and fetches data.

Sometimes there would be a need for a huge query with many join operations between more than 10-20 tables containing millions of records and many where conditions. Especially in a data warehousing environment or for reporting purposes. In such conditions, running the query each time whenever required is not a feasible option. So, there should be a technique to store the data such that we should run the query only if there is a change in data in the underlying tables There comes the usage of a materialized views as they can store the data they have queried.


Ref:
http://www.w3schools.com/SQl/sql_view.asp
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_8004.htm

Jan 30, 2010

What is an Index

Indexes are optional data structures built on tables. Indexes can improve data retrieval performance by providing a direct access method instead of the default full table scan retrieval method. You can build Btree or bitmap indexes on one or more columns in a table.

An index
key is defined as one data value stored in the index. A Btree index sorts the keys into a
binary tree and stores these keys together with the table's ROWIDs. In a bitmap index,
a bitmap is created for each key. There is a bit in each bitmap for every ROWID in the table,
forming the equivalent of a two-dimensional matrix.The bits are set if the corresponding
row in the bitmap exists.

Btree indexes are the default index type, can be unique or non-unique, and are appropriate for medium- to high-cardinality columns—those having many distinct values. Btree indexes support row-level locking and so are appropriate for multi-user, transactional applications. The indexes supporting a PRIMARY KEY or UNIQUE constraints are Btree indexes.

A bitmap index is a special kind of database index that uses bitmaps.
Bitmap indexes have traditionally been considered to work well for data such as gender, which has a small number of distinct values, for example male and female, but many occurrences of those values. This would happen if, for example, you had gender data for each resident in a city. Bitmap indexes have a significant space and performance advantage over other structures for such data. Some researchers argue that Bitmap indexes are also useful for unique valued data which is not updated frequently.[1] Bitmap indexes use bit arrays (commonly called bitmaps) and answer queries by performing bitwise logical operations on these bitmaps.
Bitmap indexes are also useful in data warehousing applications for joining a large fact table to smaller dimension tables[2] such as those arranged in a star schema.



B*Tree indexes:
Good choice for most uses as they
-maintain the sort order of the data, making it easy to look up range data
-multicolumn indexes: you can use the leading edge columns to resolve a query, even if that query doesn't reference all columns in the index
-they automatically stay balanced
-performance remains relatively constant
- can also specify reverse and unique

Bitmapped indexes:
-use them to index columns with that contain a relatively small number of distinct values
-they are compact, saving space
-were designed for query intensive databases, so not recommended for OLTP databases
-not good for range scans
-are available only in Enterprise Edition


When to Create an Index
Therefore, you should create indexes only if:
• The column contains a wide range of values
• The column contains a large number of null values
• One or more columns are frequently used together in a WHERE clause or join condition
• The table is large and most queries are expected to retrieve less than 2–4% of the rows
Remember that if you want to enforce uniqueness, you should define a unique constraint in the table definition. Then a unique index is created automatically.

When not to Create an Index
It is usually not worth creating an index if:
• The table is small
• The columns are not often used as a condition in the query
• Most queries are expected to retrieve more than 2 to 4 percent of the rows in the table
• The table is updated frequently
• The indexed columns are referenced as part of an
   Expression


for more details:


http://www.dba-oracle.com/art_9i_indexing.htm
http://www.akadia.com/services/ora_bitmapped_index.html
http://www.oracle.com/technetwork/articles/sharma-indexes-093638.html