Here are some examples of basic SQL queries based on the Monopoly database used in labs 7–9. You can run them in PostgreSQL.
The simplest SQL queries are those queries that reference only one table.
The first shows that the SELECT clause can carry expressions (e.g.,SELECT 1 + 1; SELECT * FROM Player;
1 + 1
) and
the second uses the *
, which returns
all fields in Player.
SQL syntax is not case sensitive (except for string constants).
Dates and time are represented as numbers that increase over time.SELECT * FROM Game ORDER BY time DESC;
cs262-code/lab07/monopoly.sql
) — the
resulting value in the database is NULL. Consider the following two
queries:
Do they return the same result or not? Be sure that you understand why this is.SELECT * FROM Player WHERE name IS NULL; SELECT * FROM Player WHERE name = NULL;
The wildcard character isSELECT * FROM Player WHERE emailAddress LIKE '%calvin%';
%
and the
string delimitation character is '
.
CURRENT_DATE
,
CURRENT_TIME
INTERVAL '2 months 3 days'
.
CURRENT_DATE - INTERVAL '2 months 3 days'
.
LIMIT is not supported by all SQL implementations.SELECT score FROM PlayerGame ORDER BY score DESC LIMIT 1;
Many useful queries require that we link two or more tables together. These multi-table queries are commonly called join queries. Here are some examples:
We need to join both Player and PlayerGame because Player has the name we’re focusing on (i.e., 'Dogbreath') and PlayerGame has the score we’re looking for. Note that the WHERE clause includes both a join condition (i.e.,SELECT score FROM Player, PlayerGame WHERE Player.ID = PlayerGame.playerID AND Player.name = 'Dogbreath';
Player.ID = PlayerGame.playerID
specifies
how to join the two tables) and a restricting condition (e.g.,
Player.name = 'Dogbreath'
restricts the output to only
Dogbreath’s entries).
This one has 2 join conditions and one restricting condition. The dot notation (i.e.,SELECT Player.name, score FROM Player, PlayerGame, Game WHERE Player.ID = PlayerGame.playerID AND PlayerGame.gameID = Game.ID AND Game.ID = 2;
Player.ID
) disambiguates the field
name ID
, which is used in two of the tables in the
query.
Figure out what this query is doing and why. What fields does it return? Why? How many records does it return? Why?SELECT * FROM Player, PlayerGame, Game;
You can join a table with itself, but you must use theSELECT P1.name FROM Player AS P1, Player AS P2 WHERE P1.name = P2.name AND P1.ID < P2.ID;
AS
clause to give unique names to the two instances of
the table you are joining (e.g., P1
and P2
in the example). You’ll have to add a new record to the Player
table with the same name as an existing record to get this to return
anything. Can you explain what the P1.ID < P2.ID
does in this example?