SQL – an introduction to basic SELECT queries

a beautiful sight

SQL stands for Structured Query Language, which is a domain-specific language used for operating with data in a relational database system. As per its name, the most important function of SQL is to help users query the data they need in an efficient way.

This article is written with the intention to give readers an introduction to SQL with some of its most widely-used queries.

Table of content
SELECT … FROM …
WHERE …
ORDER BY …
LIMIT …
… AS …
SELECT DISTINCT … FROM …

For illustrative purposes, we will be using the Chinook database, which is a sample database we have when installing DBeaver (a GUI tool to deal with SQL). You may also obtain the database here.

Chinook's ERD
Chinook’s ERD

SELECT … FROM …

By using the SELECT (data) FROM (table) query, we ask the system to return the data we need from the specified table.

Example 1:

SELECT Name, ArtistId 
FROM  Artist;
NameArtistId
AC/DC1
Accept2
Aerosmith3
Alanis Morissette4
Alice In Chains5

Note that the result we show here is trimmed to save space (in fact, there are 275 rows outputted for this query).

Example 2:

We may also use SELECT *, which means select all columns.

SELECT *
FROM  Artist;
ArtistIdName
1AC/DC
2Accept
3Aerosmith
4Alanis Morissette
5Alice In Chains

Example 3:

Get some data from the table Track.

SELECT Name, AlbumId, GenreId, Milliseconds
FROM Track;
NameAlbumIdGenreIdMilliseconds
For Those About To Rock (We Salute You)11343719
Balls to the Wall21342562
Fast As a Shark31230619
Restless and Wild31252051
Princess of the Dawn31375418

WHERE …

The WHERE clause allows us to filter the returned rows by some conditions.

Example 1:

Let’s list all tracks in the album with id 4.

SELECT Name, AlbumId, GenreId, Milliseconds
FROM Track
WHERE AlbumId=4;
NameAlbumIdGenreIdMilliseconds
Go Down41331180
Dog Eat Dog41215196
Let There Be Rock41366654
Bad Boy Boogie41267728
Problem Child41325041
Overdose41369319
Hell Ain’t A Bad Place To Be41254380
Whole Lotta Rosie41323761

Example 2:

We can also state multiple conditions. The logic for more than 1 condition is:

  • AND: both conditions must be true.
  • OR: at least 1 of the conditions must be true.
  • XOR: only 1 of the 2 conditions is true while the other is false.

Let’s get the tracks composed by Jerry Cantrell whose duration is longer than 200 seconds. Note that as Jerry Cantrell is a string, we need to cover it with quotes ('')

SELECT Name, AlbumId, GenreId, Milliseconds
FROM Track
WHERE Composer='Jerry Cantrell'
  AND Milliseconds > 200000;
NameAlbumIdGenreIdMilliseconds
Sea Of Sorrow71349831
Bleed The Freak71241946
Sunshine71284969
I Know Somethin (Bout You)71261955

Example 3:

There is the keyword NOT that helps inverse the verdict appears after it.

We now collect the tracks composed by Jerry Cantrell, however, only those that are not longer than 200 seconds.

SELECT Name, AlbumId, GenreId, Milliseconds
FROM Track
WHERE Composer='Jerry Cantrell'
  AND NOT Milliseconds > 200000;
NameAlbumIdGenreIdMilliseconds
We Die Young71152084
Put You Down71196231

Of course, we can, instead, translate the second condition into that the duration has to be shorter than or equal to 200 seconds, as in the query below, which gives the same result.

SELECT Name, AlbumId, GenreId, Milliseconds
FROM Track
WHERE Composer='Jerry Cantrell'
  AND Milliseconds <= 200000;

ORDER BY …

When fetching the data, we may want to see the resulted rows in some specific order, in which case we should use the ORDER BY clause.

Example 1:

Get the list of employees, sorted by their birthdates.

SELECT EmployeeId, FirstName, LastName, BirthDate
FROM Employee
ORDER BY BirthDate;
EmployeeIdFirstNameLastNameBirthDate
4MargaretPark1947-09-19 00:00:00
2NancyEdwards1958-12-08 00:00:00
1AndrewAdams1962-02-18 00:00:00
5SteveJohnson1965-03-03 00:00:00
8LauraCallahan1968-01-09 00:00:00
7RobertKing1970-05-29 00:00:00
6MichaelMitchell1973-07-01 00:00:00
3JanePeacock1973-08-29 00:00:00

Example 2:

By default, the system will order the result in increasing order (from small to large). If we want to reverse to decreasing order, just add DESC at the end of the command.

For example, let’s get the invoice list, the records with the highest total values go first.

SELECT InvoiceId, CustomerId, Total
FROM Invoice
ORDER BY Total DESC;
InvoiceIdCustomerIdTotal
404625.86
2992623.86
964521.86
1944621.86
89718.86
2012518.86
885717.91
306516.86
3134316.86
1032415.86

Note that the result is trimmed to save space (there are 412 invoices in totals).

LIMIT …

Here we describe a formal method to limit the number of rows returned by the system. Sometimes, when the database is big, our queries may result in thousands or even millions of rows, which pushes pressure on the transfer-bandwidth and memory. In those cases, put a LIMIT clause at the end of the query may help solve the issue.

Example 1:

Let’s execute the above query with a LIMIT.

SELECT InvoiceId, CustomerId, Total
FROM Invoice
ORDER BY Total DESC
LIMIT 5;
InvoiceIdCustomerIdTotal
404625.86
2992623.86
964521.86
1944621.86
89718.86

Example 2:

If we place LIMIT 1 after an ORDER BY, we will get the result with a minimum value (or maximum if we use ORDER BY ... DESC).

For instance, over the tracks whose unit price is less than 1, get the one that has the longest duration.

SELECT TrackId, Name, UnitPrice, Milliseconds
FROM Track
WHERE UnitPrice < 1
ORDER BY Milliseconds DESC
LIMIT 1;
TrackIdNameUnitPriceMilliseconds
1666Dazed And Confused0.991612329

Example 3:

What if we want to get some rows in the middle of the result? The accompany of OFFSET may make that feasible. When we use LIMIT n OFFSET i, we command the system to skip i first rows and return the next n rows. See how the below output is different from in example 1:

SELECT InvoiceId, CustomerId, Total
FROM Invoice
ORDER BY Total DESC
LIMIT 5 OFFSET 2;
InvoiceIdCustomerIdTotal
964521.86
1944621.86
89718.86
2012518.86
885717.91

… AS …

The alias is another name we give to a column or a table, denoted by the AS term. Note that this is just an alternative name for an existing object (column or table), we do NOT create a new object.

Example 1:

Get the list of tracks jointly composed by Angus Young, Malcolm Young, and Brian Johnson. Rename the column Milliseconds so that it is more clear, like Duration in milliseconds.

SELECT Name, Composer, Milliseconds AS 'Duration in milliseconds'
FROM Track
WHERE Composer='Angus Young, Malcolm Young, Brian Johnson';
NameComposerDuration in milliseconds
For Those About To Rock (We Salute You)Angus Young, Malcolm Young, Brian Johnson343719
Put The Finger On YouAngus Young, Malcolm Young, Brian Johnson205662
Let’s Get It UpAngus Young, Malcolm Young, Brian Johnson233926
Inject The VenomAngus Young, Malcolm Young, Brian Johnson210834
SnowballedAngus Young, Malcolm Young, Brian Johnson203102
Evil WalksAngus Young, Malcolm Young, Brian Johnson263497
C.O.D.Angus Young, Malcolm Young, Brian Johnson199836
Breaking The RulesAngus Young, Malcolm Young, Brian Johnson263288
Night Of The Long KnivesAngus Young, Malcolm Young, Brian Johnson205688
SpellboundAngus Young, Malcolm Young, Brian Johnson270863

SELECT DISTINCT … FROM …

SELECT DISTINCT is similar to SELECT except for the fact that the returned rows are non-duplicated. That says, only 1 of the duplicated rows is kept, while the others are removed.

Example 1:

Let’s compare the results taken from using SELECT and SELECT DISTINCT in the below queries.

SELECT

SELECT UnitPrice
FROM Track;
UnitPrice
0.99
0.99
0.99
1.99
1.99
1.99

There are 3503 rows in total.

SELECT DISTINCT

SELECT DISTINCT UnitPrice
FROM Track;
UnitPrice
0.99
1.99

There are 2 rows in total.

Conclusion

In summary, in this article, we have covered:

SELECT … FROM …Query which data from which table
WHERE …Conditions for selection
=, !=, <>, >, <, >=, <=Comparison operators
AND, OR, XORCombination logic for multiple conditions
NOTReverse the verdict of a condition
ORDER BY … (DESC)Sort the outputted rows
LIMIT …The maximum number of rows returned
… AS …Set another name (alias) for a table or column
SELECT DISTINCT … FROM …Select only the unique rows

References:

  • Wiki’s page about SQL: link
  • W3schools’s SQL: link
  • Sqlzoo’s tutorial: link
  • An introduction to Chinook by sqlitetutorial: link

Leave a Reply