MySQL Tutorial
The SELECT
statement in MySQL is used to retrieve data from one or more tables in a database. It is the most commonly used SQL command for querying data.
SELECT column1, column2 FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM students;
Below is a selection from the "students" table in the school_db database:
student_id |
name |
gender |
city |
age |
score |
course_id |
|
phone_number |
---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
The following SQL statement selects ALL the columns from the "students" table:
The following SQL statement selects the "name" column from the "students" table:
The SELECT DISTINCT
statement removes duplicate values and returns only unique records.
SELECT DISTINCT column_name FROM table_name;
The following SQL statement selects only DISTINCT values from the "Country" column in the "students" table:
The following SQL statement selects all (including the duplicates) values from the "name" column in the "students" table:
Feature |
SELECT |
SELECT DISTINCT |
---|---|---|
Returns duplicates? |
Yes |
No |
Use case |
When you need all records |
When you need unique values |
Performance |
Faster |
Slightly slower (removes duplicates) |