Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create virtual column using MySQL SELECT?

Tags:

php

select

mysql

If I do SELECT a AS b and b is not a column in the table, would query create the "virtual" column?

in fact, I need to incorporate some virtual column into the query and process some information into the query so I can use it with each item later on.

like image 963
Skuta Avatar asked Jan 18 '09 14:01

Skuta


People also ask

How do I add a virtual column in SQL?

Syntax for adding new virtual column, ==> Alter table table_name add column column_name generated always as column_name virtual; Example : Alter table contacts add column generated always as mydbops_test virtual / stored.

How do I create a new column in MySQL query?

Syntax. The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ];

What is virtuality in MySQL?

VIRTUAL: Column values are not stored, but are evaluated when rows are read, immediately after any BEFORE triggers. A virtual column takes no storage. -- MySQL Reference. STORED: Column values are evaluated and stored when rows are inserted or updated. A stored column does require storage space and can be indexed.

What is virtual column in database?

In relational databases a virtual column is a table column whose value is automatically computed using other columns values, or another deterministic expression.


2 Answers

Something like:

SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users 

This allows you to make operations and show it as columns.

EDIT:

you can also use joins and show operations as columns:

SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country FROM users u LEFT JOIN countries c ON u.country_id = c.id 
like image 99
Gabriel Sosa Avatar answered Oct 03 '22 03:10

Gabriel Sosa


Try this one if you want to create a virtual column "age" within a select statement:

select brand, name, "10" as age from cars... 
like image 29
ninsky Avatar answered Oct 03 '22 04:10

ninsky