MySQL: Views

Its been a long time since I have posted anything, hopefully interesting. In this post we’ll see Views in MySQL. Its not just MySQL, every database has it, we are just using MySQL. I’ll try to explain it in the most simplest terms I can.

Views are just like tables but there is a big difference. Views are made by querying the actual tables. Its like you form a query and save it as view in your database. So basically views are virtual tables which provide sort of abstraction, remember sort of, because they are created by querying actual tables. So whenever we select from views it runs the saved query and gives the resulted tuples. It will be more clear when we see the example. Every organization which uses database declare views and set privileges for it according to category of users which we call permissions. Plus views are more secured obviously, in most cases, because users are not interacting with actual database.

Now, technically views are just stored queries. They just makes our job easier when it comes to the coding part. You create queries and save in database and when needed that data just call select statement for that view.

Required: MySQL


Consider tables table1 and table2. Please ignore the order of the tables. Declaration of table is for understanding properly and not actual defination.

  id int primary key,
  name varchar,
  dept_id int foreign key references,

  id int primary key,
  department varchar,
  location varchar,

Below is the definition of view employees and selecting from view.

CREATE VIEW AS employees(
  SELECT, b.department, b.location FROM table1 a, table2 b WHERE a.dept_id =
SELECT * FROM employees;

Explanation: There is nothing to explain for the syntax, its self explanatory.

Syntax is almost same in all databases. There are further more things about views like updating views, which I do not recommend. This is because views can only be updated when it is derived from a single table.

For example consider the above view if we try to insert in the view what will be the value of dept_id in table1. Answer is null but we cannot have null in dept_id column clearly, it must have some value because every name must be associated with some dept_id.

There more options like algorithm, with check options etc. You should explore more about views and about creating views.

1 comment

  1. I am no longer positive the place you’re getting your info, however great topic. I needs to spend some time finding out much more or figuring out more. Thanks for excellent info I used to be on the lookout for this information for my mission.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: