How can we create a MySQL view by selecting some range of values from a base table?

MySQLMySQLi Database

As we know that MySQL BETWEEN operator can be used to select values from some range of values. We can use BETWEEN operator along with views to select some range of values from the base table. To understand this concept we are using the base table ‘student_info’ having the following data −

mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
+------+---------+------------+------------+
6 rows in set (0.00 sec)

Example

The following query will create a view named ‘Info’, to select some values in a particular range, by using ‘BETWEEN’ operator −

mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name BETWEEN 'C' AND 'P';
Query OK, 0 rows affected (0.14 sec)

mysql> Select * from info;
+------+--------+------------+------------+
| id   | Name   | Address    | Subject    |
+------+--------+------------+------------+
| 105  | Gaurav | Chandigarh | Literature |
| 133  | Mohan  | Delhi      | Computers  |
+------+--------+------------+------------+
2 rows in set (0.00 sec)

Similarly, we can use NOT with BETWEEN operator to select the different range of values than we write in the query −

mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name NOT BETWEEN 'C' AND 'P';
Query OK, 0 rows affected (0.06 sec)

mysql> Select * from Info;
+------+---------+------------+-----------+
| id   | Name    | Address    | Subject   |
+------+---------+------------+-----------+
| 101  | YashPal | Amritsar   | History   |
| 125  | Raman   | Shimla     | Computers |
| 130  | Ram     | Jhansi     | Computers |
| 132  | Shyam   | Chandigarh | Economics |
+------+---------+------------+-----------+
4 rows in set (0.00 sec)
raja
Published on 22-Feb-2018 11:11:05
Advertisements