Sub Query 서브 쿼리

  • 서브 쿼리에 대해 잘 정리해놓은 글 link
  • 서브 쿼리는 부모 쿼리 안에 작성하는 내부 쿼리를 말합니다. ()로 묶어서 서브 쿼리를 작성해줄 수 있습니다.
  • 예제
    SELECT A.*
    FROM (SELECT NAME
        FROM OCCUPATIONS) as A



  • 서브 쿼리의 종류
    • 중첩 서브 쿼리
      • WHERE 구문 안에 작성하는 서브 쿼리
    • 인라인 뷰
      • FROM 구문 안에 작성하는 서브 쿼리
    • 스칼라 서브 쿼리
      • SELECT 구문 안에 작성하는 서브 쿼리


  • 보통 일반적 join 연산이 서브쿼리보다 성능이 좋다고 알려져있다고 합니다.
    • join vs Sub Query 연산 성능 차이에 대해 설명한 글 link


  • 서브 쿼리 사용 시 주의 점
    • ()을 사용하여 감싸서 사용해야 합니다.
    • ORDER BY를 사용하지 못한다고 합니다.


  • 서브 쿼리가 사용되는 절 참고한 link
    • SELECT
    • FROM
    • WHERE
    • HAVING
    • ORDER BY
    • INSERT 절의 VALUES
    • UPDATE 절의 SET



Control Flow Function 제어문

  • Control Flow Function에 대해 잘 정리해놓은 글 link

  • MySQL에서 사용하는 Control Flow Function에는 아래와 같이 4가지가 있다고 합니다.


    • CASE operator

      • 예시
        SELECT CompanyName, 
        CASE Country WHEN 'USA' THEN 'North America' 
                   WHEN 'Canada' THEN 'North America'
                   WHEN 'Brazil' THEN 'South America'
                   WHEN 'Japan' THEN 'Asia'
                   WHEN 'Singapore' THEN 'Asia'
                   WHEN 'Australia' THEN 'Australia'
                   ELSE 'Europe' END AS Continent
        FROM Suppliers
        ORDER BY CompanyName;
    • IF/ELSE construct

      • IF(expr1,expr2,expr3) : expr1이 참이면 expr2 반환, 거짓이면 expr3 반환
      • 예시
        SELECT ProductName, 
        UnitPrice,
        IF(UnitPrice>=20, 'High Price', 'Low Price') AS "Price Level"
        FROM Products;
    • IFNULL

      • IFNULL(expr1,expr2) : expr1NULL이 아니면 expr1 반환, NULL이면 expr2 반환
      • 예시
        SELECT FirstName, LastName, IFNULL(ReportsTo, 'Is CEO')
        FROM Employees;
    • NULLIF

      • NULLIF(expr1,expr2) : 만약 expr1 = expr2가 참이면 NULL 반환, 거짓이면 expr1 반환
      • 예시
        SELECT CompanyName, 
         Fax, 
         NULLIF(IF(Fax='', 'No Fax', 'Got Fax'), 'No Fax') AS Note
        FROM Customers;
  • 처리된 각 행의 값을 반환해주는 기능을 가지고 있습니다.

  • 각 조건에 따른 결과를 반환 해 줍니다.

  • SELECT, WHERE, ORDER BY, GROUP BY 절에서 사용할 수 있습니다.


    Variable Assignment 변수 처리

  • SQL의 SET에 대한 정보 참고 글 link

  • MySQL Variable Assignment에 대해 정리해놓은 글 link


  • @의 의미

    SET @rownum:=0;
    
    SELECT
      @rownum:=@rownum+1, CRE_DTM
    FROM TB_API_ACCESS_LOG;
    • 여기서는 쉽게 변수라고 생각하면 된다고 합니다. 행이 바뀔 때마다 1씩 증가시키며 주로 행 번호를 부여하기 위해서 사용하는 변수라고 할 수 있습니다.

    • 해당 내용을 질문한 글 link


  • 변수 선언 예시

    • msrp 변수 내 가장 큰 값을 @msrp 변수로 저장

      SELECT 
        @msrp:=MAX(msrp)
      FROM
        products;
    • msrp 변수 값이 위에서 지정한 @msrp 값과 동일한 경우를 출력하는 코드

      SELECT 
        productCode, productName, productLine, msrp
      FROM
        products
      WHERE
        msrp = @msrp;
    • 만약 하나의 변수에 선언하려는 값이 여러개일 경우에는 마지막 행의 값 하나만을 저장합니다.

Easy

Practice > SQL > Advanced Select > Type of Triangle

Q. Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table:

  • Equilateral: It's a triangle with sides of equal length.
  • Isosceles: It's a triangle with sides of equal length.
  • Scalene: It's a triangle with sides of differing lengths.
  • Not A Triangle: The given values of A, B, and C don't form a triangle.
  • 나의 풀이
SELECT IF (A=B AND B=C, 'Equilateral', 
           IF (A+B <= C OR A+C <= B OR B+C <= A, 'Not A Triangle', 
               IF ((A=B OR B=C OR A=C), 'Isosceles', 'Scalene')))
FROM TRIANGLES

IF 구문을 이용하여 코드를 작성하였다. 삼각형이라 각 상황에 맞는 조건을 하나 하나 작성할 수 있었다. 강한 조건을 먼저 적용해주는 것이 중요한 문제 같았다.

  • 다른 사람 풀이
SELECT CASE             
            WHEN A + B > C AND B + C > A AND A + C > B THEN
                CASE 
                    WHEN A = B AND B = C THEN 'Equilateral'
                    WHEN A = B OR B = C OR A = C THEN 'Isosceles'
                    ELSE 'Scalene'
                END
            ELSE 'Not A Triangle'
        END
FROM TRIANGLES;

CASE를 이용한 구문으로 가독성이 좋다고 느껴졌다.

Medium

Practice > SQL > Advanced Select > The PADS

Q. Generate the following two result sets:

  1. Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

  2. Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

    There are a total of [occupation_count] [occupation]s.

    where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically.

⚡ Note: There will be at least two entries in the table for each type of occupation.

  • 나의 풀이
SELECT CONCAT(NAME,'(',left(OCCUPATION,1),')')
FROM OCCUPATIONS
ORDER BY NAME;

SELECT CONCAT('There are a total of ',
            COUNT(OCCUPATION),' ',LOWER(OCCUPATION),'s.') 
FROM OCCUPATIONS
GROUP BY OCCUPATION
ORDER BY COUNT(OCCUPATION),OCCUPATION;

처음으로 Medium 난이도를 풀어보았다. 생각보다는 어렵지 않았다. 다양한 함수와 형식들을 많이 알아가고 있는 것 같아서 뿌듯하다.

  • 다른 사람 풀이
select concat(name, '(', substr(occupation,1,1), ')')
from occupations
order by name asc;

select concat('There are total ', count(1), ' ' , lower(occupation), 's.')
from occupations
group by occupation
order by count(1) asc, occupation asc;

내 풀이와 거의 유사한 것 같다. count(1)을 활용하는 것이 눈에 띄었다.

Hard

Practice > SQL > Advanced Join > Interviews

Q. Samantha interviews many candidates from different colleges using coding challenges and contests. Write a query to print the contest_id, hacker_id, name, and the sums of total_submissions, total_accepted_submissions, total_views, and total_unique_views for each contest sorted by contest_id. Exclude the contest from the result if all four sums are .

⚡ Note: A specific contest can be used to screen candidates at more than one college, but each college only holds screening contest.

+ Recent posts