|
1 | 1 | # The Conclusion |
| 2 | + |
| 3 | +This is the last chapter of this SQL tutorial series, in this chapter we will see some miscelaneous topics and best practices. |
| 4 | + |
| 5 | +Topics: |
| 6 | +1. SQL View |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +## SQL Views |
| 11 | + |
| 12 | +A view is a virtual table based on the result-set of an SQL statement. It contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. |
| 13 | + |
| 14 | +It is operated similarly to the base table but does not contain any data of its own. The View and table have one main difference that the views are definitions built on top of other tables (or views). If any changes occur in the underlying table, the same changes reflected in the View also. |
| 15 | + |
| 16 | +We can create a new view by using the CREATE VIEW and SELECT statement. SELECT statements are used to take data from the source table to make a VIEW. |
| 17 | + |
| 18 | +**Syntax:** |
| 19 | + |
| 20 | +```sql |
| 21 | +CREATE [OR REPLACE] VIEW view_name AS |
| 22 | +SELECT columns |
| 23 | +FROM tables |
| 24 | +[WHERE conditions]; |
| 25 | +``` |
| 26 | + |
| 27 | +**Example:** Let's create a view which contains customers complete details using the data we have in Sakila DB(i.e. customer_id, name, address, zip code, city, country, phone, email and status whether active or not). |
| 28 | + |
| 29 | +To achieve this we will need to use below tables to get corresponding fields: |
| 30 | + |
| 31 | +- customer: customer_id, first_name, last_name, email, active |
| 32 | +- address: address, postal_code, phone |
| 33 | +- city: city |
| 34 | +- country: country |
| 35 | + |
| 36 | +```sql |
| 37 | +CREATE OR REPLACE VIEW customer_details_vw AS |
| 38 | +SELECT cu.customer_id AS ID, |
| 39 | +CONCAT(cu.first_name,' ',cu.last_name) AS 'customer name', |
| 40 | +a.address AS address, |
| 41 | +a.postal_code AS 'zip code', |
| 42 | +ci.city AS city, |
| 43 | +co.country AS country, |
| 44 | +a.phone AS phone, |
| 45 | +cu.email AS email, |
| 46 | +IF(cu.active,'active','') AS status |
| 47 | +FROM customer cu |
| 48 | +JOIN address a ON cu.address_id = a.address_id |
| 49 | +JOIN city ci ON a.city_id = ci.city_id |
| 50 | +JOIN country co ON ci.country_id = co.country_id; |
| 51 | +``` |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
0 commit comments