SQL Tutorial menu

SQL SELECT

The SELECT statement reads data from a table. It is the command you will use most.

SELECT Syntax

Example

sql
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

sql
SELECT name, city
FROM students;
namecity
Ali KhanKarachi
Ayesha SiddiquiLahore
Bilal AhmedKarachi
Fatima NoorIslamabad
Hamza RazaKarachi
Sana IqbalLahore

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

sql
SELECT * FROM courses;
idtitleduration_months
1Web Development6
2Python Programming4
3Graphic Designing3
4Digital Marketing3

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

sql
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

sql
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

sql
SELECT name AS student_name, marks AS score
FROM students;
student_namescore
Ali Khan78
Ayesha Siddiqui85
Bilal Ahmed64
Fatima Noor92
Hamza Raza70
Sana Iqbal88

Calculations in SELECT

You can calculate a new value for every row. Here every student gets 5 bonus marks, only in the result:

Example

sql
SELECT name, marks + 5 AS new_marks
FROM students;
namenew_marks
Ali Khan83
Ayesha Siddiqui90
Bilal Ahmed69
Fatima Noor97
Hamza Raza75
Sana Iqbal93

You can use +, -, * and / in this way.

Summary

You writeYou get
SELECT name FROM studentsOne column
SELECT name, age FROM studentsTwo columns
SELECT * FROM studentsAll columns
SELECT DISTINCT city FROM studentsEach city once
SELECT name AS student FROM studentsA renamed column

Exercise

Exercise

Which query returns each city only once?

Learn SQL with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp