Lecture 24 SQL I
- Questions
- Declarative Programming
- You just tell it what to do, not really about how it is
- Relational Databases
- Each table is made up of columns and rows of data
- Tables
- Have rows and columns
- Columns have a name and a type of value
- Rows have values for each column
- SQL Overview
- select - either create a new table from scratch, or grab data from another table
- create table - gives a global name to a table
- Union - concatenates tables together to make bigger ones
- All statements in SQL must end with a semicolon
- Select Statements
- Select will return 0 or more rows that match our query (the computer will just do it for us)
- Return all rows of tables
- SELECT * FROM cities
- The * means get everything (in this case, every column)
- Renaming columns
- Select latitude as lat, longitude as lon FROM cities
- Manipulate the column value
- select city, longitude * 1000 as long_lon
- SQL Case-sensitive?
- Convention - capital letters from the keywords and lowercase for the rest
- Optional clauses for Select
- There are optional clauses for the select statement
- First Motivation: If
- Where keyword in SQL
- Lets you filter out rows
- SELECT * FROM menu WHERE price < 15;
- filtering out where price is less than 15
- SELECT item FROM menu WHERE price < 15:
- returns the name of items where the price is under 15
- Second Motivation: Sorting
- We can use the order by method
- ORDER by will let you specify the order of the rows
- When you are sorting, default is ascending
- Third Motivation: smaller output
- We might want to only see the top 3 items by price
- LIMIT clause limits the number of rows that are output
- Combining it together
- We can use WHERE, ORDER BY, and LIMIT being used by themselves
- SQL has a specific order from each keyword
- SELECT - FROM - WHERE - ORDER BY - LIMIT
- SQL Joins
- Combining Related Tables
- Usually better to keep tables relatively simple and join them together
- Storing everything in 1 table ends up taking far more space than storing them as two smaller tables
- Joining Tables
- We do complete join in CS61a
- Every row in table 1 is matched with every row from table 2 and all the columns are kept
- Joins
- Joining two tables together 3 columns, 50 rows and another table 5 columns, 3 rows
- 8 columns, 150 rows
- Problems with Joining
- A lot of rows that we create are useless
- This means that WHERE can filter out junk rows
- Column Names when Joining
- Sometimes, we have duplicate names
- Aliasing
- Basically renaming columns
2.