Home CS61A: Lecture 32
Post
Cancel

CS61A: Lecture 32

SELECT statements

  • A SELECT statement specifies an input table using FROM [table]
    • SELECT [columns] FROM [table] WHERE [condition] ORDER BY [order];
    • SELECT [expression] AS [name], [expression] AS name;
    • We can optionally use [column] AS [name] to rename the input column in our new table.
    • Column descriptions determine how each input row is projected to a result row.
    • A subset of the rows can be selected (i.e. filtered) using WHERE [condition]
    • An ordering can be declared using ORDER BY [column]
  • To save the subset of the table we generate using select, we must concatenate the select statement to the CREATE TABLE [name] statement using AS.
    • CREATE TABLE [name] AS [SELECT statement]
  • To Generate a table by stupid brute force:
1
2
3
4
CREATE TABLE [name] AS
SELECT [value] AS [column name], [value] AS [column name] UNION
SELECT [VALUE], [value] UNION
SELECT [VALUE], [value];

Joining two tables

  • Tables A & B are joined by a comma (or JOIN) to form a new table of all the combinations of the rows of A with the rows of B
  • To format these new tables to reduce ambiguity (duplicate table names) we may assign an alias to each column name.
1
2
3
4
5
6
SELECT 
A.column1 as a_col1,
A.column2 as a_col2,
B.column1 as b_col1,
B.column2 as b_col2,
FROM A, B;

Adding to a table

  • We use the INSERT INTO statement to new rows into a table.
1
INSERT INTO [table name] VALUES ([value for col1], [value for col2])

Joining a table with itself

  • To join a table with itself, (to create combinations of our original data) we use aliases to distinguish between the same columns of the same table.
1
2
3
SELECT [alias1].[column] as [name1], [alias2].[column] as [name2],
FROM [table name] as [alias1], [table name] as [alias2],
WHERE [CONDITION]
1
SELECT parent from parents, dogs WHERE child = name AND fur = "curly"
  • Expressions may contain function calls and arithmetic operators
    • Combine valiues: +, -, *, /, %, and, or
    • Transformvalues: abs, round
    • Compare values: <, <=, >, >=, =
  • String avlues can be combined to form longer strings
This post is licensed under CC BY 4.0 by the author.

CS61A: Lecture 31

CS61A: Lecture 33