Monday, July 18, 2022

 Flashback Query

===============

https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9012.htm#SQLRF01802



=====================================

== Flashback Dropped table

=====================================



select * from dba_recyclebin;



FLASHBACK TABLE "ABMS"."BIN$hsZyomKSL6vgU8MBIgo32A==$0" TO BEFORE DROP RENAME TO WR80186_REFRESH_DATA_Orig;



FLASHBACK TABLE flashback_drop_test TO BEFORE DROP RENAME TO flashback_drop_test_old;





=====================================

== Method 1  Data as of 120 Min old  

=====================================

 


select

*

from abms.KSD_PROGRAM_BASIC

as of timestamp (systimestamp -interval '120' minute)

WHERE FK_CSB_CASE_NO IN (SELECT TRG_CASE_NUMBER FROM KEES62906_ISS_ST_DOC_ST_BLNK_U)

AND PROGRAM_TYPE = 'CC'

/


=====================================

=== Method 2

=====================================


create table abms.test22 as 

SELECT * FROM abms.sys_transact

AS OF TIMESTAMP TO_TIMESTAMP('02-SEP-2017 03:00:00', 'DD-MON-YYYY HH24:MI:SS');

create table akumar.KSD_PROGRAM_MONTH_FB as

select

/*+ parallel(KSD_PROGRAM_MONTH,5) */  *

from abms.KSD_PROGRAM_MONTH

as of timestamp (systimestamp -interval '120' minute)

WHERE FK_CSB_CASE_NO IN (SELECT TRG_CASE_NUMBER FROM KEES62906_ISS_ST_DOC_ST_BLNK_U)

AND FK_PGB_PROG_TYPE = 'CC';

/


=====================

 AWR Manual 


=================

--#########################################

-- How to Create Manual or AdHoc Snapshot 

--#########################################


EXEC DBMS_WORKLOAD_REPOSITORY.create_snapshot;



--#########################################

-- How to Pull AWR Reports Manually 

--#########################################


--Step1 Get DBID First 


SELECT DBID, instance_number, snap_id, begin_interval_time, end_interval_time

  FROM dba_hist_snapshot

 where begin_interval_time > sysdate - 3

 ORDER BY snap_id desc;

  

-- Run the following SQL


select output from table(dbms_workload_repository.awr_report_html(DBID inst_id, begin_id, end_id));

-- example

select output from table(dbms_workload_repository.awr_report_html(2981674854, 1, 29374, 29376));


 

===================

 SQL Tuning , "SQL Tuning"

--##################################################

-- From Current SQL

-- Note Try Runnning from the Correct Instance and 

-- May be directly from the server

--##################################################

DECLARE

  l_sql_tune_task_id  VARCHAR2(100);

BEGIN

  l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (

                          sql_id      => 'bd64yscq8sayf',

                          scope       => DBMS_SQLTUNE.scope_comprehensive,

                          time_limit  => 2500,

                          task_name   => 'bd64yscq8sayf_5',

                          description => 'bd64yscq8sayf');

  DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);

END;

/



--SELECT *  FROM   DBA_ADVISOR_TASKS  where task_name='cgm9r2w1fgkbh';


EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => 'cgm9r2w1fgkbh_6');


SELECT DBMS_SQLTUNE.report_tuning_task('bd64yscq8sayf_6') AS recommendations FROM dual;

 Tablespace Usage,  Space Usage

set pagesize 3000


-- ALTER TABLESPACE  PDB_TEMP   AUTOEXTEND ON MAXSIZE 100G;  


 SELECT df.tablespace_name tablespace_name,

 max(df.autoextensible) auto_ext,

 to_char(round(df.maxbytes / (1024 * 1024), 0),'999,999,999') max_ts_size,

 round((df.bytes - sum(fs.bytes)) / (df.maxbytes) * 100, 0) max_ts_pct_used,

 to_char(round(df.bytes / (1024 * 1024), 0),'999,999,999') curr_ts_size,

 to_char(round((df.bytes - sum(fs.bytes)) / (1024 * 1024), 0),'999,999,999') used_ts_size

FROM dba_free_space fs,

 (select tablespace_name,

 sum(bytes) bytes,

 sum(decode(maxbytes, 0, bytes, maxbytes)) maxbytes,

 max(autoextensible) autoextensible

 from dba_data_files

 group by tablespace_name) df

WHERE fs.tablespace_name (+) = df.tablespace_name

GROUP BY df.tablespace_name, df.bytes, df.maxbytes

UNION ALL

SELECT df.tablespace_name tablespace_name,

 max(df.autoextensible) auto_ext,

 to_char(round(df.maxbytes / (1024 * 1024), 2),'999,999,999') max_ts_size,

 round((df.bytes - sum(fs.bytes)) / (df.maxbytes) * 100, 0) max_ts_pct_used,

 to_char(round(df.bytes / (1024 * 1024), 2),'999,999,999') curr_ts_size,

 to_char(round((df.bytes - sum(fs.bytes)) / (1024 * 1024), 2),'999,999,999') used_ts_size

FROM (select tablespace_name, bytes_used bytes

 from V$temp_space_header

 group by tablespace_name, bytes_free, bytes_used) fs,

 (select tablespace_name,

 sum(bytes) bytes,

 sum(decode(maxbytes, 0, bytes, maxbytes)) maxbytes,

 max(autoextensible) autoextensible

 from dba_temp_files

 group by tablespace_name) df

WHERE fs.tablespace_name (+) = df.tablespace_name

GROUP BY df.tablespace_name, df.bytes, df.maxbytes

ORDER BY 4 desc;

 ABMSBATCH, KILL SESSION, QUERY,  MONITOR




--#########################################################

-- Monitor the Current running SQL

--#########################################################


select * from gv$session where username ='ABMSBATCH';


alter system flush shared_pool;


select distinct inst_id, plan_hash_value,sql_id,executions exec,rows_processed rows_ ,round(ELAPSED_TIME/1000000) TIME_SEC,round(ELAPSED_TIME/60000000) Min , 

buffer_gets bufr_gets,

parsing_schema_name schema, sql_text 

from  gv$sql 

where sql_id in

(

select sql_id

from gv$session s

WHERE   s.username ='ABMSBATCH'

)

and sql_text not like '%DBMS%APP%'

order by TIME_SEC desc;

 


--#########################################################

-- Monitor the Current running SQL - Via SQLMonitor

--#########################################################


select  

    inst_id, status, sql_id, 

    to_char(sql_exec_start,'DD-Mon HH:MI') SQL_START, 

    to_char(last_refresh_time,'DD-Mon HH:MI') last_refresh_time,

    round((sysdate - sql_exec_start)*(24*60)) Min,

    refresh_count,sql_plan_hash_value, sid,session_serial# serial#,

    sql_text

from gv$sql_monitor

where status not like  '%DONE%'

order by elapsed_time desc;



select 'alter system kill session ''' || sid ||','||serial# ||',@'|| inst_id ||''' immediate;'  

from  gv$session 

where  username ='TESTUSER'

and sql_id='5mdjfv8594zj8';




--#########################################################


-- How may ABMSBATCH  Sessions in Database

select  count(*) from gv$session  where username ='TESTUSER'   ;


-- How may ABMSBATCH Sessions per instance

select  inst_id,sql_id,count(*) from gv$session  where username ='TESTUSER' group by inst_id,sql_id  ;


-- ABMSBATCH with SID

select  inst_id,sql_id,sid,count(*) from gv$session  where username ='TESTUSER' group by inst_id,sql_id,sid  ;


-- ABMSBATCH active sessions with SQL ID

select  inst_id,sql_id,status,count(*) from gv$session  where username ='TESTUSER' and status ='ACTIVE'  group by inst_id,sql_id,status  ;


-- ABMSBATCH active sessions with SQL ID - Spacific sql

select  inst_id,sql_id,status,count(*) from gv$session  where username ='TESTUSER' where sql_id ='&SQLID'  group by inst_id,sql_id,status  ;


-- Longops all ABMSBATCH

select * from gv$session_longops where username ='TESTUSER' ;  


-- Longops ABMSBATCH specific SQL

select * from gv$session_longops where username ='TESTUSER' and sql_id ='&SQLID';

 

---------------------------------------

-- SQL Area Stats - One ABMSBATCH SQL

---------------------------------------

select inst_id,rows_processed,hash_value,plan_hash_value, sql_profile from gv$sqlarea where sql_id ='&SQLID' order by 1;


---------------------------------------

-- SQL Area Stats - ALL ABMSBATCH SQL

----------------------------------------

select distinct inst_id, sql_id,executions,rows_processed,round(ELAPSED_TIME/1000000) ELAPSED_TIME,sql_text 

from  gv$sql 

where sql_id in

(

select sql_id

from gv$session s

WHERE   s.username ='TESTUSER'

)

and sql_text not like '%DBMS%APP%'

order by elapsed_time desc;


select * from gV$ACTIVE_SESSION_HISTORY where sql_id ='&SQLID';



SELECT optimizer_mode_mismatch, reason

FROM gv$sql_shared_cursor

WHERE sql_id ='&SQLID'

AND child_number = 0;

 


=====================================

-- Find Who is Blocking Session

=====================================


SELECT DISTINCT S1.USERNAME || '@' || S1.MACHINE

|| ' ( INST=' || S1.INST_ID || ' SID=' || S1.SID || ' Serial=' || S1.SERIAL# || ' ) IS BLOCKING '

|| S2.USERNAME || '@' || S2.MACHINE || ' ( INST=' || S1.INST_ID || ' SID=' || S2.SID || ' ) ' AS BLOCKING_STATUS

FROM GV$LOCK L1, GV$SESSION S1, GV$LOCK L2, GV$SESSION S2

WHERE S1.SID=L1.SID AND S2.SID=L2.SID

AND S1.INST_ID=L1.INST_ID AND S2.INST_ID=L2.INST_ID

AND L1.BLOCK > 0 AND L2.REQUEST > 0

AND L1.ID1 = L2.ID1 AND L1.ID2 = L2.ID2

order by 1; 


=====================================

-- Find Blocking Objects - Query1

=====================================


alter system kill session 'SID,SERERIAL,@INST' immediate;

 

SELECT d.OBJECT_ID, substr(OBJECT_NAME,1,20), l.SESSION_ID, l.ORACLE_USERNAME, l.LOCKED_MODE

from   gv$locked_object l, dba_objects d

where  d.OBJECT_ID=l.OBJECT_ID;


SELECT XIDUSN,OBJECT_ID,SESSION_ID,ORACLE_USERNAME,OS_USER_NAME,PROCESS from gv$locked_object;


select * from gv$locked_object;


select * from sys.obj$ where obj#=&OBJID;


=====================================

-- Find Blocking Objects - Query2

=====================================


select

   sess.sid,

   sess.serial#,

   lo.oracle_username,

   lo.os_user_name,

    ao.object_name,

    lo.locked_mode

 from

   v$locked_object lo,

   dba_objects     ao,

   v$session       sess

where

   ao.object_id = lo.object_id

and

   lo.session_id = sess.sid;



#################################


-- BLOCKING

--------------


select inst_id,sid,sql_id,username,status,WAIT_CLASS,WAIT_TIME,SECONDS_IN_WAIT,STATE, BLOCKING_SESSION_STATUS ,

 BLOCKING_INSTANCE     ,

 BLOCKING_SESSION  ,

 FINAL_BLOCKING_SESSION_STATUS  ,

 FINAL_BLOCKING_INSTANCE     ,

 FINAL_BLOCKING_SESSION

from gv$session 

where 

 username  in ('TESTUSER')

 ;


-- SPID 

SELECT s.inst_id,s.sid,p.spid ,s.osuser,s.status,  s.sql_id,s.prev_sql_id,s.*

FROM   gv$session s

       JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id

WHERE   s.username ='TESTUSER'

and  s.status ='ACTIVE'

;



select

  distinct s.snap_id,to_char(s.begin_interval_time,'mm-dd hh24')  c1,

  sql.sql_id               c2,   

  sql.executions_delta     exe_delta,

  sql.buffer_gets_delta    buffer_gets_delta,

  sql.disk_reads_delta     disk_reads_delta,

  sql.iowait_delta         iowait_delta,

  sql.apwait_delta         apwait_delta,

  sql.ccwait_delta         ccwait_delta

from

   dba_hist_sqlstat        sql,

   dba_hist_snapshot         s

where

   s.snap_id = sql.snap_id

   and

   sql_id = '68p9v83zkp64h'

order by

   c1 desc,

   c2

;



---------------------------------------

-- My Session

---------------------------------------


select  sys_context('USERENV','SID')  from dual;

select  sid from  v$mystat where   rownum <=1;

select to_number(substr(dbms_session.unique_session_id,1,4),'XXXX') mysid from dual; 



---------------------------------------

-- Sessions

---------------------------------------


select * from gv$instance;

select inst_id,count(*) from gv$session group by inst_id;


select inst_id,machine,count(*) from gv$session group by inst_id,machine order by machine;


select username,count(*) from gv$session group by username order by username;


select inst_id,username,count(*) from gv$session group by username,inst_id order by username,inst_id;

 

select username,sql_id,count(*) 

from gv$session 

where status='ACTIVE' 

and username is not null

group by username,sql_id order by 1;



SELECT  *

FROM   gv$session  

WHERE   type != 'BACKGROUND'

and  status ='ACTIVE' 

and username is not null

order by username ;


-- List All Logged Users  info1


SELECT  inst_id ,username, osuser, status , count(*)

FROM   gv$session  

WHERE   type != 'BACKGROUND'

and username is not null

--and  status ='ACTIVE'

group by  inst_id ,username,osuser, status 

order by 2,1 ;


---------------------------------------

-- Kill Query list all Shared Global Sessions  

---------------------------------------

SELECT s.inst_id,s.sid,p.spid spid_to_kill  ,s.osuser,s.status , s.sql_id,s.prev_sql_id, s.*

FROM   gv$session s

       JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id

WHERE  s.type != 'BACKGROUND'

--and    s.sid=9264

--and    s.inst_id=2

and    s.username ='SHARED_GLOBAL'

 


---------------------------------------

-- list Blocking Sessions

---------------------------------------


select 

   blocking_session, 

   sid, 

   serial#, 

   wait_class,

   seconds_in_wait

from 

   gv$session

where 

   blocking_session is not NULL

order by 

   blocking_session;



select

   sess.sid,

   sess.serial#,

   lo.oracle_username,

   lo.os_user_name,

    ao.object_name,

    lo.locked_mode

 from

   v$locked_object lo,

   dba_objects     ao,

   v$session       sess

where

   ao.object_id = lo.object_id

and

   lo.session_id = s.sid;








select  sys_context('USERENV','SID')  rom dual;

select  sid from  v$mystat where   rownum <=1;

select to_number(substr(dbms_session.unique_session_id,1,4),'XXXX') mysid from dual; 

---------------------------------------

-- Sessions

---------------------------------------


select * from gv$instance;

select inst_id,count(*) from gv$session group by inst_id;


select inst_id,machine,count(*) from gv$session group by inst_id,machine order by machine;


select username,count(*) from gv$session group by username order by username;


select inst_id,username,count(*) from gv$session group by username,inst_id order by username,inst_id;


show parameter global;




 

  

 




-- List Summary of Total Sessions in the Database Instance

SELECT  inst_id , status , count(*)

FROM   gv$session  

WHERE   type != 'BACKGROUND'

group by   inst_id   ,status 

order by 1 ;


---------------------------

-- ABMSBATCH  Related

---------------------------

 

 SELECT optimizer_mode_mismatch, reason

FROM gv$sql_shared_cursor

WHERE sql_id ='2h224cxcq878r'

AND child_number = 0;


select distinct inst_id, sql_id,executions,rows_processed,round(ELAPSED_TIME/1000000) ELAPSED_TIME,sql_text 

from  gv$sql 

where sql_id in

(

select prev_sql_id

from gv$session s

WHERE   s.username ='TESTUSER'

)

and sql_text not like '%user$%' and sql_text not like '%role$%' and sql_text not like '%DBMS%APP%'

and sql_text not like '%tab$%'

order by elapsed_time desc;

order by sql_id;



select s.inst_id,s.username,s.status, sql_id,prev_sql_id,count(*)

from gv$session s

WHERE   s.username ='TESTUSER'

group by  s.inst_id,s.username,s.status,sql_id,prev_sql_id;


select * from gv$sql;


select * from gv$session;


select distinct inst_id, sql_id,executions,rows_processed,ELAPSED_TIME,sql_text from  gv$sql where sql_id in

(

select prev_sql_id

from gv$session s

WHERE   s.username ='TESTUSER'

)

order by sql_id;

 

select distinct inst_id, sql_id,sql_text from  gv$sql where sql_id in

(

select prev_sql_id

from gv$session s

WHERE   s.username ='TESTUSER'

--and status ='ACTIVE'

 );


select   sql_id, sum(executions),sum(ROWS_PROCESSED), sql_text from  gv$sql where sql_id in

(

select prev_sql_id

from gv$session s

WHERE   s.username ='TESTUSER'

--and status ='ACTIVE'

 )

 group by sql_id,sql_text;

   


 

SELECT s.inst_id,s.sid,p.spid ,s.osuser,s.status, s.*

FROM   gv$session s

       JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id

WHERE   s.username ='TESTUSER'

and  s.status ='ACTIVE'

;




---------------------------------------

-- Kill Query list all Shared Global Sessions  

---------------------------------------

SELECT s.inst_id,s.sid,p.spid spid_to_kill  ,s.osuser,s.status, s.*

FROM   gv$session s

       JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id

WHERE  s.type != 'BACKGROUND'

--and    s.sid=9264

--and    s.inst_id=2

and    s.username ='SHARED_GLOBAL'

;



---------------------------------------

-- list all Sessions

---------------------------------------


select username,machine,count(*),status, service_name

from gv$session 

where username is not null 

and username not in ('TESTUSER','DBSNMP')

and osuser not in ('oracle')

group by  username,machine,osuser,status,module, service_name order by 1,2,3;


 


select username,status,WAIT_CLASS,WAIT_TIME,SECONDS_IN_WAIT,STATE, BLOCKING_SESSION_STATUS ,

 BLOCKING_INSTANCE     ,

 BLOCKING_SESSION  ,

 FINAL_BLOCKING_SESSION_STATUS  ,

 FINAL_BLOCKING_INSTANCE     ,

 FINAL_BLOCKING_SESSION

from gv$session 

where 

 username  in ('TESTUSER')

 ;


 


---------------------------------------

-- list Blocking Sessions

---------------------------------------


select 

   blocking_session, 

   sid, 

   serial#, 

   wait_class,

   seconds_in_wait

from 

   gv$session

where 

   blocking_session is not NULL

order by 

   blocking_session;



select

   sess.sid,

   sess.serial#,

   lo.oracle_username,

   lo.os_user_name,

    ao.object_name,

    lo.locked_mode

 from

   v$locked_object lo,

   dba_objects     ao,

   v$session       sess

where

   ao.object_id = lo.object_id

and

   lo.session_id = s.sid;



2k2a2ys5mjhkf





RMAN -1

============================

-- Run in root container

============================


COL in_sec FORMAT a10

COL out_sec FORMAT a10

COL TIME_TAKEN_DISPLAY FORMAT a10

SELECT SESSION_KEY, 

       OPTIMIZED, 

       COMPRESSION_RATIO, 

       INPUT_BYTES_PER_SEC_DISPLAY in_sec,

       OUTPUT_BYTES_PER_SEC_DISPLAY out_sec, 

       TIME_TAKEN_DISPLAY

FROM   V$RMAN_BACKUP_JOB_DETAILS

ORDER BY SESSION_KEY;



select s.inst_id, o.sid, CLIENT_INFO ch, context, sofar, totalwork,

                    round(sofar/totalwork*100,2) "% Complete"

     FROM gv$session_longops o, gv$session s

     WHERE opname LIKE 'RMAN%'

     AND opname NOT LIKE '%aggregate%'

     AND o.sid=s.sid

     AND totalwork != 0

     AND sofar <> totalwork;



select SID, START_TIME,TOTALWORK, sofar, round((sofar/totalwork) * 100)  done,

to_char(sysdate + TIME_REMAINING/3600/24,'dd-MON-yy hh:mi AM') end_at

from gv$session_longops

where totalwork > sofar

AND opname NOT LIKE '%aggregate%'

AND opname like 'RMAN%'

/


SELECT SID, SPID, CLIENT_INFO, event, seconds_in_wait secs, p1, p2, p3

  FROM gV$PROCESS p, gV$SESSION s

  WHERE p.ADDR = s.PADDR

  and  p.inst_id = s.inst_id

  and CLIENT_INFO   like '%rman%'

/



SELECT sid, serial#, sofar, totalwork, opname,

round(sofar/totalwork*100,2) AS pct_complete

FROM gv$session_longops

WHERE opname LIKE 'RMAN%'

AND opname NOT LIKE '%aggregate%'

AND totalwork != 0

AND sofar <> totalwork;


Monday, November 30, 2020

 LISTENER SCAN LISTENERS

#######################################

Two Types of Listener

#######################################

1) Local listener called "LISTENER"

2) SCAN Listener  called "LISTENER_SCAN1/2/3"

Check using this must list SCAN_LISTENER and LISTENER

ps -ef | grep -i listener  

they must be running from the GRID Home

LISTENER

==============

srvctl start/stop/status   listener  will stop LISTENER on local node

srvctl start/stop/status   scan_listener will stop LISTENER_SCAN1/2/3 on ALL local node

Note: services are registered in all Listeners

Check 

========

1) Service is running or Not  [use srvctl status service -d pcfxm]

2) Does Listener Knows about the Service [use  lsnrctl ]

lsnrctl services LISTENER

lsnrctl services LISTENER_SCAN1

lsnrctl services LISTENER_SCAN2

lsnrctl services LISTENER_SCAN3

srvctl config scan_listener

========================================================================


[oracle@orastby01a:/apps/crs/12.2.0.1/bin]$ srvctl status scan_listener

SCAN Listener LISTENER_SCAN1 is enabled

SCAN listener LISTENER_SCAN1 is running on node orastby01a

SCAN Listener LISTENER_SCAN2 is enabled

SCAN listener LISTENER_SCAN2 is running on node orastby02a

SCAN Listener LISTENER_SCAN3 is enabled

SCAN listener LISTENER_SCAN3 is running on node orastby02a

============= Services ============


only one command

lsnrctl services 

srvctl add database -d  dbname  -o /apps/oracle/product/11.2.0.4/db

srvctl add instance -d dbname   -i pcfxm1 -n orastby01a

srvctl add instance -d dbname   -i pcfxm2 -n orastby02a

srvctl add service -d dbname   -s vinservice -r pcfxm1 -a pcfxm2

srvctl add service -d dbname   -s oilservice -r pcfxm1 -a pcfxm2

srvctl add service -d dbname  -s gasservice -r pcfxm1 -a pcfxm2


Thursday, September 17, 2015

Setup VNC server

On Linux  Server as root

Install Software  using  yum repository
yum install vnc-server
yum -y install libXfont
yum install xterm
yum install xorg

Change a File  & Add oracle and Port
vi /etc/sysconfig/vncservers
VNCSERVERS="1:oracle"
VNCSERVERARGS[1]="-geometry 800x600"

Now Change the Password for ONC user
sudo su - oracle
vncpasswd

set password= oracle
As root Start the service

chkconfig --list | grep -i vnc
service vncserver stop
service vncserver start

As root Start the service
maybe stop iptables
service iptables stop

Now Connect to the Box using VNC Client
Download a vnc client such as VNC-Viewer-5.2.3-Windows-32bit  (  yes it is 32 on 64bit box)



Q: How can I run multiple VNC server sessions on the same server at the same time by different users?

Ans:
Open the main config file and add all the users along with any of the id as shown below. So that the user will logon using that ID using vnc client.

# vi /etc/sysconfig/vncservers
VNCSERVERS="2:root 4:deepak "

Once done save the file and assign a vnc pwd to each user manually by logging into their account

NOTE: Make sure you login to the users account for assigning them password or else the vncserver services would not run properly for all the users

# su - deepak

$ vncpasswd
Password: [Give the password for VNC]
Verify: [Retype the password for VNC]
Restart the vncserver services
# service vncserver restart
Shutting down VNC server: 2:root 4:deepak                  [  OK  ]
Starting VNC server: 2:root
New 'server.example.com:2 (root)' desktop is server.example.com:2

Starting applications specified in /root/.vnc/xstartup
Log file is /root/.vnc/server.example.com:2.log

4:deepak
New 'server.example.com:4 (deepak)' desktop is  server.example.com:4

Starting applications specified in /home/deepak/.vnc/xstartup
Log file is /home/deepak/.vnc/server.example.com:4.log

                                                            [  OK  ]
Now you can login to the Linux machine using VNC viewer client using the below syntax

192.168.0.100:2 ==> for user root
192.168.0.100:4 ==> for user deepak

You can also login to the server using your browser. Type the following links for the same

http://server-ip:5802 ==> for user root
http://server-ip:5804 ==> for user deepak

NOTE:
As you can see the port no. when you are trying to access your machine through the browser. It defines the ID of the user which you have assigned in the configuration file.

For example:

2:root - 5802
4:deepak - 5804
 

Saturday, August 29, 2015

Linux Symbolic Links

##########################################################################
Create a Soft or link between the Directories
##########################################################################

Situation :We have 2 databases with the Wallet Directory and files
We are going to move wallet to a Common location /deploy/database_wallet/
==========================================================================

/apps/oracle/product/11.2.0/db/admin/DB1/wallet/
                                                                                              -- a.txt
                                                                                              -- b.txt

/apps/oracle/product/11.2.0/db/admin/DB2/wallet/
                                                                                              -- c.txt
                                                                                              -- d.txt

Desired(Complete Directory and Contents should mapped to /deploy location
============================================================================
It should look like this

/apps/oracle/product/11.2.0/db/admin/DB1/wallet -> /deploy/database_wallet/DB1/wallet

/apps/oracle/product/11.2.0/db/admin/DB2/wallet -> /deploy/database_wallet/DB2/wallet

Work
=============================================================================
                                               
1) Create directories to the New Location which is /deploy & Change the Permissions

    mkdir -p /deploy/database_wallet/DB1/wallet
    mkdir -p /deploy/database_wallet/DB2/wallet

2) Copy original files which to the new Location

   copy  a.txt, b.txt to

   /deploy/database_wallet/DB1/wallet

   copy  c.txt, d.txt to

   /deploy/database_wallet/DB2/wallet

3) Now we have this

     /deploy/database_wallet/DB1/wallet/
                                                                         -- a.txt
                                                                         -- b.txt

     /deploy/database_wallet/DB2/wallet/
                                                                         -- c.txt
                                                                        -- d.txt

4) Now time to remove the Old Location (ONLY WALLET) and Map it to the New one
  
    rm -rd /apps/oracle/product/11.2.0/db/admin/DB1/wallet
    rm -rd /apps/oracle/product/11.2.0/db/admin/DB2/wallet

   Now the Old Location do not have wallet Directory at all

   Time to create a Directory with the Link

   ln -s /deploy/database_wallet/DB1/wallet    /apps/oracle/product/11.2.0/db/admin/DB1/wallet

   ln -s /deploy/database_wallet/DB2/wallet    /apps/oracle/product/11.2.0/db/admin/DB2/wallet


Now Checking
 
   ls -l /apps/oracle/product/11.2.0/db/admin/DB1

       lxxx xxx xxx /apps/oracle/product/11.2.0/db/admin/DB1/wallet -> /deploy/database_wallet/DB1/wallet



Friday, August 21, 2015

MySQL Useful Commands


========================================
                                            Misc Info
========================================

select database();  <- List Current Database

select version();   <- List Current version

select current_date, current_time,now(), database();

========================================
                            Create/Grant/Drop/Privs User
========================================

Note 1: user info is stored in database name called "mysql" and table "user"
Note 2: If you specify only the user name part of the account name, a host name part of '%' is used.
Note 3: If you want user to connect database from any machine then do not provide HOST in the user creation
Note 4: Must Grant to connect to specific database *.* will give access to all databases;

DESC mysql.user;

DROP user 'mysql'@'dbaovm03';

CREATE  user user1 identified by 'mysql';  

GRANT ALL ON db1.* to db1_user1;

CREATE USER 'mysql'@'%'; identified by 'mysql' [WITH GRANT OPTION];

GRANT ALL ON  *.* to user1  [WITH GRANT OPTION];

SELECT user,host,db from mysql.db where db = "*<database_name>*";

SELECT user,host,db from mysql.user;

SELECT * FROM mysql.tables_priv ;

SELECT * FROM mysql.columns_priv  ;

SELECT * FROM mysql.procs_priv  ;

SELECT CONCAT(QUOTE(user),'@',QUOTE(host)) UserAccount FROM mysql.user;

---------------------------------------------------------------------------------------------------------------------
Connect       -> mysql -uroot -pmysql [dbname]  (Do not put any space between -p (lower p) and pwd to avoid pwd prompt)
                        mysql --user=root --password=mysql
                        mysql -u root -pmysql -h localhost
                        mysql -u root -pmysql -h localhost -P 3306    [OK] for port "Caps P"
                        mysql -u root  -p mysql  --> prompt for the pwd and try to connect dbname=mysql

mySql Process while runnig -> ps -ef | grep -i mysqld_safe
                                                  ps -ef | grep -i /usr/bin/mysqld

list session current values    -> mysql>show status ;

list parameteres               -> mysql>show variables like '%';
                                            mysqladmin  -u root -p variables

Change Parater               -> mysql>set bulk_insert_buffer_size=40000;

list Databases                -> mysql>show databases

Create Database            -> mysql>create database [mycustomer];

List Tables                     -> mysql>show tables in information_schema;   [ show tables in DATABASE]

Desc Tables                   -> mysql>describe [tab]
                                           mysql>show columns from [tab];
Create table                   -> mysql>use [db]create table [tab](id integer primary key,nm varchar(30), ph varchar(10));

drop table                      -> mysql>use [db] , drop table [table Name]

drop database                -> mysqladmin -u root -p drop [dbname]

Error Log Default         -> /var/lib/mysql...

Commit                         -> mysql>commit;

help                               -> mysql>help   , mysql> help
                                                                                                                       
Load Data                     -> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;
                                     -> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet  LINES TERMINATED BY '\r\n';
                                     -> INSERT INTO pet VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);

start/stop                      -> service mysql start/stop
                                         /etc/init.d/mysql stop
                                         sudo -u mysql /usr/local/mysql/bin/mysqld stop
                                         mysqladmin -u root -p   shutdown

status details                 -> mysql> status 
                                         #mysqladmin -u root -p     status | extended-status
                                         #mysqladmin -uroot -ppwd   status | extended-status

Check Mysql is alive    ->  mysqladmin -uroot -p ping
                                          Output:mysqld is alive

                                           mysqladmin -uroot -p processlist

reload privs                -> mysqladmin -u root -p reload; mysqladmin -u root -p refresh

Dump a database        -> mysqldump -u root -p [dbname] > output_filename.sql

Restore database        -> mysql> create database [dbname];  mysql -u root -p [dbname] < dumpfile_name.sql

Drop column              -> msql>  ALTER TABLE [tableName] drop [ColumnName];

Rename Table            -> mysql> RENAME TABLE [tableA] TO [tableB];

========================================
   MYSQL from Command prompt
   You can add all commands in one lin eand execute
========================================
-- Prompt update and redirect output
mysql -u oas_user -p oas_user oas "update accounts a, password_reset_tokens t set status = 'Stub_Expired' 
where a.id = t.account_id and t.created_at < date_sub(sysdate(), INTERVAL 47 HOUR); commit;" > /tmp/expire_pending_accounts.output.txt

-- Prompt deletes and redirect output
mysql -u oas_user -p oas_user oas "delete from change_events where account_id in (select id from accounts where username LIKE '%@system.test.com'); delete from password_reset_tokens where account_id in (select id from accounts where username LIKE '%@system.test.com'); delete from accounts where username LIKE '%@system.test.com'; commit;" > /tmp/purge_test_accounts.output.txt

mysql -uoas_user -poas_user oas -e"select count(1) from information_schema.tables;"

mysql -uoas_user -poas_user oas -e"select count(1) from information_schema.tables;" > drew.txt

========================================
   MYSQL FLUSH
========================================

# mysqladmin -u root -p variables
# mysqladmin -u root -p kill 5
# mysqladmin -u root -p flush-hosts
# mysqladmin -u root -p flush-tables
# mysqladmin -u root -p flush-threads
# mysqladmin -u root -p flush-logs
# mysqladmin -u root -p flush-privileges
# mysqladmin -u root -p flush-status           

mysql> show storage engines;
+--------------------+---------+----------------------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                                    | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------------------+--------------+------+------------+
| MyISAM             | YES     | MyISAM storage engine                                          | NO          | NO | NO |
| CSV                     | YES     | CSV storage engine                                                 | NO           | NO | NO |
| MRG_MYISAM | YES     | Collection of identical MyISAM tables                   | NO           | NO | NO |
| BLACKHOLE      | YES     | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables     | NO| NO | NO |
| InnoDB                | DEFAULT | Percona-XtraDB, Supports transactions, row-level locking, and foreign keys | YES | YES  | YES |
| ARCHIVE              | YES     | Archive storage engine                                         | NO | NO| NO |
| PERFORMANCE_ SCHEMA | YES     | Performance Schema                          | NO| NO| NO|
| FEDERATED          | NO      | Federated MySQL storage engine                        | NULL | NULL| NULL|
+--------------------+---------+----------------------------------------------------------------------------+--------------+------+------------+

mysql> SHOW ENGINE INNODB MUTEX;
+--------+------------------------------+------------+
| Type   | Name                         | Status     |
+--------+------------------------------+------------+
| InnoDB | &buf_pool->flush_state_mutex | os_waits=1 |
| InnoDB | &log_sys->checkpoint_lock    | os_waits=2 |
+--------+------------------------------+------------+
========================================
Command Line
========================================
--basedir=e: /mysql
--datadir=d: /mysqldata
or

mysql --defaults-file=c:\my-opts

refrence other file
!include    file_name
!includedir dir_name

========================================
                        Logs and Locations
========================================

option file location  :   /etc/my.cnf  or $MYSQL_HOME/my.cnfor  or ~/.my.cnf
mysql can write to several types of logs
 
syslog: mysqld_safe option
--syslog[=tag]
--skip-syslog(default)

Or
general Query log     ,   slow query log    .  binay log

you can start server with file name ow everything will goto screen
 
mysqld --log-error=filename

hostname.err
mysqld_safe

general query log - Logs all SQL received by the server/Client Connections

You may also write in a table general_log tables in mysql database

SET GLOBAL general_log='ON'

SET GLOBAL general_log='OFF'

General QUERY LOG
------------------------------
set general_log to enable/disable
Set general_log_file to specify name of the logfile

--log-output options
1) TABLE -log to tables
2) FILE  -log to files
1) NONE  - do not log to tables or  files

Slow Query Log ( file or Table)
--------------------------------
Set server variable , Log query executing time longer than  long_query_time server  variable (in Sec)

Enable log
slow_query_log  or  slow_query_log_file=filename

Not Index Queries

--log-queries-not-using-indexes

mysql_install_db --user=mysql --datadir=/data/mysql/data

mysql_install_db --user=root --datadir=/data/mysql/data

DEFAULT database and Log /Err Location : /var/lib/mysql
DEFAULY cnf location /etc/my.cnf

========================================
  ==== MySQL Client Based programs ===
========================================

mysql
mysqladmin
mysqlimport
mysqldump

mysql -uroot --skip-column-names -rsp
mysql --host=<> --port=3351 --user=ro

Terminator
: or \g
\G ( Specifies vertical display of output)
\c (don't send current statement to server)
 
mysql> prompt aa >
PROMPT set to 'aa >'
aa >

root@localhostmysql>prompt \u@\h \d>
PROMPT set to '\u@\h \d>'
root@localhost mysql>


Adarsh Kumar
AK Technosoft Corp.
Database Design and  Consulting