SQL

SQL View

SQL View

This page covers SQL view.

The concept of views occurs in many programming languages.

Views represent tables virtually and do not store data values in a database. Instead, the data derives from the rows and columns of a real table.

The data of the view is defined by a query.

As such, SQL methods as well as statements can apply on views.

This tutorial covers:

  • creating views
  • altering views
  • dropping views

Create view

The syntax for creating views is easy. The keywords are “create view as”, followed by the query statement.

Below is an example of creating a view.

CREATE VIEW only_student_names AS
SELECT firstName, lastName
FROM student_info;

With the above statement, we create a separate (virtual) table under the name “only_student_names“. The table selects only the names of the student, first name and last name.

Let’s see the result by executing the statement “SELECT * FROM only_student_names;“.

The result:

firstNamelastName

As mentioned above, now there is a second modified table. But the table is only virtual, and as such, does not exist in the database.

We can check this with the statement that shows all tables in the database.

SELECT * FROM sys.tables;

The above statement will display only one existing table (student_info).

Alter view

In SQL, views can be modified.

This happens through the statement keywords “alter view as”.

Below is an example of changing (updating) an SQL view.

ALTER VIEW only_student_names AS
SELECT firstName
FROM student_info;

The above now modifies the previous view, which included first name and last name, to a virtual table of only containing the first name of the student.

Use “SELECT * FROM only_student_names;” to check the outcome.

Drop view

Dropping an SQL view is quite straightforward.

Use the keywords “drop view”.

DROP VIEW only_student_names;

Now let’s check the changes with the statement “SELECT * FROM sys.views;” which shows all available views.


Next: SQL Insert