MySQL SELECT Statement
SELECT reads data from a table. It is the command you will use most.
All columns
SELECT * FROM students;
Result
| id | name | city | marks | course_id |
|---|---|---|---|---|
| 1 | Robin | Delhi | 85 | 1 |
| 2 | Maria | Mumbai | 92 | 2 |
| 3 | John | Pune | 78 | 1 |
| 4 | Asha | Jaipur | 88 | 3 |
| 5 | Vikram | Delhi | 65 | NULL |
| 6 | Neha | Mumbai | 45 | 2 |
* means all columns.
Specific columns
SELECT name, city FROM students;
Result
| name | city |
|---|---|
| Robin | Delhi |
| Maria | Mumbai |
| John | Pune |
| Asha | Jaipur |
| Vikram | Delhi |
| Neha | Mumbai |
Note:
In real programs, write the column names you need instead of *. It is faster, and the code does not break when a column is added.
Calculated columns
You can calculate values in a query. Give the result a name with AS.
SELECT name, marks, marks + 5 AS marks_with_bonus FROM students LIMIT 2;
Result
| name | marks | marks_with_bonus |
|---|---|---|
| Robin | 85 | 90 |
| Maria | 92 | 97 |
A simpler example with text:
SELECT CONCAT(name, ' from ', city) AS student FROM students LIMIT 2;
Result
| student |
|---|
| Robin from Delhi |
| Maria from Mumbai |
SELECT without a table
SELECT 5 + 3 AS total, NOW() AS today;
MySQL can also calculate without a table. NOW() gives the current date and time.
Summary
SELECT columns FROM table;reads data.*means all columns.- Give a name to calculated columns with
AS. - Next: MySQL WHERE.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |