0% found this document useful (0 votes)
2 views

5.PracticalSQL2E_SampleCh3 - Copy

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

5.PracticalSQL2E_SampleCh3 - Copy

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Practical SQL 2e (Sample Chapter) © 2021 by Anthony DeBarros

the SELECT clause. Thus, you could rewrite Listing 3-3 this way, using 3 to
refer to the third column in the SELECT clause, salary:

SELECT first_name, last_name, salary


FROM teachers
ORDER BY 3 DESC;

The ability to sort in our queries gives us great flexibility in how we view
and present data. For example, we’re not limited to sorting on just one col-
umn. Enter the statement in Listing 3-4:

SELECT last_name, school, hire_date


FROM teachers
1 ORDER BY school ASC, hire_date DESC;

Listing 3-4: Sorting multiple columns with ORDER BY

In this case, we’re retrieving the last names of teachers, their school,
and the date they were hired. By sorting the school column in ascending
order and hire_date in descending order 1, we create a listing of teachers
grouped by school with the most recently hired teachers listed first. This
shows us who the newest teachers are at each school. The result set should
look like this:

last_name school hire_date


--------- ------------------- ----------
Smith F.D. Roosevelt HS 2011-10-30
Roush F.D. Roosevelt HS 2010-10-22
Reynolds F.D. Roosevelt HS 1993-05-22
Bush Myers Middle School 2011-10-30
Diaz Myers Middle School 2005-08-30
Cole Myers Middle School 2005-08-01

You can use ORDER BY on more than two columns, but you’ll soon reach
a point of diminishing returns where the effect will be hardly noticeable.
Imagine if you added columns about teachers’ highest college degree
attained, the grade level taught, and birthdate to the ORDER BY clause. It
would be difficult to understand the various sort directions in the output
all at once, much less communicate that to others. Digesting data happens
most easily when the result focuses on answering a specific question; there-
fore, a better strategy is to limit the number of columns in your query to
only the most important and then run several queries to answer each ques-
tion you have.

Using DISTINCT to Find Unique Values


In a table, it’s not unusual for a column to contain rows with duplicate
values. In the teachers table, for example, the school column lists the same
school names multiple times because each school employs many teachers.

Beginning Data Exploration with SELECT 5

You might also like