SQL Flashcards
(38 cards)
Benefits of IN
IN executes faster than OR
Can contain another SELECT
NOT
WHERE NOT city = ‘London’ AND NOT city = ‘Dallas’
OR
WHERE name = ‘ali’ OR ‘mamad’
IN
WHERE id IN (9,10,11)
Wildcards
%
‘%Pizza’
‘Pizza%’
‘%Pizza%’
‘S%E’
WHERE size LIKE ‘%pizza’
ORDER BY position
Must always be the last clause in a select statement
Aggregate Functions
AVG() COUNT() MIN() MAX() SUM()
Count all the rows in a table containing values and NULL values
SELECT COUNT (*) AS total_cust FROM customers;
Count all the rows in a specific column ignoring NULL vales
SELECT COUNT (customerID) AS total_cust FROM customers;
DISTINCT on aggregate functions
SELECT COUNT(DISTINCT customerID) FROM customers
Every column in your SELECT statement must be present in a GROUP BY clause, except for
aggregated calculations
WHERE filters on rows, instead use … to filter for groups
HAVING
WHERE vs HAVING
WHERE filters before data is grouped
HAVING filters after data is grouped
Rows eliminated by the WHERE clause will not be included in the group
HAVING
SELECT customerID, COUNT() AS orders
FROM orders
GROUP BY customerID
HAVING COUNT ()>=2;
WHERE clause operators
= <> != >= > <= < BETWEEN AND IS NULL
Subquery selects can only retrieve a single column
.
Cartesian (Cross) join
Each row from the first table joins with all the rows of another table.
Output will be the number of joins in the 1st table multiplied by the number of rows in the 2ed table
Ex.
SELECT *
FROM table1 CROSS JOIN table2
inner joins
SELECT suppliers.CompanyName, ProductName, UnitPrice
FROM Suppliers INNER JOIN Products
ON Suppliers.supplierid = Products.supplierid
Inner join in multiple tables?
Yes, no limit
Inner join with multiple tables example
SELECT o.order_id, c.company_name ,e.last_name
FROM ((Orders o INNER JOIN Customers c ON o.customer_id = c.customer_id)
INNER JOIN Employees e ON o.employee_id = e.employee_id);
Aliases
/ˈālēəs/
SELECT vendor_name ,product_name, product_price
FROM Vendors AS v, Products as p
WHERE v.vendor_id = p.vendor_id;
Self Joins
SELECT
a.customer_name AS c_name1
,b.customer_name AS c_name2
a.city
FROM Customers AS a, Customers as b
WHERE a.customer_id = b.customer_id
AND a.city = b.city
ORDER BY a.city;
FULL OUTER JOIN
SELECT C.customer_name , O.order_id
FROM Customers AS C
FULL OUTER JOIN Orders AS O
ON C.customer_id = O.customer_id
ORDER BY C.customer_name;
Unions
A UNION is used to combine the result-set of multiple SELECT statements.
To create a union:
each SELECT statement must have the same number of columns
the columns in each SELECT statement must be in the same order
the matching columns must have similar data types