io

2008: Les traditionnelles augmentations de tarifs

Le premier janvier de chaque année est l'occasion des traditionnelles augmentation des prix. En 2008, cela va concerner le gaz, les timbres. Mais d'autres hausses de prix devraient suivrent. Lire tout l'article (source) Le lait : + 5 à 10 % Le gaz : +...




io

Sarkozy défenseur des religions en Arabie Saoudite

Le président français a célébré lundi les religions du Livre et félicité le roi Abdallah pour ses efforts d'ouverture. La «politique de civilisation» chère au président français a pris un tour résolument religieux lundi en Arabie Saoudite. Dans ce pays...




io

Rétention de sûreté: Sarkozy insiste

Le chef de l'Etat a demandé au président de la Cour de cassation de trouver le moyen juridique de contourner la censure du Conseil constitutionnel. Celui-ci a limité l' application immédiate de la loi sur la rétention de sûreté pour les criminels déjà...




io

Décision le 3 mars sur le site "note2be.com"

Le Snes-FSU, la FSU et six enseignants ont assigné en référé le site et son co-fondateur, Stéphane Cola, pour avoir proposé aux élèves de noter leurs profs nommément. Le sort du site internet "note2be.com", qui, en proposant aux élèves de noter leurs...




io

La loterie des notes au bac : un réexamen de l'arbitraire de la notation des élèves

La question de la notation à l’école n’est pas récente, les nombreuses études réalisées sur ce thème mettent toutes en évidence l’incertitude de la mesure des performances scolaires des élèves par les notes et les divers biais associés à cette pratique...




io

Des militaires français soupçonnés de viols sur des enfants en Centrafrique

Un document confidentiel de l'ONU, qui fait état de viols sur mineurs par des soldats français, a été transmis par un employé des Nations unies aux autorités françaises. Une enquête préliminaire a été ouverte ainsi qu'une "enquête de commandement" au...




io

Tek'it Audio - Winkl 1.2.1

Freeware for PC : Plug-ins & effects / Distortion unit




io

UVI - UVI Workstation 2.6.10

Freeware for PC : Virtual Instruments / Expander / sampler




io

Audio Damage - FuzzPlus 3.1

Freeware for PC : Plug-ins & effects / Vintage fuzz pedal emulation




io

Tek'it Audio - 8kut 2.2

Freeware for Mac : Plug-ins & effects / 8 bands frequencies cutter




io

LVC-Audio - Limited-Z 1.1.0

Freeware for PC : Plug-ins & effects / Limiter




io

Vijesti :: Drugi XIXO kup okupio oko 200 djece

Autor: Redakcija 031 Naslov: Drugi XIXO kup okupio oko 200 djece
Postano: 13.11.2024. 8:06 (GMT 1) Rukometni klub Baranja u suradnji s Udrugom BIT organizirao je drugi XIXO kup, turnir u mini rukometu, u sklopu obilježavanja Dana Grada Belog Manastira.

Na sportskom terenu Nastavno-sportske dvorane u Belom Manastiru, snage su odmjerile najmlađe rukometne ekipe, uzrasta od 9 do 10 godina s područja Osječko-baranjske, Vukovarsko-srijemske, Brodsko-posavske i Požeško-slavonske županije. Sudjelovalo je 12 klubova s 20 prijavljenih ekipa. Ukupno oko 200 djece.

"Turnir nema natjecateljski karakter, a cilj mu je da djeca razviju ljubav prema rukometu, i sportu općenito. Izuzetno je važno da djeca nauče i usvoje pravila rukometa, a najvažnije da postanu timski igrači i dio ekipe jer, rukomet je timski sport", objašnjava cilj i smisao XIXO kupa, turnira u mini rukometu Dalibor Dodoš, dopredsjednik Rukometnog kluba Baranja iz Belog Manastira.




Tekst: RK Baranja
Foto: Nenad Milić




io

Vijesti :: Poznat datum isplate nacionalne naknade za starije osobe

Autor: Redakcija 031 Naslov: Poznat datum isplate nacionalne naknade za starije osobe
Postano: 13.11.2024. 11:49 (GMT 1) U petak 15. studenoga 2024. počinje isplata nacionalne naknade za starije osobe za listopad 2024. korisnicima računa otvorenih u poslovnim bankama.

Nacionalnu naknadu za starije osobe dobit će 17 388 korisnika (80,23 % žena i 19,77 % muškaraca), za što je osigurano 2.591.205,00 eura iz Državnog proračuna.

U skladu sa Zakonom o izmjenama i dopunama Zakona o nacionalnoj naknadi za starije osobe (NN 156/23), nacionalna naknada od 1. siječnja 2024. iznosi 150,00 eura, izvijestili su iz HZMO-a.


Foto: Osijek031.com/Arhiv




io

Un haut responsable du PCC appelle � la promotion d'une communaut� Chine-Vietnam d'avenir partag�

Le haut responsable chinois, Li Xi, a rencontr� Phan Dinh Trac, membre du Bureau politique, secr�taire du secr�tariat et pr�sident de la Commission des affaires int�rieures du Comit� central du Parti communiste vietnamien (PCV), mardi � Beijing. ...




io

Le PM chinois met l'accent sur l'am�lioration de la production agricole et la pr�vention des catastrophes

Le Premier ministre chinois Li Qiang a mis l'accent sur l'am�lioration de la capacit� globale de production agricole, ainsi que sur la pr�vention et la r�duction des catastrophes, afin de poser des bases solides pour assurer la s�curit� alimentaire....




io

La Chine accueille les entreprises � capitaux �trangers pour approfondir la coop�ration mutuellement b�n�fique

La Chine promeut une ouverture de haut niveau du secteur financier et accueille les entreprises � capitaux �trangers pour approfondir la coop�ration mutuellement b�n�fique, a annonc� mardi � Beijing le vice-Premier ministre chinois He Lifeng. M....




io

Tenue du premier Forum des m�dias et des groupes de r�flexion du Sud global au Br�sil

Organis� sur le th�me "D�veloppement et revitalisation : un nouveau parcours pour le Sud global", le premier Forum des m�dias et des groupes de r�flexion du Sud global s'est tenu lundi et mardi � S�o Paulo, au Br�sil. Des messages de...




io

Un rapport d'un groupe de r�flexion chinois "Un nouveau mod�le pour le progr�s humain et son importance mondiale" d�voil� au Br�sil

Le Forum des m�dias et des groupes de r�flexion du Sud global s'est tenu lundi et mardi � Sao Paulo, et un rapport intitul� "Un nouveau mod�le pour le progr�s humain et son importance mondiale" a �t� diffus� � cette occasion. Il fournit une...




io

Alg�rie : des livres chinois attirent l'attention des lecteurs lors du Salon international du livre d'Alger

Le stand chinois a attir� un large public, en particulier de jeunes visiteurs d�sireux de d�couvrir la culture et la langue chinoises lors de la 27e �dition du Salon international du livre d'Alger (SILA), a constat� sur place Xinhua. Selon Liu...




io

L'arm�e chinoise effectue des patrouilles de pr�paration au combat � Huangyan Dao

L'arm�e chinoise a effectu� mercredi des patrouilles de pr�paration au combat dans les eaux territoriales et l'espace a�rien territorial de Huangyan Dao, �le chinoise en mer de Chine m�ridionale, ainsi que dans des zones avoisinantes. Le...




io

La modernisation chinoise favorise un nouveau mod�le de d�veloppement humain

Un rapport conjoint intitul� "Un nouveau mod�le pour le progr�s humain et son importance mondiale" a �t� publi� lors du Forum des m�dias et des groupes de r�flexion du Sud global qui s'est tenu lundi � Sao Paulo, au Br�sil. R�dig� par des groupes...




io

Airbus pr�voit une forte demande d'avions en Chine au cours des 20 prochaines ann�es

Airbus a pr�vu que la Chine aurait besoin de plus de 9.500 nouveaux avions de transport de passagers et d'avions cargos au cours des deux prochaines d�cennies, en raison de la forte croissance de la demande de transport a�rien et de fret. Selon...




io

Chine : la partie continentale encourage les �changes entre les jeunes et appelle � lever les restrictions sur les voyages entre les deux rives du d�troit de Taiwan

La partie continentale de la Chine a r�affirm� son engagement � promouvoir les �changes entre les jeunes � travers le d�troit de Taiwan et a demand� aux autorit�s du Parti d�mocrate progressiste (PDP) de lever les restrictions sur les voyages �...




io

Chine : la partie continentale d�clare que les consultations entre les deux rives du d�troit sont possibles en reconnaissant le Consensus de 1992

Les consultations entre l'Association pour les relations entre les deux rives du d�troit de Taiwan (ARATS) et la Fondation pour les �changes entre les deux rives du d�troit de Taiwan (SEF) pourraient reprendre si les autorit�s de Taiwan...




io

La Chine compte la plus grande capacit� totale de production d'�nergie nucl�aire dans le monde

La capacit� totale de production d'�nergie nucl�aire de la Chine, y compris les unit�s en fonctionnement, en construction et officiellement approuv�es, occupe la premi�re place mondiale, d'apr�s la Soci�t� de recherche �nerg�tique de Chine (China...




io

Xi entame une tourn�e en Am�rique latine pour d�fendre la coop�ration et le multilat�ralisme

Le pr�sident chinois Xi Jinping entame mercredi une tourn�e en Am�rique latine, o� il assistera � la 31e r�union des dirigeants �conomiques de la Coop�ration �conomique pour l'Asie-Pacifique (APEC) � Lima, capitale du P�rou, et au 19e sommet du G20...




io

Chine : la puissance de l'aviation et de la d�fense de la partie continentale est une protection solide pour les compatriotes taiwanais

Une porte-parole de la partie continentale de la Chine a qualifi� les r�sultats et la puissance de la partie continentale dans les domaines de l'aviation, de l'a�rospatiale et de la d�fense nationale de protection "solide et immense" pour les...




io

La Chine et le Vietnam conviennent de renforcer leur coop�ration en mati�re de s�curit�

Chen Wenqing, haut responsable du Parti communiste chinois (PCC), a rencontr� Phan Dinh Trac, membre du Bureau politique et pr�sident de la Commission des affaires int�rieures du Comit� central du Parti communiste vietnamien (PCV), mardi � Beijing. ...




io

Hostname/IP Address Resolution Utility Released

A new utility that resolves an IP address from a given hostname (and vice versa) has just been released.




io

Introduction To Maven 2

Maven is a tool used to build Java code, similar to ANT. However Maven has a number of advantages over ANT, the main one being it being able to automatically download a project's dependencies from a central repository.




io

Guide To Installing Fedora Core 6 On HP Pavilion dv2000 Series Laptops

This guide provides installation and configuration instructions for installing Fedora Core 6 on HP Pavilion dv2000 series laptops.




io

Antonio Volpon




io

Three impossibilities with partitioned indexes

articles: 

There are three restrictions on indexing and partitioning: a unique index cannot be local non-prefixed; a global non-prefixed index is not possible; a bitmap index cannot be global. Why these limitations? I suspect that they are there to prevent us from doing something idiotic.

This is the table used for all examples that follow:

CREATE TABLE EMP
      (EMPNO NUMBER(4) CONSTRAINT PK_EMP PRIMARY KEY,
       ENAME VARCHAR2(10),
       JOB VARCHAR2(9),
       MGR NUMBER(4),
       HIREDATE DATE,
       SAL NUMBER(7,2),
       COMM NUMBER(7,2),
       DEPTNO NUMBER(2) )
PARTITION BY HASH (EMPNO) PARTITIONS 4;

the usual EMP table, with a partitioning clause appended. It is of course a contrived example. Perhaps I am recruiting so many employees concurrently that a non-partitioned table has problems with buffer contention that can be solved only with hash partitioning.

Why can't I have a local non-prefixed unique index?
A local non-unique index is no problem, but unique is not possible:

orclz> create index enamei on emp(ename) local;

Index created.

orclz> drop index enamei;

Index dropped.

orclz> create unique index enamei on emp(ename) local;
create unique index enamei on emp(ename) local
                              *
ERROR at line 1:
ORA-14039: partitioning columns must form a subset of key columns of a UNIQUE index

You cannot get a around the problem by separating the index from the constraint (which is always good practice):

orclz> create index enamei on emp(ename) local;

Index created.

orclz> alter table emp add constraint euk unique (ename);
alter table emp add constraint euk unique (ename)
*
ERROR at line 1:
ORA-01408: such column list already indexed


orclz>

So what is the issue? Clearly it is not a technical limitation. But if it were possible, consder the implications for performance. When inserting a row, a unique index (or a non-unique index enforcing a unique constraint) must be searched to see if the key value already exists. For my little four partition table, that would mean four index searches: one of each local index partition. Well, OK. But what if the table were range partitioned into a thousand partitions? Then every insert would have to make a thousand index lookups. This would be unbelievably slow. By restricting unique indexes to global or local prefixed, Uncle Oracle is ensuring that we cannot create such an awful situation.

Why can't I have a global non-prefixed index?
Well, why would you want one? In my example, perhaps you want a global index on deptno, partitioned by mgr. But you can't do it:

orclz> create index deptnoi on emp(deptno) global partition by hash(mgr) partitions 4;
create index deptnoi on emp(deptno) global partition by hash(mgr) partitions 4
                                                                *
ERROR at line 1:
ORA-14038: GLOBAL partitioned index must be prefixed


orclz>
This index, if it were possible, might assist a query with an equality predicate on mgr and a range predicate on deptno: prune off all the non-relevant mgr partitions, then a range scan. But exactly the same effect would be achieved by using global nonpartitioned concatenated index on mgr and deptno. If the query had only deptno in the predicate, it woud have to search each partition of the putative global partitioned index, a process which would be just about identical to a skip scan of the nonpartitioned index. And of course the concatenated index could be globally partitioned - on mgr. So there you have it: a global non-prefixed index would give you nothing that is not available in other ways.

Why can't I have a global partitioned bitmap index?
This came up on the Oracle forums recently, https://forums.oracle.com/thread/2575623
Global indexes must be prefixed. Bearing that in mind, the question needs to be re-phrased: why would anyone ever want a prefixed partitioned bitmap index? Something like this:

orclz>
orclz> create bitmap index bmi on emp(deptno) global partition by hash(deptno) partitions 4;
create bitmap index bmi on emp(deptno) global partition by hash(deptno) partitions 4
                                       *
ERROR at line 1:
ORA-25113: GLOBAL may not be used with a bitmap index

orclz>

If this were possible, what would it give you? Nothing. You would not get the usual benefit of reducing contention for concurrent inserts, because of the need to lock entire blocks of a bitmap index (and therefore ranges of rows) when doing DML. Range partitioning a bitmap index would be ludicrous, because of the need to use equality predicates to get real value from bitmaps. Even with hash partitions, you would not get any benefit from partition pruning, because using equality predicates on a bitmap index in effect prunes the index already: that is what a bitmap index is for. So it seems to me that a globally partitioned bitmap index would deliver no benefit, while adding complexity and problems of index maintenance. So I suspect that, once again, Uncle Oracle is protecting us from ourselves.

Is there a technology limitation?
I am of course open to correction, but I cannot see a technology limitation that enforces any of these three impossibilities. I'm sure they are all technically possible. But Oracle has decided that, for our own good, they will never be implemented.
--
John Watson
Oracle Certified Master DBA
http://skillbuilders.com




io

Inverted tables: an alternative to relational structures

articles: 

The inverted table format can deliver fast and flexible query capabilities, but is not widely used. ADABAS is probably the most successful implementation, but how often do you see that nowadays? Following is a description of how to implement inverted structures within a relational database. All code run on Oracle Database 12c, release 12.1.0.1.

Consider this table and a few rows, that describe the contents of my larder:

create table food(id number,capacity varchar2(10),container varchar2(10),item varchar2(10));
insert into food values(1,'large','bag','potatoes');
insert into food values(2,'small','box','carrots');
insert into food values(3,'medium','tin','peas');
insert into food values(4,'large','box','potatoes');
insert into food values(5,'small','tin','carrots');
insert into food values(6,'medium','bag','peas');
insert into food values(7,'large','tin','potatoes');
insert into food values(8,'small','bag','carrots');
insert into food values(9,'medium','box','peas');

The queries I run against the table might be "how many large boxes have I?" or "give me all the potatoes, I don't care about how they are packed". The idea is that I do not know in advance what columns I will be using in my predicate: it could be any combination. This is a common issue in a data warehouse.
So how do I index the table to satisfy any possible query? Two obvious possibilities:
First, build an index on each column, and the optimizer can perform an index_combine operation on whatever columns happen to be listed in the predicate. But that means indexing every column - and the table might have hundreds of columns. No way can I do that.
Second, build a concatenated index across all the columns: in effect, use an IOT. That will give me range scan access if any of the predicated columns are in the leading edge of the index key followed by filtering on the rest of the predicate. Or if the predicate does not include the leading column(s), I can get skip scan access and filter. But this is pretty useless, too: there will be wildly divergent performance depending on the predicate.
The answer is to invert the table:
create table inverted(colname varchar2(10),colvalue varchar2(10),id number);
insert into inverted select 'capacity',capacity,id from food;
insert into inverted select 'container',container,id from food;
insert into inverted select 'item',item,id from food;

Now just one index on each table can satisfy all queries:
create index food_i on food(id);
create index inverted_i on inverted(colname,colvalue);

To retrieve all the large boxes:
orclz> set autotrace on explain
orclz> select * from food where id in
  2  (select id from inverted where colname='capacity' and colvalue='large'
  3  intersect
  4  select id from inverted where colname='container' and colvalue='box');

        ID CAPACITY   CONTAINER  ITEM
---------- ---------- ---------- ----------
         4 large      box        potatoes


Execution Plan
----------------------------------------------------------
Plan hash value: 1945359172

---------------------------------------------------------------------------------
| Id  | Operation                                | Name       | Rows  | Bytes | C
---------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                         |            |     3 |   141 |
|   1 |  MERGE JOIN                              |            |     3 |   141 |
|   2 |   TABLE ACCESS BY INDEX ROWID            | FOOD       |     9 |   306 |
|   3 |    INDEX FULL SCAN                       | FOOD_I     |     9 |       |
|*  4 |   SORT JOIN                              |            |     3 |    39 |
|   5 |    VIEW                                  | VW_NSO_1   |     3 |    39 |
|   6 |     INTERSECTION                         |            |       |       |
|   7 |      SORT UNIQUE                         |            |     3 |    81 |
|   8 |       TABLE ACCESS BY INDEX ROWID BATCHED| INVERTED   |     3 |    81 |
|*  9 |        INDEX RANGE SCAN                  | INVERTED_I |     3 |       |
|  10 |      SORT UNIQUE                         |            |     3 |    81 |
|  11 |       TABLE ACCESS BY INDEX ROWID BATCHED| INVERTED   |     3 |    81 |
|* 12 |        INDEX RANGE SCAN                  | INVERTED_I |     3 |       |
---------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("ID"="ID")
       filter("ID"="ID")
   9 - access("COLNAME"='capacity' AND "COLVALUE"='large')
  12 - access("COLNAME"='container' AND "COLVALUE"='box')

Note
-----
   - dynamic statistics used: dynamic sampling (level=2)

orclz>

Or all the potatoes:
orclz> select * from food where id in
  2  (select id from inverted where colname='item' and colvalue='potatoes');

        ID CAPACITY   CONTAINER  ITEM
---------- ---------- ---------- ----------
         1 large      bag        potatoes
         4 large      box        potatoes
         7 large      tin        potatoes


Execution Plan
----------------------------------------------------------
Plan hash value: 762525239

---------------------------------------------------------------------------------
| Id  | Operation                              | Name       | Rows  | Bytes | Cos
---------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                       |            |     3 |   183 |
|   1 |  NESTED LOOPS                          |            |       |       |
|   2 |   NESTED LOOPS                         |            |     3 |   183 |
|   3 |    SORT UNIQUE                         |            |     3 |    81 |
|   4 |     TABLE ACCESS BY INDEX ROWID BATCHED| INVERTED   |     3 |    81 |
|*  5 |      INDEX RANGE SCAN                  | INVERTED_I |     3 |       |
|*  6 |    INDEX RANGE SCAN                    | FOOD_I     |     1 |       |
|   7 |   TABLE ACCESS BY INDEX ROWID          | FOOD       |     1 |    34 |
---------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   5 - access("COLNAME"='item' AND "COLVALUE"='potatoes')
   6 - access("ID"="ID")

Note
-----
   - dynamic statistics used: dynamic sampling (level=2)
   - this is an adaptive plan

orclz>

Of course, consideration needs to be given to handling more complex boolean expressions; maintaining the inversion is going to take resources; and a query generator has to construct the inversion code and re-write the queries. But In principle, this structure can deliver indexed access for unpredictable predicates of any number of any columns, with no separate filtering operation. Can you do that with a normalized star schema? I don't think so.
I hope this little thought experiment has stimulated the little grey cells, and made the point that relational structures are not always optimal for all problems.
--
John Watson
Oracle Certified Master DBA
http://skillbuilders.com




io

Finding gaps with analytic functions

articles: 

Finding gaps is classic problem in PL/SQL. The basic concept is that you have some sort of numbers (like these: 1, 2, 3, 5, 6, 8, 9, 10, 15, 20, 21, 22, 23, 25, 26), where there’s supposed to be a fixed interval between the entries, but some entries could be missing. The gaps problem involves identifying the ranges of missing values in the sequence. For these numbers, the solution will be as follows:
START_GAP END_GAP
4 4
7 7
11 14
16 19
24 24

First, run the following code, to create tab1 table:


CREATE TABLE tab1
(
col1 INTEGER
);

Then, insert a few rows:


INSERT INTO tab1 VALUES (1);
INSERT INTO tab1 VALUES (2);
INSERT INTO tab1 VALUES (3);
INSERT INTO tab1 VALUES (5);
INSERT INTO tab1 VALUES (6);
INSERT INTO tab1 VALUES (8);
INSERT INTO tab1 VALUES (9);
INSERT INTO tab1 VALUES (10);
INSERT INTO tab1 VALUES (15);
INSERT INTO tab1 VALUES (20);
INSERT INTO tab1 VALUES (21);
INSERT INTO tab1 VALUES (22);
INSERT INTO tab1 VALUES (23);
INSERT INTO tab1 VALUES (25);
INSERT INTO tab1 VALUES (26);

COMMIT;

With data, you can take care of solving the gaps problem…

One of the most efficient solutions to the gaps problem involves using analytic functions (also known as window functions)


WITH aa AS
(SELECT col1 AS cur_value, LEAD (col1) OVER (ORDER BY col1) AS next_value
FROM tab1)
SELECT cur_value + 1 AS start_gap, next_value - 1 AS end_gap
FROM aa
WHERE next_value - cur_value > 1
ORDER BY start_gap

Using the LEAD function, you can return for each current col1 value (call it cur_value) the next value in the sequence (call it next_value). Then you can filter only pairs where the difference between the two is greater than the one.




io

Recursion with recursive WITH

articles: 

I recently had the opportunity to talk with Tom Kyte (!), and in the course of our conversation, he really made me face up to the fact that the SQL syntax I use every day is frozen in time: I’m not making much use of the analytic functions and other syntax that Oracle has introduced since 8i.

Here’s a brief history of these additions to Oracle SQL, from Keith Laker, Oracle’s Product Manager for Analytical SQL:

8i Window functions
9i Rollup, grouping sets, cube, enhanced window functions
10g SQL Model clause, statistical functions, partition outer join
11g SQL Pivot clause, Recursive WITH, Listagg, Nth value
12c Pattern matching, Top N

Not only do these make complex queries much, much simpler and easier, they are also much faster for the same result than non-analytic SQL, as Tom Kyte has shown repeatedly on his blog and in his books.

So, I was sold and I wanted to jump in with Recursive WITH. The WITH clause lets you define inline views to use across an entire query, and the coolest thing about this is that you can define the subquery recursively – so that the inline view calls itself.

Recursive WITH basic syntax:

WITH Tablename (col1, col2, ...) AS
(SELECT A, B, C... FROM dual                   --anchor member
UNION ALL
SELECT A', B', C'... from Tablename where...   --recursive member
)
select ... from Tablename where ...

Refactoring the Factorial

One fun thing about recursive WITH, aka recursive subquery refactoring, is the ease with which we can implement a recursive algorithm in SQL. Let’s warm up with a classic example of recursion: finding the factorial of a number. Factorial(n) = n! = 1*2*3*…*n . It’s a classic example because Factorial(n) can be defined recursively as:

Factorial(0) = 1
Factorial(n) = Factorial(n-1) * n

Here’s a first pass at implementing that directly in SQL to find the factorial of 5, using a recursive WITH subquery:

WITH Factorial (operand,total_so_far) AS
(SELECT 5 operand, 5 total_so_far FROM dual    -- Using anchor member to pass in "5"
UNION ALL
SELECT operand-1, total_so_far * (operand-1) FROM Factorial
WHERE operand > 1)
SELECT * FROM Factorial;

   OPERAND TOTAL_SO_F
---------- ----------
         5          5
         4         20
         3         60
         2        120
         1        120

and to display just the result, we select it from Factorial:

WITH Factorial (operand,total_so_far) AS
(SELECT 5 operand, 5 total_so_far FROM dual    -- Find the factorial of 5
UNION ALL
SELECT operand-1, total_so_far * (operand-1) FROM Factorial
WHERE operand > 1)
SELECT MAX(operand) || '! = ' || MAX(total_so_far) AS RESULT FROM Factorial;

RESULT
-----------------
5! = 120

Ahem! I have cheated a little for simplicity here. The query doesn’t take into account that Factorial(0) = 1:

WITH Factorial (operand,total_so_far) AS
(SELECT 0 operand, 0 total_so_far FROM dual    -- Find the factorial of 0
UNION ALL
SELECT operand-1, total_so_far * (operand-1) FROM Factorial
WHERE operand > 1)                             -- This is going to get me nowhere fast...
SELECT * FROM Factorial;

  OPERAND TOTAL_SO_F
---------- ----------
         0          0

To do it properly, we need to include Factorial(0) = 1 in the recursive subquery:

WITH Factorial (operand,total_so_far) AS
(SELECT 0 operand, 0 total_so_far FROM dual    -- Find the factorial of 0
UNION ALL
SELECT operand-1, 
CASE                                           -- Factorial (0) = 1
  WHEN operand=0 THEN 1
  ELSE (total_so_far * (operand-1))
  END
FROM Factorial
WHERE operand >= 0)
SELECT MAX(operand) || '! = ' || MAX(total_so_far) AS RESULT FROM Factorial;

RESULT
------------------------------------------------------------------------------------
0! = 1

We can also reverse direction and recursively build a table of factorials, multiplying as we go.
That’s the approach Lucas Jellema takes in his excellent blog post on factorials in SQL.

WITH Factorial (operand,output) AS
(SELECT 0 operand, 1 output FROM dual
UNION ALL
SELECT operand+1, output * (operand+1) FROM Factorial
WHERE operand < 5)
SELECT * FROM Factorial;

   OPERAND     OUTPUT
---------- ----------
         0          1
         1          1
         2          2
         3          6
         4         24
         5        120

There are two nice things about this approach: first, every row of the subquery result contains n and n! , and second, the rule that 0! = 1 is elegantly captured in the anchor member.

denrael ev’ew tahw gniylppA

Now let’s do something more interesting – reversing a string. Here’s some sample code in C from the CS 211 course at Cornell:

 public String reverseString(String word) {
     if(word == null || word.equals(""))
        return word;
     else
        return reverseString(word.substring(1, word.length())) + 
            word.substring(0,1);
  }

Let’s run through an example word to see how it works. For simplicity I’ll write reverseString(“word”) as r(word). Using “cat” as the word, stepping through the algorithm gives:

r(cat) = r(r(at))+c = r(r(r(t))+a+c = r(r(r(r())+t+a+c = ''+t+a+c = tac

Now to rewrite the same function in SQL. Using the same example string, “cat,” I want my recursively defined table to look like this:

in   out
--------
cat 
at   c
t    ac
     tac

In C, the initial letter in the word is the 0th letter, and in SQL, it’s the 1st letter. So the C expression word.substring(1,N) corresponds to SQL expression substr(word,2,N-1) . With that in mind, it’s easy to rewrite the C algorithm in SQL:

WITH WordReverse (INPUT, output) AS
  (SELECT 'CAT' INPUT, NULL output FROM dual
   UNION ALL
   SELECT substr(INPUT,2,LENGTH(INPUT)-1), substr(INPUT,1,1) || output
   FROM wordReverse
   WHERE LENGTH(INPUT) > 0
  )
SELECT * FROM wordReverse;

INPUT    OUTP
-------- ----
CAT
AT       C
T        AC
         TAC

NOTE: if using 11.2.0.3 or earlier, you might get “ORA-01489: result of string concatenation is too long” when reversing anything longer than a few letters. This is due to Bug 13876895: False ora-01489 on recursive WITH clause when concatenating columns. The bug is fixed in 11.2.0.4 and 12.1.0.1, and there’s an easy workaround: Cast one of the inputs to the concatenation as a varchar2(4000).

We could make this query user-friendlier by using a sql*plus variable to hold the input string. Another approach is to add an additional subquery to the with block to “pass in” parameters. I picked this up from Lucas Jellema’s post mentioned above, and wanted to give it a try, so I’ll add it in to my WordReverse query here.

Let’s use this to reverse a word that’s really quite atrocious:

WITH
params AS
  (SELECT 'supercalifragilisticexpialidocious' phrase FROM dual),
WordReverse (inpt, outpt) AS
  (SELECT phrase inpt, CAST(NULL AS varchar2(4000)) outpt FROM params
   UNION ALL
   SELECT substr(inpt,2,LENGTH(inpt)-1), substr(inpt,1,1) || outpt
   FROM wordReverse
   WHERE LENGTH(inpt) > 0
  )
SELECT phrase,outpt AS reversed FROM wordReverse, params
WHERE LENGTH(outpt) = LENGTH(phrase) ;

PHRASE                             REVERSED
---------------------------------- ----------------------------------------
supercalifragilisticexpialidocious suoicodilaipxecitsiligarfilacrepus

Now you might not have needed to know how to spell “supercalifragilisticexpialidocious” backwards, but one recursive requirement that does come up often is querying hierarchical data. I wrote a series of posts on hierarchical data recently, using Oracle’s CONNECT BY syntax. But recursive WITH can also be used to query hierarchical data. That’ll be the subject of my next post.


Republished with permission. Original URL: http://rdbms-insight.com/wp/?p=94




io

Forellen Station Deluxe normaal €399,00 nu voor maar €320,00

Forellen Station deluxe Merk: TFT TFT heeft wederom een kwaliteitsproduct voor de forelvisser op de markt gebracht. De TFT forellen Station Deluxe. Een tas met vele mogelijkheden. Het station bestaat uit de volgende onderdelen: - 1 draagtas , hierin passen alle onderdelen - 1x een deegtablet hierin kunt u eenvoudig uw deegpotjes plaatsen, zo heeft ze bij de hand - 1 x een assdoosjes tablet ( op de afbeelding zijn ze verschillende kleuren, maar in het echt hebben ze allemaal een rode deksel) - 1 x een tackle tas :deze kleinere tas kunt u aan de voorzijde van het station plaatsen. - 1 x het staanderwerk, waarom heen ook een tas zit. In deze grote tas zitten een tweedeling. Genoeg ruimte dus om al uw hengelsportartikelen in op te bergen, en handig mee te nemen. Wilt u een filmpje over het forellen station bekijken? ( helaas alleen nog in het duits te vinden) https://www.youtube.com/watch?v=m8JUzhcUtVc




io

te koop: shimano aspire competition 13m nieuw

te koop: shimano aspire competition 13m nieuw. topsets en cupset apart verkrijgbaar.tophengel elastiek gemonteerd. eventueel ook op 14.5m verkrijgbaar.




io

te koop visstation van matrix

te koop..een zeer mooi feeder visstation van het merk matrix.het is 1 klein jaartje oud maar in super mooie staat.er zitten heel veel extra bij.mocht je interesse hebben stuur ik graag wat foto s naar u.gr smeets




io

vaste stok presto ignition a60 13 m gis larc

hengel preston ignition a 60 13 m. de eigenschappen van deze hengel is suncore fusion en magic steps. ook nog larc en gis systeem. 2 topsets van 5 delen. ook nog kokers bij geleverd. 3 keer mee gevist zo goed als nieuw dus.weg wegens niet meer vissen op het kanaal.advies prijs is 1799 euro.je mag bieden vanaf 750 euro vindt ik een goede prijs.




io

Come migliorare il processo di acquisto

Sono fortunato. Negli ultimi anni ho avuto la possibilità di partecipare alla progettazione e realizzazione di alcuni tra gli e-commerce più importanti nati in Italia. È bello, interessante e istruttivo lavorare per un e-commerce, perché il sito non è fine … Continua a leggere

L'articolo Come migliorare il processo di acquisto proviene da Fucinaweb.




io

Progettare applicazioni mobile

Non si ferma la pubblicazione nel blog Internet della BBC, già tema di un mio precedente intervento, di articoli che spiegano nel dettaglio il processo di progettazione di siti e servizi. Questa volta tocca all’applicazione iPhone del player che permette … Continua a leggere

L'articolo Progettare applicazioni mobile proviene da Fucinaweb.




io

I bozzetti in aiuto alla comunicazione di progetto

Anche quest’anno (dopo il 2009, 2010 e 2011) ho partecipato come speaker a Better Software. Questa volta ho presentato “Carta, penna e calamaio. I bozzetti in aiuto alla comunicazione di progetto”. Molte incomprensioni in fase progettuale derivano dalla mancanza di un … Continua a leggere

L'articolo I bozzetti in aiuto alla comunicazione di progetto proviene da Fucinaweb.




io

Quando un foglio volante è meglio di un’app

Perché realizzare un’applicazione mobile per un festival? Forse per permettere ai visitatori di accedere al calendario degli eventi senza stampare il programma. Magari per essere aggiornati sulle variazioni dell’ultimo minuto. Probabilmente per facilitare l’accesso ai luoghi degli incontri. O per … Continua a leggere

L'articolo Quando un foglio volante è meglio di un’app proviene da Fucinaweb.




io

10 accorgimenti per migliorare il checkout e-commerce

68%. E’ la percentuale di visitatori che aggiungono almeno un prodotto al carrello senza concludere l’acquisto. Un numero alto, perché il carrello è usato come contenitore temporaneo, ma soprattutto perché il percorso di acquisto è spesso molto lungo e complicato. A Meet Magento presenterò alcuni suggerimenti per … Continua a leggere

L'articolo 10 accorgimenti per migliorare il checkout e-commerce proviene da Fucinaweb.




io

NBA DFS Projections - March 22 (Free Preview)

Check out a preview of our daily NBA DFS projections in the forums, part of a new DFS package exclusively created for #FullTimeArmy!




io

NBA DFS Projections - March 23 (Free Preview)

Check out a preview of our daily NBA DFS projections in the forums, part of a new DFS package exclusively created for #FullTimeArmy!




io

NBA DFS Projections - March 25 (Free Preview)

Check out a preview of our daily NBA DFS projections in the forums, part of a new DFS package exclusively created for #FullTimeArmy!




io

Dr. Roto's Fantasy Baseball Auction Strategies (Premium)

Senior Fantasy Baseball Expert Dr. Roto lays out a few guidelines to help you triumph in your Fantasy Baseball auctions this season!




io

NBA DFS Projections - March 26 (Free Preview)

Check out a preview of our daily NBA DFS projections in the forums, part of a new DFS package exclusively created for #FullTimeArmy!