Simple select
- attribute : specifies a column in the result
- table_reference : the name of the table
- where_condition : the condition that selected rows must satisfy
Example
Select Distinct
To remove duplicate rows from the result, we can use SELECT DISTINCT
Where Clause
Logical connections AND
, OR
, NOT
can be used to create a more complex where condition
IS [NOT] NULL
Other Operations
Order by Clause
Order of rows in the result can be given by adding the ORDER BY CLAUSE
Example
Relational Product by an example
Joins
Inner Join
We want to show the ID, first name, last name, and department’s title for all employees.
Idea: DO the relational product and take only the rows where the employee’s department_id is equal to the department’s id
OR
Outer Join
Example
Table alias
If an attribute’s name is unique, the table reference can be dropped
Tables can be referenced by using aliases:
Create table
다음과 같은 예시를 참고해주면 된다.
추가적으로 primary key를 integer로 사용하는 편이 좋다. 이를 개선한 코드이다.
Reference options
Reference options
- Cascade : Deletes/update matching rows in the child tables too
- No action : Delete/update will fail if there are matching rows in the child tables
- Set null : Foreign key for matching rows in the child tables will be changed to NULL
INSERTING NEW DATA
Deleting and Modifying data
Removing and Modifying relations
Set Operations - Union
Set Operations - Intersection
Set Operations - Except
Aggregate functions
Aggregate functions, e.g. count(), sum(), avg(), min(), max(), can be used to calculate summary statistics based on rows selected by a WHERE clause
Grouping
We can divide selected rows into groups based on the value of one or several attributes and calculate summary statistics in each group.
Having clause
Nested Queries
Suppose we want to find an employees have the lowest hour salary.
Actually, these approach works. However, we can use a nested query which returns one value instead of hardcoded like above.
Similarly, instead of a list of constants, we can use a nested query which returns several values
Correlated Nested queries
A nested query can also use attributes from the tables used in the main outer query. Such queries are called correlated
or synchronized
Any and ALL
Exists
Exists
NOT EXISTS
Using the result of a nested query as a table
Views
A view is a named “virtual” table representing the result set of a given SELECT query.
The content of this virtual table is determined dynamically when such a query is executed