Advanced Syntax Flashcards
What time data can a TIME format hold?
TIME can only hold time information
What data can DATE hold?
DATE can only hold date information, no time
What information can the TIMESTAMP datatype hold?
TIMESTAMP can hold both date and time information
What information can the TIMESTAMPTZ datatype hold?
TIMESTAMPTZ can contain date, time and timezone information
What does the EXTRACT() function do?
- Allows you to extract or obtain a sub-component of a date value
- EXTRACT(YEAR FROM data_col)
What does the AGE() function do?
- Calculates and returns the current age given a timestamp
- Useage:
- AGE(date_col)
- Returns
- 13 years 1 mon 5 days 01:34:13.003423
What does the TO_CHAR() function do?
Lets you parse the datetime to a specific format. For example:
SELECT TO_CHAR(payment_date, ‘MM-YYYY’)
Documentation: https://www.postgresql.org/docs/12/functions-formatting.html
Can you use EXTRACT, AGE, TO_CHAR functions outside of SELECT?
Yes, they can be used to filter out results inside a WHERE clause for example
How can I concatenate strings inside a query?
SELECT first_name || ‘ ’ || last_name as full_name
FROM customer
Result:
Trevor Lahey
How can I uppercase strings inside a query?
SELECT upper(first_name)
What is a sub query?
- A sub query allows you to construct complex queries, essentially performing a query on the results of another query
- The syntax is straightforward and involves two SELECT statements
Example:
SELECT * FROM table
WHERE something > (SELECT somethingElse FROM table)
Given the following table named test_scores:
student,grade
How can I find all students that are better than average using a sub query?
SELECT student,grade
FROM test_scores
WHERE grade > (SELECT AVG(grade) FROM test_scores)
What gets executed first? The main query or the sub query?
The sub query
Can you add other tables using sub queries?
Yes, just like JOIN, sub queries can access data from other tables.
Example:
SELECT student,grade
FROM test_scores
WHERE student IN (SELECT student FROM honor_roll_table)
What operator do I need to use if the sub query results in multiple values?
IN operator