SQL SELECT
The SELECT statement reads data from a table. It is the command you will use most.
SELECT Syntax
Example
SELECT column1, column2
FROM table_name;You list the columns you want after SELECT, and the table after FROM. The answer comes back as a new table, called the result set.
Select Some Columns
This query returns only the name and the city of each student:
Example
SELECT name, city
FROM students;| name | city |
|---|---|
| Ali Khan | Karachi |
| Ayesha Siddiqui | Lahore |
| Bilal Ahmed | Karachi |
| Fatima Noor | Islamabad |
| Hamza Raza | Karachi |
| Sana Iqbal | Lahore |
The columns come back in the order you wrote them, not the order in the table.
Select All Columns
Use * to get every column:
Example
SELECT * FROM courses;| id | title | duration_months |
|---|---|---|
| 1 | Web Development | 6 |
| 2 | Python Programming | 4 |
| 3 | Graphic Designing | 3 |
| 4 | Digital Marketing | 3 |
SELECT * is handy for a quick look. In a real app, list only the columns you need. It is faster and the code still works if someone adds new columns later.
SELECT DISTINCT
A column often has the same value many times. DISTINCT returns each value only once:
Example
SELECT DISTINCT city
FROM students;| city |
|---|
| Karachi |
| Lahore |
| Islamabad |
Six students live in only three different cities. You can also count the different values:
Example
SELECT COUNT(DISTINCT city)
FROM students;| COUNT(DISTINCT city) |
|---|
| 3 |
Rename a Column with AS
An alias gives a column a new name in the result. It does not change the table itself.
Example
SELECT name AS student_name, marks AS score
FROM students;| student_name | score |
|---|---|
| Ali Khan | 78 |
| Ayesha Siddiqui | 85 |
| Bilal Ahmed | 64 |
| Fatima Noor | 92 |
| Hamza Raza | 70 |
| Sana Iqbal | 88 |
Calculations in SELECT
You can calculate a new value for every row. Here every student gets 5 bonus marks, only in the result:
Example
SELECT name, marks + 5 AS new_marks
FROM students;| name | new_marks |
|---|---|
| Ali Khan | 83 |
| Ayesha Siddiqui | 90 |
| Bilal Ahmed | 69 |
| Fatima Noor | 97 |
| Hamza Raza | 75 |
| Sana Iqbal | 93 |
You can use +, -, * and / in this way.
Summary
| You write | You get |
|---|---|
SELECT name FROM students | One column |
SELECT name, age FROM students | Two columns |
SELECT * FROM students | All columns |
SELECT DISTINCT city FROM students | Each city once |
SELECT name AS student FROM students | A renamed column |
Exercise
Exercise
Which query returns each city only once?
