[SQL/ORACLE] ROWNUM 함수 (SQL의 TOP 함수) 특정 행까지만 출력
https://school.programmers.co.kr/learn/courses/30/lessons/59411
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
입양을 간 동물 중, 보호 기간이 가장 길었던 동물 두 마리의 아이디와 이름을 조회하는 SQL문을 작성해주세요. 이때 결과는 보호 기간이 긴 순으로 조회해야 합니다.
WITH TEMP01 AS (
SELECT I.ANIMAL_ID, I.NAME
FROM ANIMAL_INS I
JOIN ANIMAL_OUTS O ON I.ANIMAL_ID = O.ANIMAL_ID
ORDER BY O.DATETIME - I.DATETIME DESC
)
SELECT * FROM TEMP01 WHERE ROWNUM <= 2
특정 행까지 추출하기 위해서 SQL에서는 TOP 함수를 사용하지만, ORACLE에서는 ROWNUM 함수를 사용한다.
이 때 WHERE 절을 바로 쓰면 ORDER BY가 적용되기 전에 ROWNUM 함수가 먼저 적용되기 때문에, 위에 처럼 먼저 ORDER BY로 정렬한 후에 추출하고자 하는 행의 개수를 ROWNUM을 통해 추출한다.
https://docs.oracle.com/cd/B14117_01/server.101/b10759/pseudocolumns008.htm
ROWNUM
ROWNUM For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on. You can use RO
docs.oracle.com
If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level query, then you can force the ROWNUM condition to be applied after the ordering of the rows. For example, the following query returns the employees with the 10 smallest employee numbers. This is sometimes referred to as top-N reporting:
SELECT * FROM
(SELECT * FROM employees ORDER BY employee_id)
WHERE ROWNUM < 11;