The SQL statement MERGE (available from version 9i) provides the functionality of “INSERT or UPDATE” in a single statement.
The basic syntax is:
MERGE INTO <target>
ON (<join conditions>)
WHEN MATCHED THEN UPDATE <SET clause>
WHEN NOT MATCHED THEN INSERT (<column list>) VALUES (<expression list>);
- <target> is the table that we’d like to insert new records into and/or update existing records in
- <source> is usually some SQL query (it may also be simply a table)
- <join conditions> specify the relationship between the source and the target – these conditions determine whether a row from the source exists in the target or not
Each row from the source is looked up in the target table, using the conditions specified in the ON clause. If the row exists in the target table, then the WHEN MATCHED clause is executed – the target row is updated. If the row does not exist in the target table, then the WHEN NOT MATCHED clause is executed – a new row is inserted into the target table.
Let’s take an example. Continue reading
I lectured about Oracle SQL and PL/SQL in a course lately. As always, some issues that had not been part of the planned scope were raised and discussed, so I thought to write short posts about some of them, for the benefit of the participants and everyone else that may find it relevant.
These issues are:
Lateral Inline Views – an official feature of Oracle 12c (was hidden/unsupported/undocumented in 11g) – lets you refer within an inline view to tables that appear to its left in the FROM clause.
Let’s take an example (a simplification of a real-life use case I handled recently). We have a SCHEDULES table, including for each repeatable task the time range in which it should be executed, and the frequency:
create table schedules (
name varchar2(100) not null primary key,
repeat_interval interval day to second
Let’s fill it with 3 records: Continue reading
One of my favorite aggregate functions in Oracle is FIRST (and of course its counterpart, LAST; ok, so two of my favorite aggregate functions).
The very common aggregate functions MIN and MAX allow you (conceptually) to sort a group of rows by some column and return the value of that column from the first or last row in the sorted group.
The FIRST and LAST functions extend this ability, and allow you to sort a group of rows by one column, but return the value of another column from the first or last row in the sorted group. Continue reading
In order to implement a one-to-many relationship we use a foreign key constraint.
To implement a many-to-many relationship Continue reading
We have a parent-child pair of tables with a foreign key constraint between them, and we need to add an index to the parent table, while the application is active.
The parent table is static during the creation of the index (no DML on it), but lots of DML statements are done on the child table. The parent table is relatively big, so the index creation takes a relatively significant time.