Select Clauses: Where
Select Clauses: Where
These are all the select clauses we've seen in the lesson so far.
where
The where clause expresses restrictions filtering a table for rows that follow a particular rule.
where supports equalities, inequalities, and boolean operators (among other things):
where species = 'gorilla' return only rows that have 'gorilla' as the value of the
species column.
where name >= 'George' return only rows where the name column is alphabetically
after 'George'.
where species != 'gorilla' and name != 'George' return only rows where species isn't
'gorilla' and name isn't 'George'.
limit / offset
The limit clause sets a limit on how many rows to return in the result table. The optional offset
clause says how far to skip ahead into the results. So limit 10 offset 100 will return 10 results
starting with the 101st.
order by
The order by clause tells the database how to sort the results usually according to one or
more columns. So order by species, name says to sort results first by the species column, then
by name within each species.
Ordering happens before limit/offset, so you can use them together to extract pages of
alphabetized results. (Think of the pages of a dictionary.)
The optional desc modifier tells the database to order results in descending order for instance
from large numbers to small ones, or from Z to A.
group by
The group by clause is only used with aggregations, such as max or sum. Without a group by
clause, a select statement with an aggregation will aggregate over the whole selected table(s),
returning only one row. With a group by clause, it will return one row for each distinct value of
the column or expression in the group by clause.
Insert: Adding Rows
The basic syntax for the insert statement:
insert into table ( column1, column2, ... ) values ( val1, val2, ... );
If the values are in the same order as the table's columns (starting with the first column), you
don't have to specify the columns in the insert statement:
For instance, if a table has three columns (a, b, c) and you want to insert into a and b, you can
leave off the column names from the insert statement. But if you want to insert into b and c, or a
and c, you have to specify the columns.
A single insert statement can only insert into a single table. (Contrast this with the select
statement, which can pull data from several tables using a join.)
Rules for normalized tables:
The example to keep in mind here is the diet table from the zoo database. Instead of trying to
stuff multiple foods for a species into a single row about that species, we separate them out. This
makes it much easier to do aggregations and comparisons.
2. There is a unique key and everything in a row says something about the key.
The key may be one column or more than one. It may even be the whole row, as in the diet table.
But we don't have duplicate rows in a table.