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

4.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)
6 views

4.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

expect, which is a task well suited to SELECT. Are dates in a proper format
complete with month, date, and year, or are they entered (as I once ruefully
observed) as text with the month and year only? Does every row have values
in all the columns? Are there mysteriously no last names starting with let-
ters beyond M? All these issues indicate potential hazards ranging from
missing data to shoddy record keeping somewhere in the workflow.
We’re only working with a table of six rows, but when you’re facing a
table of thousands or even millions of rows, it’s essential to get a quick read
on your data quality and the range of values it contains. To do this, let’s dig
deeper and add several SQL keywords.

NOTE pgAdmin allows you to drag and drop column names, table names, and other objects
from the object browser into the Query Tool. This can be helpful if you’re writing a
new query and don’t want to keep typing lengthy object names. Expand the object tree
to find your tables or columns, as you did in Chapter 1, and click and drag them into
the Query Tool.

Sorting Data with ORDER BY


Data can make more sense, and may reveal patterns more readily, when it’s
arranged in order rather than jumbled randomly.
In SQL, we order the results of a query using a clause containing the
keywords ORDER BY followed by the name of the column or columns to sort.
Applying this clause doesn’t change the original table, only the result of the
query. Listing 3-3 shows an example using the teachers table:

SELECT first_name, last_name, salary


FROM teachers
ORDER BY salary DESC;

Listing 3-3: Sorting a column with ORDER BY

By default, ORDER BY sorts values in ascending order, but here I sort in


descending order by adding the DESC keyword. (The optional ASC keyword
specifies sorting in ascending order.) Now, by ordering the salary column
from highest to lowest, I can determine which teachers earn the most:

first_name last_name salary


---------- --------- ------
Lee Reynolds 65000
Samuel Cole 43500
Betty Diaz 43500
Kathleen Roush 38500
Janet Smith 36200
Samantha Bush 36200

The ORDER BY clause also accepts numbers instead of column names,


with the number identifying the sort column according to its position in

4 Chapter 3

You might also like