Firebird SQL Best Practices
Firebird SQL Best Practices
SMALLDISTINCT
=============
0
1
2
WITH RECURSIVE
t AS (SELECT min(smalldistinct) AS smalldistinct FROM HASH
UNION ALL
SELECT (SELECT min(smalldistinct) FROM HASH
WHERE smalldistinct > t.smalldistinct)
FROM t WHERE t.smalldistinct IS NOT NULL)
SELECT smalldistinct FROM t WHERE smalldistinct IS NOT NULL
UNION ALL
SELECT NULL FROM RDB$DATABASE
WHERE EXISTS(SELECT 1 FROM HASH WHERE smalldistinct IS NULL)
MERGE
The purpose of MERGE is to read data from the source and INSERT, UPDATE or
DELETE in the target table according to a condition.
The source may be table, a view or "anithing you can select from" in general. Each
source record will be used to update, or delete one or more target record, insert a new
record in the target table, or neither.
ITEM_ID BALANCE
========== ============
10 2200
20 1900
create table buy ( item_id int not null primary key, volume int);
insert into buy values (10, 1000);
insert into buy values (30, 300);
commit;
select * from buy;
ITEM_ID VOLUME
========== ============
10 1000
30 300
create table sale ( item_id int not null primary key, volume int);
insert into sale values (10, 2200);
insert into sale values (20, 1000);
commit;
select * from sale;
ITEM_ID VOLUME
========== ============
10 2200
20 1000
rollback;
SELECT * FROM stock ORDER BY item_id;
ITEM_ID BALANCE
========== ============
10 2200
20 1900
A Window
• Represents set of rows that is used to compute additionnal attributes
• Based on three main concepts
• partition
• specified by PARTITION BY clause in OVER()
• Allows to subdivide the table, much like GROUP BY clause
• Without a PARTITION BY clause, the whole table is in a single partition
• order
• defines an order with a partition
• may contain multiple order items
• Each item includes a value-expression
• NULLS FIRST/LAST defines ordering semantics for NULL
• this clause is independant of the query's ORDER BY clause
Performance
List orders, quantity ordered and cumulative quantity ordered by day
Thank you !