Wednesday, April 1, 2026

Selectivity and Cardinality

 Selectivity and Cardinality (detailed, with formulas & examples)

Cardinality = how many distinct values (or how many rows),

Selectivity = what fraction of the table matches a predicate. The optimizer uses these to estimate rows and pick plans.

1) Cardinality — definitions & formulae

A. Column cardinality (distinct values)

Definition:

Number of distinct values in a column.

Notation / formula:

CARDINALITY(column) = COUNT(DISTINCT column)

Example: if dept_id in emp has values {0,10,20,30,40} → CARDINALITY(dept_id) = 5.

B. Result-set cardinality (rows returned by a query/predicate)

Definition:

Actual number of rows that satisfy a predicate.

Notation / formula:

CARDINALITY(result) = COUNT(*) WHERE <predicate>

Example:

If emp has N = 10,000 rows and dept_id = 20 occurs in 2,000 rows, then:

CARDINALITY(result) = 2000

2) Selectivity - definition & basic formula

Definition:

Fraction (or probability) of rows that satisfy a predicate.

Formula:

Selectivity(s) = (number of rows satisfying predicate) / (total rows)

s = matched_rows / N

Estimated rows (used by optimizer):

Estimated_Rows = N * s

Worked example (digit-by-digit):

Table emp has N = 10,000 rows. dept_id = 20 occurs in matched_rows = 2,000

rows.

Compute selectivity:

1. matched_rows / N = 2000 / 10000

2. simplify: 2000/10000 = 2/10 (divide numerator & denominator by 1000)

3. 2/10 = 1/5

4. 1/5 = 0.2

So s = 0.2. Estimated rows = 10,000 * 0.2 = 2,000 (same as actual here).

3) Common useful formulas & rules-of-thumb

Equality predicate (assuming uniform distribution):

Selectivity(eq) ≈ 1 / NDV(column) where NDV = number of distinct values for that column.

Example: NDV(dept_id) = 5 → s ≈ 1/5 = 0.2.

Range predicate (simple uniform model):

Selectivity(range low..high) ≈ (high - low + 1) / (max_value - min_value + 1)

(For continuous numeric ranges you can drop the +1's, it’s an approximation.)

AND of independent predicates (multiplicative):

If predicates A and B are independent,

s(A AND B) = s(A) * s(B)

Example: s(dept_id = 20) = 0.2, s(gender = 'M') = 0.5 

 combined s = 0.2 * 0.5 = 0.1 → estimated rows = 10,000 * 0.1 = 1,000.

OR of independent predicates (inclusion–exclusion):

s(A OR B) = s(A) + s(B) - s(A)*s(B)

Example: s(dept=20)=0.2, s(dept=30)=0.2 (disjoint here so s=0.4 actually — inclusion-exclusion gives same result when disjoint).

Negation:

s(NOT A) = 1 - s(A)

Important caveat: independence assumption often fails (correlation/skew) — real estimates need histograms/statistics.

4) How optimizer uses selectivity & cardinality

1. Optimizer reads table size N and statistics (NDV, histograms, min/max, frequency) and computes s for predicates → then Estimated_Rows = N * s.

2. The chosen access path (index vs full scan), join order, join method depend on estimated rows.

3. If estimated rows are very small → index access is attractive. If large → full table scan may be cheaper.

Rule-of-thumb (not absolute): indexes are more likely to be used when predicate selectivity is low (small fraction), e.g. s < 0.05 (5%)

- but threshold depends on table size, index clustering factor, I/O costs, and DB engine.

5) Concrete SQL examples (with numbers)

Assume emp table: N = 10,000 rows, dept_id has NDV = 5 uniformly distribute

d → each dept has 2,000 rows.

1. SELECT * FROM emp WHERE dept_id = 20;

1. matched_rows = 2,000

2. selectivity s = 2000 / 10000 = 0.2 (20%)

3. estimated rows = 10,000 * 0.2 = 2,000

2. SELECT * FROM emp WHERE gender = 'M' (assume 50% male)

1. s = 0.5 → estimated rows = 5,000

3. SELECT * FROM emp WHERE dept_id = 20 AND gender = 'M'

1. If independent: s = 0.2 * 0.5 = 0.1 → estimated rows = 1,000

2. If highly correlated (say dept 20 mostly males), actual rows could be much

higher — optimizer needs histograms to be accurate.

4. SELECT * FROM emp WHERE salary BETWEEN 40000 AND 60000

Suppose salary min=30000, max=130000 and uniform distribution:

s ≈ (60000 - 40000) / (130000 - 30000) = 20000 / 100000 = 0.2

Estimated rows = 10,000 * 0.2 = 2,000.

6) Why real-world estimates can be wrong

1. Skew: some values much more frequent → uniform assumption fails.

2. Correlation: two columns not independent (e.g., dept and salary). Multiplicative rule gives wrong estimates.

3. Stale or missing statistics: optimizer guesses and may pick poor plan.

4. Complex predicates (LIKE '%abc', functions) require function-based stats or histograms.

Solution: gather accurate statistics (DBMS_STATS in Oracle), create histograms

for skewed columns, use extended statistics for correlated columns.

7) Quick cheat-sheet (formulas)

1. s = matched_rows / N

2. Estimated_Rows = N * s

3. s(eq) ≈ 1 / NDV (if uniform)

4. s(range) ≈ (high - low) / (max - min) (approx)

5. s(A AND B) = s(A) * s(B) (if independent)

6. s(A OR B) = s(A) + s(B) - s(A)*s(B) (if independent)


Vinayak Vishweshwara Dabgar

www.dabgarvinayakv.com

For Database Scripts : https://l-earn.dabgarvinayakv.com/toolkit/

Sunday, October 7, 2018

Restauration et récupération de la base de données

Full Database Offline Backup:

#!/bin/bash

rman target / catalog rmancat/rmancat@GEK <<EOF
  shutdown immediate;
  startup mount;
  backup database format '/u01/oracle/db/AKI/bck/ora_df%t_s%s_s%p';
  alter database open;
EOF
exit

Full Database Online Backup:

#!/bin/bash

rman target / catalog rmancat/rmancat@GEK <<EOF
  backup database format '/u01/oracle/db/AKI/bck/ora_df%t_s%s_s%p';
EOF
exit


Backing Up a Tablespace

backup tablespace system format '/u01/oracle/db/AKI1/bck/ora_df%t_s%s_s%p';
run {

  allocate channel d1 type disk;
  backup tablespace system, users include current controlfile
  format '/u01/oracle/db/AKI1/bck/ora_df%t_s%s_s%p';
}


Backing Up Control Files


View Backup Information

RMAN> list backup;
View Schema
RMAN> report schema;


Is Backup restorable ?

RMAN> run {
   allocate channel d1 type disk;
   restore database validate;
}

Validate Backup

RMAN> backup validate database archivelog all;



Restoring and Recovering All Datafiles

SQL> connect sys/... as SYSDBA;
SQL> shutdown abort;
ORACLE instance shut down.


SQL> startup mount;
Oracle instance started.

$ rman target / catalog rmancat/rmancat@catdb

RMAN> restore database;
RMAN> recover database;
RMAN> alter database open;


For Oracle8i command:
RMAN> run {
  allocate channel d1 type disk;
  restore database;
  recover database;
}
alter database open;

$ sqlplus /nolog
SQL> connect sys/... as SYSDBA;
SQL> recover database;
SQL> alter database open;


Restoring Specific Tablespaces/Datafiles


sqlplus "sys/managase as sysdba"
SQL> alter tablespace tab offline;
$ rman target / catalog rmancat/rmancat@GEK1
RMAN> restore tablespace tab;
RMAN> recover tablespace tab;
SQL> alter tablespace tab open;
If this fails:
SQL> connect sys/... as SYSDBA;
SQL> shutdown abort;
SQL> startup mount;
$ rman target / catalog rmancat/rmancat@GEK1
RMAN> restore tablespace tab;
RMAN> recover tablespace tab;
SQL> alter database open;

Restoring Control Files

SQL> connect sys/... as SYSDBA;
SQL> shutdown abort;
SQL> startup nomount;
$ rman target / catalog rmancat/rmancat@GEK
RMAN> restore controlfile;
RMAN> alter database mount;
RMAN> alter database open;

If this fails with ...

SQL> shutdown abort;
SQL> startup mount;
$ rman target / catalog rmancat/rmancat@GEK
RMAN> recover database;
RMAN> alter database open resetlogs;



Restoring Online Redologs

sqlplus "sys/manager as sysdba"
SQL> shutdown abort;
SQL> startup nomount;
$ rman target / catalog rmancat/rmancat@GEK
RMAN> restore controlfile;
RMAN> alter database mount;
RMAN> restore database;
RMAM> recover database;

Time-Based or Change-Based Incomplete Recovery

sqlplus "sys/manager as sysdba"
SQL> shutdown abort;
SQL> startup mount;
$ rman target / catalog rmancat/rmancat@GEK1
RMAN> restore database;
SQL> recover database until time '2004-09-19:10:35:00';
media recovery complete.
SQL> alter database open resetlogs;




Commandes de maintenance
RMAN> report need backup;
Quels fichiers ont besoin d'une sauvegarde maintenant
RMAN> crosscheck backup;
Détermine si un jeu de sauvegarde et ses éléments associés existent toujours sur le support. Si une partie de sauvegarde existe à l'emplacement enregistré dans le fichier de contrôle de la base de données cible ou dans le catalogue de récupération facultatif, son statut est marqué comme DISPONIBLE. S'il ne se trouve pas à l'emplacement spécifié, il est marqué EXPIRÉ.
RMAN> delete expired backup of database;
RMAN> delete backup of database;
Pour Oracle9i, cette commande supprime les fichiers physiques associés aux jeux de sauvegarde et aux copies de fichiers de données, met à jour leur statut dans le fichier de contrôle et supprime leurs informations du catalogue de récupération facultatif (le cas échéant).
Dans Oracle8i et Oracle9i, les sauvegardes sont marquées EXPIRÉ si elles ne peuvent pas être trouvées à leur emplacement enregistré. La suppression des sauvegardes EXPIRED supprime leurs informations du fichier de contrôle et du catalogue de récupération facultatif (le cas échéant).
RMAN> create catalog;
RMAN> drop catalog;
Créez un catalogue de récupération.
Supprime tous les objets associés au schéma du catalogue de récupération.
RMAN> report need backup days 2 database;

RMAN> report need backup days 2
    
 tablespace system;

RMAN> report obsolete;
RMAN> report unrecoverable;










Mots-clés et paramètres RMAN

 Mots-clés et paramètres RMAN:

%d Spécifie le nom de la base de données

%f - Spécifie le numéro de fichier absolu

%s - Spécifie le numéro du jeu de sauvegarde

%t - Spécifie l'horodatage du jeu de sauvegarde
%p - Spécifie le numéro de pièce du jeu de sauvegarde



Création du script de sauvegarde sous Linux


Exemple :

#!/bin/sh 
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/dbhome_1 
export ORACLE_SID=orcl 
PATH=$ORACLE_HOME/bin:$PATH 

rman <<EOF 
connect target / 
RUN 
{  
ALLOCATE CHANNEL disk_iub DEVICE TYPE DISK;  
RECOVER COPY OF DATABASE WITH TAG daily_iub;  
BACKUP INCREMENTAL LEVEL 1 FOR RECOVER OF COPY WITH TAG daily_iub DATABASE; 

exit 
EOF


Par exemple,

If your script is in the file /u01/app/oracle/rman/daily_backup.sh,

Puis entrez cette commande:

/u01/app/oracle/rman/daily_backup.sh

If the script is in the file /u01/app/oracle/rman/daily_backup.sh, then the .crontab file must contain: MAILTO=first.last@example.com

# MI HH DD MM DAY CMD
00 2 * * * /u01/app/oracle/rman/daily_backup.sh

In a command window, change directory to your home directory and enter the following command:

crontab .-e edit the cron details.

crontab -l to check the cron details



Selectivity and Cardinality

 Selectivity and Cardinality (detailed, with formulas & examples) Cardinality = how many distinct values (or how many rows), Selectivit...