Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why used Views instead of Sql Statement [duplicate]

Tags:

sql-server

Possible Duplicate:
Use SQL View or SQL Query?

What is the reason writting a views instead of writting a sql statement?

like image 900
vivek Avatar asked Mar 03 '26 10:03

vivek


1 Answers

Yes, there are lots of reasons.

  1. Security: when you want to limit what certain user can see from a table you can just grant access to the view instead of the underlying table.
  2. Simplicity: when you need to use the query/view on a subquery. Or just when you don't want to type several times the same complex query over and over again.
  3. Materialized Views (if your RDBMS supports it): can increase performance on some analytical queries (Data-warehousing).
  4. Partitioning: if you want a relation (view) representing just a subset of other relation (table). I.E. you can create invoices_2011 view with just invoices made in 2011 from the table invoices.

Update:

On the example asked:

Let's say you have this table:

create table customers (
   customer_id integer primary key,
   name varchar(200) not null,
   dob date
);

And you want user bart to see only name and dob of customers born before 1980. You can't grant access to customers table to bart because he could see anything stored on it.

You instead create a view:

create view customers_1980 as 
select name, dob from customers
 where dob < '1980-01-01';

And then grant bart access to that view:

grant select on customers_1980 to bart;

This way, bart will only have access to the restricted view subset of customers table.

like image 130
Pablo Santa Cruz Avatar answered Mar 05 '26 22:03

Pablo Santa Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!