[손에 잡히는 10분 SQL - 벤 포터 지음, 박남혜 옮김] 책의 학습 후 정리자료입니다.
뷰가 데이터를 갖고 있지 않기 때문에 뷰를 사용할 때마다 쿼리가 실행된다.
여러 개의 조인과 필터가 있는 복잡한 뷰를 생성하거나,
여러 겹의 뷰를 생성한다면 성능은 급격히 저하된다.
뷰를 빈번하게 사용하는 프로그램이라면 배포하기 전에 반드시 테스트해보자.
CREATE VIEW
문을 사용해서 생성한다.뷰를 삭제하려면 DROP 문을 사용한다. 문법은 DROP VIEW 뷰이름; 이다.
뷰를 덮어쓰거나 또는 업데이트하려면, 뷰를 먼저 삭제한 후에 다시 생성해야 한다.
CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id
FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND OrderItems.order_num = Orders.order_num
SELECT cust_name, cust_contact
FROM ProductCustomers
WHERE prod_id = 'RGAN01';
특정 데이터에 종속되지 않는 뷰를 생성하는 것은 좋은 생각이다.
뷰의 범위를 확장하면 재사용이 가능하기 때문에 좀 더 유용하다.
또한, 여러개의 비슷한 뷰를 만들고 관리하지 않아도 된다.
vend_name
)과 위치(vend_country
)를 하나로 결합한 열로 가져온다.SELECT RTRIM(vend_name) || ' (' || RTRIM(vend_country) || ')' AS vend_title
FROM Vendors
ORDER BY vend_name;
CREATE VIEW VendorLocations AS
SELECT RTRIM(vend_name) || ' (' || RTRIM(vend_country) || ')' AS vend_title
FROM Vendors
SELECT *
FROM vendorLocations;
뷰를 생성하는 문법은 DBMS와 상관없이 상당히 일관된다고 언급한 바가 있다.
위 사실과는 별개로 여러 버전의 문장이 쓰이는 이유는 뷰가 단순히 SELECT 문을 감싼 것이기 때문이다.
각 DBMS에서 SELECT 문이 따라야 하는 모든 규칙과 제약을 그대로 적용받기 때문이다.
CREATE VIEW CustomerEmailList AS
SELECT cust_id, cust_name, cust_email
FROM Customers
WHERE cust_email IS NOT NULL;
SELECT *
FROM CustomerEmailList;
CREATE VIEW OrderItemsExpanded AS
SELECT order_num,
prod_id,
quantity,
item_price,
quantity*item_price AS expanded_price
FROM OrderItems
WHERE order_num = 20008;
SELECT *
FROM OrderItemsExpanded;
CustomerWihOrders
라는 뷰를 작성하라. 원하는 고객을 거르기 위해 Orders
테이블과 조인할 수 있다. 그 후 데이터가 맞는지 확인하기 위해 SELECT 문을 작성한다.CREATE VIEW CustomerWithOrders AS
SELECT Customers.cust_id,
Customers.cust_name,
Customers.cust_contact
FROM Customers, Orders
WHERE Customers.cust_id = Orders.cust_id;
SELECT *
FROM CustomerWithOrders;
CREATE VIEW OrderItemsExpanded AS
SELECT order_num,
prod_id,
quantity,
item_price,
quantity*item_price AS expanded_price
FROM OrderItems
ORDER BY order_num;
CREATE VIEW OrderItemsExpanded AS
SELECT order_num,
prod_id,
quantity,
item_price,
quantity*item_price AS expanded_price
FROM OrderItems