Menu

SQL SELECT, DISTINCT and Aliases Explained

SQL SELECT, DISTINCT and Aliases Explained

Every query you write for analysis starts with SELECT. It says which columns you want, and FROM says which table they live in. Think of it as asking a question of a spreadsheet: which columns, from which sheet.

Here is a small movies table we will query.

movie_id

title

genre

release_year

rating

1Silent HarborDrama20187.9
2Red MonsoonThriller20218.1
3Paper KitesDrama20197.4
4The Last SignalSci-Fi20228.4
5Neon StreetsThriller20207.7
6Quiet OrbitSci-Fi20238.0

Picking Columns and Renaming Them

SELECT * returns every column, which is handy for a quick look. For real work, name the columns you need. The query runs faster and the result is easier to read.

SELECT title AS movie, rating
FROM movies;

Output:

movie

rating

Silent Harbor7.9
Red Monsoon8.1
Paper Kites7.4
The Last Signal8.4
Neon Streets7.7
Quiet Orbit8.0

Code Explanation:

  • SELECT lists the two columns we want, and the other columns are left out.
  • AS movie is an alias. It renames the title column in the result set only; the table itself is not changed.
  • FROM movies tells the database where to read from.

Aliases are not limited to column names. They also label calculated values, such as rating * 10 AS score_out_of_100.

Removing Repeats with DISTINCT

Sometimes you want to know what values exist in a column, not how often they appear. DISTINCT returns each value once.

SELECT DISTINCT genre
FROM movies;

Output:

genre
Drama
Thriller
Sci-Fi

Code Explanation:

  • The table has six rows, but only three different genres.
  • DISTINCT collapses the repeats into one row per value.
  • The order of the rows is not guaranteed unless you sort them.

SQL for Data Science

AP

Abhishek Pati



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details