Set MySQL select in a custom variable



Let us first create a table −

mysql> create table DemoTable2013    -> (    -> Name varchar(20)    -> ); Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2013 values('Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable2013 values('David'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2013 values('Mike'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable2013 values('Sam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable2013 values('Bob'); Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2013;

This will produce the following output −

+-------+ | Name | +-------+ | Chris | | David | | Mike | | Sam | | Bob | +-------+ 5 rows in set (0.00 sec)

Here is the query to set MySQL SELECT statement in a custom variable −

mysql> set @query := (select count(*) from DemoTable2013); Query OK, 0 rows affected (0.00 sec) mysql> select Name -> from DemoTable2013 -> where (@query := @query-1) = 0;

This will produce the following output −

+------+ | Name | +------+ | Bob | +------+ 1 row in set (0.00 sec)
Updated on: 2020-04-06T12:51:59+05:30

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements