Thursday, January 10, 2013

Delete last lines from .bash_history

history - View command history from ~/.bash_profile file

history -d $((HISTCMD-2)) && history -d $((HISTCMD-1))

This command will hide the history command and the previous command.

 history -d $((HISTCMD-1))

This command will delete from history only the record of this command.

history -d [line_number]

Deletes command from line [line_number]

Friday, January 4, 2013

MySQL datatypes

Integer data types

Type      Storage Required Signed Range                           Unsigned Range
TINYINT   1 byte           –128 to 127                          0 to 255    
SMALLINT  2 bytes          –32,768 to 32,767                    0 to 65,535
MEDIUMINT 3 bytes          –8,388,608 to 8,388,607              0 to 16,777,215
INT       4 bytes          –2,147,683,648 to 2,147,483,647                          0 to 4,294,967,295
BIGINT    8 bytes          –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807                                       0 to 18,446,744,073,709,551,615

Floating point data types

FLOAT represents single-precision floating-point values that require four bytes each for storage.

DOUBLE represents double-precision floating-point values that require eight bytes each
for storage.

Fixed point data types


DECIMAL uses a fixed-decimal storage format: All values in a DECIMAL column have the same
number of decimal places and are stored exactly as given when possible. DECIMAL values are
not processed quite as efficiently as FLOAT or DOUBLE values (which use the processor’s native
binary format), but DECIMAL values are not subject to rounding error, so they are more accurate.
The NUMERIC data type in MySQL is a synonym for DECIMAL.

BIT data type


The BIT data type represents bit-field values. BIT column specifications take a width indicating
the number of bits per value, from 1 to 64 bits.

String data types


Type Description
CHAR Fixed-length non-binary string
VARCHAR Variable-length non-binary string
TEXT Variable-length non-binary string
BINARY Fixed-length binary string
VARBINARY Variable-length binary string
BLOB Variable-length binary string
ENUM Enumeration consisting of a fixed set of legal values
SET Set consisting of a fixed set of legal values

Non Binary sting data types


Type Storage Required Maximum Length
CHAR(M) M characters 255 characters
VARCHAR(M) L characters plus 1 or 2 bytes 65,535 characters (subject to
limitations)
TINYTEXT L characters + 1 byte 255 characters
TEXT L characters + 2 bytes 65,535 characters
MEDIUMTEXT L characters + 3 bytes 16,777,215 characters
LONGTEXT L characters + 4 bytes 4,294,967,295 characters

Binary string data types


Type Storage Required Maximum Length
BINARY(M) M bytes 255 bytes
VARBINARY(M) L bytes plus 1 or 2 bytes 65,535 bytes (subject to limitations)
TINYBLOB L + 1 bytes 255 bytes
BLOB L + 2 bytes 65,535 bytes
MEDIUMBLOB L + 3 bytes 16,777,215 bytes
LONGBLOB L + 4 bytes 4,294,967,295 bytes

ENUM and SET data types


ENUM is an enumeration type. An ENUM column definition includes a list of allowable values;
each value in the list is called a “member” of the list.
The SET data type, like ENUM, is declared using a comma-separated list of quoted strings that

define its valid members. But unlike ENUM, a given SET column may be assigned a value consisting
of any combination of those members.

Temporal data types


Type Storage Required Range
DATE 3 bytes ‘1000-01-01’ to ‘9999-12-31’
TIME 3 bytes ‘-838:59:59’ to ‘838:59:59’
DATETIME 8 bytes ‘1000-01-01 00:00:00’ to
‘9999-12-31 23:59:59’
TIMESTAMP 4 bytes ‘1970-01-01 00:00:00’ to
mid-year 2037
YEAR 1 byte 1901 to 2155 (for YEAR(4)),
1970 to 2069 (for YEAR(2))








Thursday, January 3, 2013

How to reset current value for sequence

This is one interesting issue regarding altering a sequence to reset CURRENT VALUE.
Because this current value is not specified in CREATE SEQUENCE statement, it can not be reset with ALTER SEQUENCE statement. Instead you have the following methods:

1. Drop and recreate the sequence. Take care of the object affected by this sequence (triggers, procedures, etc.), because they will be invalidated.

2. Use ALTER SEQUENCE command to change some sequence limits and the generate new values

- review your sequence DDL

select 'create sequence '||sequence_name||
       ' increment by '||increment_by||
       ' start with '||last_number||
       ' maxvalue '||max_value||
       decode(cycle_flag,'N',' NOCYCLE ',' CYCLE ')||
       decode(cache_size,0,'NOCACHE ','CACHE '||cache_size)
 from user_sequences where sequence_name = 'SEQ_TEST';


- view current value for this sequence
select seq_test.currval from dual;
5

- change the maximum value of the sequence equal to current value and make the sequence to cycle if maxvalue is reach
alter sequence seq_test maxvalue 5 cycle nocache;


- generate new value for the sequence
select seq_test.nextval from dual;

- check that the new value is 0

select seq_test.currval from dual;
0

- use ALTER statement to change the sequence parameters like they use to be

alter sequence seq_test nomaxvalue nocycle cache 20;

2012 Oracle events in Bucharest

Even if we've just entered in 2013, here is the summary of two events that took place in Bucharest in October and November in Bucharest: Oracle Day 2012 and MySQL workshop. Oracle Day was the opportunity to get some details about the announcements made at Oracle Open World 2012.
Those 2 events highlighted the main directions for Oracle in developing and improving his 2 databases: Oracle Database and MySQL Database.

Oracle Day 2012Oracle Open World announcements:
•              Infrastructure as a Service – IaaS
•             Complete Cloud Offering 
◦                     SaaS,
◦                     PaaS,
◦                     IaaS
•             Exadata
•             Exalogic 

2. Oracle Private Cloud


3. Oracle Database 12c
Oracle Database 12c into Oracle Cloud – Multitenant database
•         multitenancy, enables users to create multiple "pluggable" databases that reside within a single database container
•         "heat map“ tracks how frequently different chunks of data are used
.•         Database upgrades and patches are made simpler than in the past thanks to the pluggable database concept.
•         Backup and recovery efforts benefit as well.

4. EXADATA X3 & EXALOGIC X3
•         Exadata X3 (www.youtube.com/watch?v=vcA71QGEhzI)
•          Database In-Memory Machine
◦              26 TB in DRAM (4) in Flash (22) in one rack
◦              X3H2M2 (X3 Heuristic Hierachical Mass Memmory) – Automatically keeps all active data in memory
•          All Active Data in Memory
•          Exadata Database Cloud
•          New Entry-level Eighth Rack
•          Exalogic X3
•          Extreme Performance For Java Applications
•          Extreme Performance For Oracle Business Applications
•          Natively Leverages Exadata
•          Best Consolidation Platform
•          Entry-level Eighth Rack
http://cloud.oracle.com 

Parallel sessions
•         Cloud
•          Instrastructure as a Service
•          Database as a Service
•          Midleware as a Service
•         Customer Experience•          Talent management (Oracle Taleo Cloud Service)
•          Customer experience (Oracle RightNow CX Cloud Service)
•         Data Center•          Exadata, Exalogic, Exalitycs
•         Enterprise Applications•          Business Intelligence
•          Business Process Modelling

MySQL workshop
•         MySQL 5.6 RC (Release Candidate)
•          MySQL Enterprise
•          What’s new in MySQL 5.6
•         MySQL Cluster 7.3 DMR1 (Developemnt Milestone Release)
•          What’s new

 MySQL 5.6 Enterprise Edition
•         MySQL Support
•         MySQL External Authentication
•         MySQL Enterprise Audit
•         MySQL Thread Pool
•         MySQL Enterprise Monitor
•         MySQL Enterprise Backup

 MySQL 5.6 RC
•         InnoDB engine
•          SSD optimization
◦              Page size from 4K to 64K
◦              Separate tablespaces for InnoDB Undo Log
•          Innodb_log_file_size (redo) 4GB limit dropped
•          Online DDL operations
◦              CREATE/DROP INDEX, ADD/DROP FOREIGN KEY
◦              Add, drop, rename, reorder, chane NULL/NOT_NULL for COLUMN
•          Persistent optimizer statistics
•          Optimized for READ ONLY workloads
◦              Autocommit=1: automatic
◦              Autocommit=0: START TRANSACTION READ ONLY
•          NoSQL solution for MySQL - delivered via memcached
•          Full Text Search 

MySQL 5.6 RC
•         Replication
•          Global Transaction IDs
◦              Unique identifier for each transaction written to the Binlog
•          Multi Threaded Slaves
◦              Great for systems which isolate application data using databases – e.g. multi-tenant
•          Optimized row base replication
◦              Binlog-row-image=minimal
•          Crash-safe Slaves
◦              Binlog and table data are transactionally consistent
•          Replication event checksum
 
MySQL 5.6 RC
•         Performance schema
•         Security
•          Password strength policies
•          Stronger password hashing
•         Other
•          Default optimized configuration
•          TIME/TIMESTAMP/DATETIME - fractional second precision
•          Improved partition


MySQL Cluster 7.3
•         MySQL Cluster is designed for
•          Short transactions
•          Many parallel transactions
 
MySQL Cluster
•         MySQL Cluster 7.2 GA
•          Adaptive Query Localization (AQL) – ndb_join_pushdown=on
•          Distribution Aware App
•          Connection pooling between MySQL Servers and data node
◦              ndb-cluster-connection-pool > 1 in my.cnf 
 •          NoSQL API
•         What’s new in MySQL 7.3 (EA)•          Autoinstaller
•          Support for Foreign Keys
•          Integration with the latest MySQL Server
•          New NoSQL APIs;
  

ORA-14060 - Partition key can not be changed


When you want to partition a table be careful about the datatype and length of tahat column, because you can not issue an ALTER command to modify it.
For example, when trying to change the partition column data type from data to timestamp, following error appears:

ALTER TABLE PARTITION_TABLE MODIFY (create_time TIMESTAMP)

Error report:
SQL Error: ORA-14060: data type or length of a table partitioning column may not be changed
14060. 00000 -  "data type or length of a table partitioning column may not be changed"
*Cause:    User issued ALTER TABLE statement attempting to modify
           data type and/or length of a column used to partition the
           table named in ALTER TABLE statement, which is illegal
*Action:   Avoid modifying data type and/or length of table
           partitioning column(s)

Wednesday, December 12, 2012

Oracle Startup/Shutdown scripts

For Oracle 11gR2 you have the opportunity to use Oracle Restart, but to use it you must install Grid Infrastructure. If you don't want to use GI, you can use the scripts below:

vi /etc/init.d/dbora


#!/bin/sh
# chkconfig: 345 99 10
# description: Oracle automatic startup/shutdown script.
#
# Set ORA_OWNER to the user id of the owner of the Oracle database software.

ORA_OWNER=oracle

case "$1" in
    'start')
        # Start the Oracle databases:
        su - $ORA_OWNER -c "/home/oracle/scripts/startup.sh >> /home/oracle/scripts/startup_shutdown.log 2>&1"
        touch /var/lock/subsys/dbora
        ;;
    'stop')
        # Stop the Oracle databases:
        su - $ORA_OWNER -c "/home/oracle/scripts/shutdown.sh >> /home/oracle/scripts/startup_shutdown.log 2>&1"
        rm -f /var/lock/subsys/dbora
        ;;
esac

chmod 750 dbora

vi /home/oracle/scripts/startup.sh

#!/bin/bash

export ORACLE_SID=DB11G
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/dbhome_1
export PATH=$PATH:$ORACLE_HOME/bin

# Start Listener
lsnrctl start

# Start Database
sqlplus / as sysdba << EOF
STARTUP;
EXIT;
EOF

chmod 755 startup.sh

vi /home/oracle/scripts/shutdown.sh

#!/bin/bash

export ORACLE_SID=sapcc
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/dbhome_1
export PATH=$PATH:$ORACLE_HOME/bin

# Start Listener
lsnrctl stop

# Start Database
sqlplus / as sysdba << EOF
SHUTDOWN IMMEDIATE;
EXIT;
EOF

chmod 755 shutdown.sh

Running scripts as root:

/etc/init.d/dbora stop
/etc/init.d/dbora start

Running as service:

chkconfig --add dbora
chkconfig --list dbora
dbora           0:off   1:off   2:off   3:on    4:on    5:on    6:off

service dbora stop
service dbora start

Wednesday, November 14, 2012

HOW TO SQL - NULL values


NULL values often generate unexpected results when they appear in SQL queries. This is because not always these NULL values are understood. So, what about those NULL  values?
LNNVL
NULLIF
NVL
NVL2

It’s probably best to begin with a few words about what NULL is NOT:
·         NULL is not the number 0
·         NULL is not the empty string
NULL is a special placeholder in SQL used to indicate that the value does not exist in the database, that the value is unknown.
Now let’s explore some unknown NULL values!
·         Comparison with null values is done with special syntax IS NULL or IS NOT NULL, and doesn’t use comparison operands like =, <>, >, <.

select employee_id from employees where manager_id=NULL;

no rows selected

SQL> select employee_id from employees where manager_id IS NULL;

EMPLOYEE_ID
-----------
        100

·         Because the value of NULL values is unknown, unknown is also the result of any operation with NULL.

select 5+7+null+9 as suma from dual;

      SUMA
----------
       NULL

·         The truth table is also influenced by NULL values as follows, an interesting case being FALSE or NULL = NULL:

Bool1           Bool2           AND              OR
TRUE             TRUE             TRUE             TRUE
TRUE             FALSE           FALSE           TRUE
TRUE             NULL            NULL            TRUE
FALSE           TRUE             FALSE           TRUE
FALSE           FALSE           FALSE           FALSE          
FALSE           NULL            FALSE           NULL
NULL            TRUE             NULL            TRUE
NULL            FALSE           FALSE           NULL
NULL            NULL            NULL            NULL
 
·         To view how unknown NULL values are treated in databases, let’s take the example of DEPARTMENTS table, where there are some departments with no manager (manager_id is NULL).

SELECT * FROM DEPARTMENTS WHERE MANAGER_ID <= 200
UNION ALL
SELECT * FROM DEPARTMENTS WHERE MANAGER_ID > 200;

This SQL, which is a UNION ALL between 2 sets of data that covers all values for MANAGER_ID will not return all departments, as someone would expect, but only those with a known value for manager_id.  

10     Administration       200    1700
30     Purchasing           114    1700
50     Shipping             121    1700
60     IT                   103    1700
80     Sales                145    2700
90     Executive            100    1700
100    Finance              108    1700
20     Marketing            201    1700
40     Human Resources      203    2700
70     Public Relations     204    2700
110    Accounting           205    1700

·         Another thing that is related to the unknown character of NULL values is that NULL values aren’t stored in INDEXES. This is why queries having condition IS NULL don’t use index, even if there is one defined for the column specified in condition. On the contrary, the index is used in queries having conditions IS NOT NULL.

select * from employees where manager_id is null;

-------------------------------------------------------------------------------
| Id  | Operation         | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |           |     1 |    69 |     3   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMPLOYEES |     1 |    69 |     3   (0)| 00:00:01 |
-------------------------------------------------------------------------------

select * from employees where manager_id is not null;

--------------------------------------------------------------------------------
| Id  | Operation                   | Name           | Rows  | Bytes | Cost
--------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |                |   107 |  7383 |     9  
|   1 |  TABLE ACCESS BY INDEX ROWID| EMPLOYEES      |   107 |  7383 |     9  
|*  2 |   INDEX FULL SCAN           | EMP_MANAGER_IX |   107 |       |     1  
--------------------------------------------------------------------------------

·         In sorting operation, NULL values appear LAST in ASC order and FIRST in DESC order.

select * from departments order by manager_id ASC;

           90 Executive                             100        1700
           60 IT                                    103        1700
          …….
          110 Accounting                            205        1700
          230 IT Helpdesk                           NULL       1700
          240 Government Sales                      NULL       1700
          ……
          140 Control And Credit                    NULL       1700


select * from departments order by manager_id DESC;

          140 Control And Credit                    NULL       1700
          ………
          160 Benefits                              NULL       1700
          110 Accounting                            205        1700
          ……
           90 Executive                             100        1700

·         All aggregate functions except COUNT(*) and GROUPING ignore nulls. You can use the NVL function in the argument to an aggregate function to substitute a value for a null. COUNT never returns null, but returns either a number or zero. For all the remaining aggregate functions, if the data set contains no rows, or contains only rows with nulls as arguments to the aggregate function, then the function returns null.

SELECT COUNT(*) FROM DEPARTMENTS;

  COUNT(*)
----------
        27

SQL> select count(manager_id) from departments;

COUNT(MANAGER_ID)
-----------------
               11

select min(manager_id) from departments;

MIN(MANAGER_ID)
---------------
            100

SQL> select max(manager_id) from departments;

MAX(MANAGER_ID)
---------------
            205

·         NULL does not equal NULL or other value

select * from a;

        C1         C2
---------- ----------
         1          1
         1          2
         1      NULL
      NULL      NULL

select * from a where c1=c2;

        C1         C2
---------- ----------
1             1

·         The NULL-related functions facilitate null handling. The NULL-related functions are:
COALESCE

·         Null have different behavior in NOT  IN and NOT EXISTS.
Take, for example, the case of returning all employees that has no managers:

SELECT * FROM HR.EMPLOYEES WHERE EMPLOYEE_ID NOT IN ( SELECT MANAGER_ID FROM HR.EMPLOYEES );

no rows selected

SELECT * FROM HR.EMPLOYEES E1 WHERE NOT EXISTS ( SELECT 1 FROM HR.EMPLOYEES E2 WHERE E2.EMPLOYEE_ID = E1.MANAGER_ID);

        100 Steven               King
SKING                     515.123.4567         17-JUN-98 AD_PRES         24000
                                     90
                or departments with no employees:

SELECT department_id FROM hr.departments
WHERE department_id
NOT IN (SELECT department_id FROM HR.EMPLOYEES);

            no rows selected
           
SELECT DEPARTMENT_ID FROM HR.DEPARTMENTS d
WHERE NOT EXISTS (SELECT 1
FROM HR.EMPLOYEES e where e.department_id = d.department_id);

DEPARTMENT_ID
-------------
          120
          130
          140
………

As you can see, this happens because one or more values in NOT IN clause are NULL (UNKNOWN), and the predicate  department_id NOT IN (x,y,NULL) evaluates to neither TRUE, nor FALSE, but to UNKNOWN (NULL).
This is why, NOT IN can be used if all the values that must be evaluated differ from NULL value.

As a conclusion of this short intro, the existence of NULL values into a database introduces a new degree of uncertainty. If not understood, a lot of guessing must be done by an SQL programmer to counter for erroneous results of NULL values in a database.