1
SQL Notes Powerful Websites: SQLZoo, Stackoverflow, SQLPuzzleArchives
Structured Query Language
- Used to query, insert, update, and modify data
- Communicative tool between user and data
- Reads, Writes, and Updates data
RELATIONAL DATABASE (RDB)
- Allows for querying & data manipulation in an easy, logical, and intuitive manner
Entity:
Person, Place, Thing, or Event
- Distinguishable
- Unique
- Distinct
Attribute:
A characteristic of an entity
Relationship:
Describes the association between entities
- 1 to 1
- 1 to Many
- Many to Many
2
ER (Entity Relationship) Model:
Composed of entity types and specifies the relationship that exists between instances of
those entity types
USER STUDIES COURSE
Entity 1 Entity 2
Relationship
FirstName
Attribute
LastName
Primary Key: Column(s) whose values uniquely identify every row in a table
(MUST have a value)
Foreign Key: One or more column(s) used together to identify a single row in another table
------------------------------------------------------------------------------------------------------
CREATING TABLES:
Label column(s); name and define them; define the datatype
NULL values: The absence of a value of an entity
NOT NULL values: The presence of a value for an entity
3
Statements and Clauses
SELECT Statement:
Foundational statement in SQL querying. Allows user to retrieve data from a database by
asking the question “What do you have for me?”
Example:
SELECT ProductID (“ProductID” is column name)
----------------------------------------------------------------------------------------------------
FROM Clause:
Clause used to specify which table SQL should retrieve data from
Example:
SELECT ProductID
FROM Products (“Products” is the table)
------------------------------------------------------------------------------------------------------
LIMIT Clause:
Allows user to limit the number of records (rows) returned from the query
Example:
SELECT ProductID
FROM Products
LIMIT 5; (5 is number of records (rows) returned)
------------------------------------------------------------------------------------------------------
4
WHERE Clause:
Allows users to specify which records (rows) are returned of the entity (column(s)) based
upon a condition set regarding one of the entities (column(s)) within the table selected
Example:
SELECT ProductID
FROM Products
WHERE BillingCity = ‘London’ Commented [LP1]: String datatypes need quotation
marks
------------------------------------------------------------------------------------------------------
ORDER BY Clause:
Allows users to sort data by particular column(s) by indicating to SQL which column it
should reference when sorting
- Can take multiple columns
- Add commas after each column
- Can sort by information NOT wanted
- Must always be last clause in a SELECT statement
- Can utilize operators like DESC & ASC
Example:
SELECT ProductID, CustomerID, BillingCity
FROM Products
WHERE BillingCity = ‘London’
ORDER BY ProductID DESC;
------------------------------------------------------------------------------------------------------
GROUP BY Clause:
Allows users to sort data when utilizing aggregate functions Commented [LP2]: Used to summarize data based
upon a specified order
- Can contain multiple columns
5
- Every column in SELECT statement can/may be present in a GROUP BY Clause
except the aggregate functions
- NULL Values will be grouped together if clause contains NULLs
- WHERE Clause cannot be utilized with GROUP BY clause b/c WHERE clause
operates on data before it is grouped
- Utilize the HAVING Clause instead
Example:
SELECT Product, SUM(Quantity) AS TotalQuantity Commented [LP3]: (AS TotalQuantity) is an alias given
to the aggregate function SUM(quantity) to clarify the new
FROM Orders column made from this query
GROUP BY TotalQuantity;
------------------------------------------------------------------------------------------------------
HAVING Clause:
Similar to WHERE Clause, except it is utilized with the GROUP BY clause to filter data
based on certain criteria after the data has been grouped
Example:
SELECT Product, SUM(Quantity) AS TotalQuantity
FROM Orders
GROUP BY TotalQuantity
HAVING TotalQuantity > 4;
------------------------------------------------------------------------------------------------------
JOINS
- Associate the correct records from multiple tables quickly
- Allow data retrieval from multiple tables in one query
- Are not physical (they persist for the duration of the query)
- No limit on the number of tables that can be joined
- List all the tables, then define the condition
6
This Photo by Unknown Author is licensed under CC BY-SA
Best Practices when utilizing JOINS
- Make sure you pre-qualify your JOINs using the “.”
- The type of JOIN is important
- How are you connecting the JOINs?
Cartesian (Cross) Join
- Allows user to join each row from first table with all the rows from another table
Example:
SELECT ProductName, UnitPrice, CompanyName
FROM Suppliers CROSS JOIN Products;
Output will be number of rows in 1st table multiplied by the number of rows in the 2nd table
------------------------------------------------------------------------------------------------------
INNER JOIN (One of the most frequently used JOINs)
Used to select records that have matching values in both tables
Example:
7
SELECT [Link], ProductName, UnitPrice Commented [LP4]: “suppliers.” indicates which table
you would like SQL to retrieve that column from when
FROM Suppliers INNER JOIN Products referencing multiple tables in a query.
ON [Link] = [Link] Commented [LP5]: Reference previous comment
This tells SQL to grab all the data from both tables, but only return the records that have
values based on the primary key indicated (productID) that is indicated using the ON
operator
Utilize “.” to prequalify a column from the table you want SQL to retrieve the data from
------------------------------------------------------------------------------------------------------
SELF JOIN
- Used to join an original table to itself
- Compares rows of the same table
- Assists in providing a hierarchy of data
Example:
Find all employees and their respective managers
SELECT [Link], [Link],
CONCAT ([Link], || “ ” || [Link]) AS ReportsTo Commented [LP6]: Reference page #9
FROM employees AS E1
INNER JOIN employees AS E2
ON [Link] = [Link]
ORDER BY ReportsTo;
- E1 and E2 are aliases allowing the user to distinguish between two instances of the
same table
- The query joins the employee table using the supervisorID and matching values to
the employeeID
------------------------------------------------------------------------------------------------------
LEFT JOIN
Returns all records from the left (1st) table and any matching results from the right (2nd)
table
8
Returns all NULL values
Example:
Return all the customers and any respective orders they might have placed
SELECT [Link], [Link]
FROM Customers AS Customers
LEFT JOIN Orders AS Orders
ON [Link] = [Link]
ORDER BY [Link];
- This query will return all specified columns from the Customers table and any
matching results from the Orders table based on the specified key of CustomerID
------------------------------------------------------------------------------------------------------
UNION:
Used to combine the result-set of two or more SELECT statements
Each statement must have:
o Same # of columns
o Similar data types
o Columns must be in the same order
Example:
SELECT City, Country
FROM Customers
WHERE Country = ‘Germany’
UNION
SELECT City, Country
FROM Suppliers
WHERE Country = ‘Germany’
Utilize this statement to represent the relationship between customers and suppliers in
different countries
9
CASE Statements
Working With String Variables
Retrieves the data in the format you need in the format required
Supports JOINs
String Functions:
- Concatenate (Link Together)
- Substring
- Trim
- Upper
- Lower
CONCAT:
Combines the first and last name from the employees table, E2, and gives it a new name,
which will return a new column with that alias as its name
Utilizes “||” to combine the entities
Example:
SELECT [Link], [Link],
CONCAT ([Link], || “ ” || [Link]) AS ReportsTo
FROM employees AS E1
INNER JOIN employees AS E2
ON [Link] = [Link]
ORDER BY ReportsTo;
------------------------------------------------------------------------------------------------------
TRIM
Trims the leading or trailing space from a string
- TRIM
- RTRIM
10
- LTRIM
SELECT TRIM (“…You the best…”)
AS TrimmedString;
------------------------------------------------------------------------------------------------------
SubString
Returns the specified number of characters from a particular position of a given string
Example format:
SUBSTR (string name, string position, # of characters to be returned);
Example:
SELECT first_name, SUBSTR (first_name,2,3)
FROM Employees
This will take the value in the first_name column, start from the 2nd letter, and return the
next 2 because you specified 3 characters
------------------------------------------------------------------------------------------------------
UPPER & LOWER
These will return the string in whichever specified case is requested
Example:
SELECT UPPER/LOWER(column_name)
FROM table_name
------------------------------------------------------------------------------------------------------
Date & Time Strings
Check which DBMS is utilized and review its date and time formats
11
DATE: YYYY-MM-DD
TIMESTAMP: HR:MI:SE
DATETIME: YYYY-MM-DD HR:MI:SE
------------------------------------------------------------------------------------------------------
CASE Staments
Mimics an IF-THEN-ELSE statement found in most programming languages
Utilzied in SELECT, INSERT, UPDATE, & DELETE Statements
CASE input_expression
WHEN when_expression THEN result_expression
ELSE else_result_expression
END name_of_new_column
------------------------------------------------------------------------------------------------------
Views:
A stored query
Add or remove column(s) without changing the schema
Used to encapsulate queries
Removed after the connection to the database has concluded
CREATE VIEW [IF NOT EXISTS]
View_name (column_name_list)
AS
SELECT_statement;
12