Skip to content

Commit ab3aeb6

Browse files
committed
views
1 parent ff80877 commit ab3aeb6

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*****************************************/
2+
/* Creating Views */
3+
/*****************************************/
4+
5+
USE mosh_sql_invoicing;
6+
7+
CREATE VIEW v_sales_by_client AS (
8+
SELECT c.client_id, c.name, SUM(invoice_total) AS total_sales
9+
FROM clients c
10+
JOIN invoices i USING (client_id)
11+
GROUP BY client_id, name
12+
);
13+
14+
SELECT *
15+
FROM v_sales_by_client;
16+
17+
/*view to see the balance for each client.*/
18+
CREATE OR REPLACE VIEW v_clients_balance AS (
19+
SELECT c.client_id, c.name, SUM(i.invoice_total - i.payment_total) AS balance
20+
FROM clients c
21+
JOIN invoices i ON c.client_id = i.client_id
22+
GROUP BY 1
23+
);
24+
25+
/*****************************************/
26+
/* Altering or Dropping Views */
27+
/*****************************************/
28+
29+
DROP VIEW v_sales_by_client;
30+
31+
CREATE OR REPLACE VIEW v_clients_balance AS (
32+
SELECT c.client_id, c.name, SUM(i.invoice_total - i.payment_total) AS balance
33+
FROM clients c
34+
JOIN invoices i ON c.client_id = i.client_id
35+
GROUP BY 1
36+
);
37+
38+
39+
/*****************************************/
40+
/* Updatable Views */
41+
/*****************************************/
42+
43+
CREATE VIEW v_invoices_with_remaining_balance AS (SELECT invoice_id, number, client_id, invoice_total, payment_total,
44+
invoice_total - payment_total AS remaining_balance,
45+
invoice_date, due_date, payment_date
46+
FROM invoices);
47+
48+
SELECT * FROM v_invoices_with_remaining_balance;
49+
50+
-- delete
51+
DELETE FROM v_invoices_with_remaining_balance
52+
WHERE invoice_id = 1;
53+
54+
-- update
55+
UPDATE v_invoices_with_remaining_balance
56+
SET due_date = '2020-01-01'
57+
WHERE invoice_id = 2;
58+
59+
60+
/*****************************************/
61+
/* WITH OPTION CHECK Clause */
62+
/*****************************************/
63+
/*To ensure the consistency of a view so that users can only display or update data that visible through the view,
64+
you use the WITH CHECK OPTION when you create or modify the view.*/
65+
66+
CREATE OR REPLACE VIEW v_invoices_with_remaining_balance AS (SELECT invoice_id, number, client_id, invoice_total, payment_total,
67+
invoice_total - payment_total AS remaining_balance,
68+
invoice_date, due_date, payment_date
69+
FROM invoices
70+
WHERE (invoice_total - payment_total) > 0
71+
) WITH CHECK OPTION;
72+
73+
SELECT * FROM v_invoices_with_remaining_balance;
74+
75+
UPDATE v_invoices_with_remaining_balance
76+
SET payment_total = invoice_total
77+
WHERE invoice_id = 2;

0 commit comments

Comments
 (0)