Files
eth-summaries/semester4/dmdb/parts/01_sql/03_query-language/00_intro.tex
T

38 lines
2.7 KiB
TeX

\subsection{Query Language}
The basic structure of a \sql\ statement is \texttt{SELECT I FROM T WHERE C},
which corresponds to $\Pi_{\texttt{I}}(\sigma_{\texttt{C}} \texttt{T})$.
We can set \texttt{I = *} if we want to return all columns for a table.
To rename, we can set \texttt{I = Column as Name, Column2 as Name2}, etc
\inlinetheorem Every SPJR \acrshort{ra} expression can be written in \texttt{SELECT ... FROM ... WHERE ...} form:
\begin{tables}{lll}{Operation & Notation & SQL}
Selection & $\sigma_c(R)$ & \texttt{SELECT * FROM R WHERE c;} \\
Projection & $\Pi_{A_1, \ldots, A_n} R$ & \texttt{SELECT A1, \ldots, An FROM R;} \\
Cartesian Product & $R_1 \times R_2$ & \texttt{SELECT * FROM (R1, R2);} \\
Rename & $\rho_{a, b, c} R$ & \texttt{SELECT A as a, \ldots, B as c FROM R;} \\
Union & $R_1 \cup R_2$ & \texttt{R1 UNION R2;} \\
Difference & $R_1 - R_2$ & \texttt{R1 EXCEPT R2;} \\
Intersection & $R_1 \cap R_2$ & \texttt{R1 INTERSECT R2;} \\
\end{tables}
Since \sql\ implements \gls{bag} and not set semantics, there is a \texttt{DISTINCT} keyword, which is used to remove duplicates.
It is to be applied in the \texttt{SELECT} clause (\texttt{I} above), e.g.
\mint{sql}|SELECT DISTINCT name FROM Data;|
For the last three operations, \texttt{R1} and \texttt{R2} typically are other \sql\ statements, example:
\mint{sql}|(SELECT name FROM FirstTable) UNION (SELECT name FROM SecondTable)|
In addition, to apply \textit{bag semantics}, as opposed to \textit{set semantics} append \texttt{ALL} to the expression (e.g. \texttt{UNION ALL})
We can also name the tables, e.g. $\texttt{T} = \texttt{One o, Two t}$, and then access columns from a specific table using
$\texttt{I} = \texttt{o.Col, b.Col}$, or the like.
String concatenation works using \texttt{CONCAT('string', 'string', 'string', ...)}, or using \texttt{'string' || 'string' || \dots}. Note that SQL uses single quote for Strings,
and double quotes for renaming columns (using \texttt{AS} statements, or in \texttt{SELECT})
Dates work as you'd expect. We can create a new date using \texttt{Date('ISO-date-string')}. \texttt{DATETIME} combines date and time and \texttt{TIME} is just the time.
To compute time delta, we can use \texttt{DATEDIFF('interval', DateOne, DateTwo)}, where the interval can be:
\texttt{year, quarter, month, dayofyear, day, week, weekday, hour, minute, second, millisecond}.
The current date, time, year, etc is provided using \texttt{current\_date} (etc).