Search This Blog

Showing posts with label oracle. Show all posts
Showing posts with label oracle. Show all posts

Friday, January 7, 2011

Select a range from oracle, mysql

I talked about how to select first/top n rows from oracle, mysql, and ms sql server. How do we get the range, say from m to n, where m < n?

Oracle
select id, age from (select id, age, rownum as rn from customer order by age) where rn between :m and :n
MySql
select * from customer order by age limit :m, :n - :m
MS SQL

I don't know how to do it with MS sql server yet. I don't have ms sql server installed. If you happen to know it, please post your solution in the comment.

Tuesday, December 28, 2010

Select first n rows from oracle, MySql and MS Sql

Assume we have table customer with columns id and age. Find first n customers with youngest ages

Oracle
select * from (select * from customer order by age) where rownum < :n
Mysql
select * from customer order by age limit :n
MS Sql
select top :n * from customer order by age

Monday, December 27, 2010

Oracle merge into with only one table

I recently wanted to use oracle MERGE INTO to update a table. With MERGE INTO, it usually works with 2 tables, a source and a target table. However, in my case, I only have one table: update the table if the given id exists, otherwise insert a new row. I initially thought the following should work:
MERGE INTO image i
USING (select id, url from offer_image
WHERE id = :id and url = :url) ii
ON (ii.id = i.id AND ii.url = i.url)
WHEN MATCHED THEN
UPDATE SET
title = :title
WHEN NOT MATCHED THEN
INSERT (i.id, i.url, i.title)
VALUES (:id, :url, :title)
However, it only does update and not insert. I consulted oracle DBA and here is his answer:
"Your source always needs to return a non-empty for the merge to work. In this case your source is returning 0 rows."
Then I came up the following merge statement:
MERGE INTO image i
USING (select 1 from dual) ii
ON (i.id = :id AND i.url = :url)
WHEN MATCHED THEN
UPDATE SET
title = :title
WHEN NOT MATCHED THEN
INSERT (i.id, i.url, i.title)
VALUES (:id, :url, :title)
Note that Oracle table DUAL is a special one row one column table. Here is a good explanation about DUAL