Curso de SQL
Curso de SQL
EXAMPLE:
SELECT ProductName
, UnitName
, SupplierName
FROM Products
WHERE ProductName = ‘Tofu’;
NOT clause
WHERE NOT City=’London’ AND NOT City= ‘Seattle’;
WILDCARDS:
SELECT ProductID
, UnitOnOrder
, UnitPrice
, UnitOnOrder * UnitPrice AS Total_Order_Cost
FROM Products
WHERE Solo filtra por filas mas no por grupos. Por lo que al Usar GROUP BY se
necesita the Having clause
SELECT
CustomerID
,Count (*) AS orders
FROM Orders
GROUP BY CustomerID
HAVING COUNT (*) >=2;
SUBQUERIES
Son incrustaciones de una segunda estructura (orden) dentro de otra. Sirve para
trabajar con varios recursos “tables” a la vez, pero solo pueden recuperar una
columna. Para filtrar.
COMBINED:
SELECT
Customer_ID
,companyName
,Region
FROM Customers
WHERE CustomerID in (SELECT customerI
FROM orders
WHERE freight >100);
SUBQUERY IN SUBQUERY
Escribirlas con sangría para poder leerlas mejor
SELECT
DISTINCT City
,(SELECT COUNT (DISTINCT CustomerId) AS number_of_customers
FROM customers a
WHERE a.City = b.City) AS number_of_customers
FROM customers b
ORDER BY City DESC;
SELECT Suppliers.CompnyName
,productName
,UnitPrice
FROM suppliers INNER JOIN products
ON suppliers.supplierid=
Products.supplierid
Aliases:
SELECT vendor_name
,product_name
,product_price
FROM Vendors AS v, products AS p
WHERE v. vendor_id= p. vendor_id;
SELF JOIN
Sirve para unir una tabla con ella misma como cuando uno quiere ver todos los
clientes que están en la misma ciudad.
SELECT A.CustomerName AS
CustomerName1, B.CustomerName AS
CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID= B.CustomerID
AND A.City=B.CustomerID
ORDER BY A.City;
LEFT JOIN:
Se usa cuando se quiere recuperar todos los datos de una de tablas además de lo
que este asociado
SELECT c. CustomerName, o.OrderID
FROM Customers C
LEFT JOIN Orders o ON c. customerID= o.customerID
ORDER BY c. CustomerName;
UNION JOINS
Se usan para cuando la información que se necesita junta ha sido recuperada por
aparte. Por lo que necesitan juntar todos los datos.
CREATING TABLES
MODIFIERS
Applied from left to right
NNN days
NNN hours
NNN minutes
NNN.NNNN seconds
NNN years
Start of month
Start of year
Start of day
Weekday N
Unixepoch
Localtime
Utc
STRFTIME: is a function used to extract certain parts of date and time string.
Example:
SELECT Birthdate
,STRFTIME (‘%Y’, Birthdate) AS Year
,STRFTIME (‘%M’, Birthdate) AS Month
,STRFTIME (‘%D’, Birthdate) AS Day
FROM employees
SELECT
FirstName
,LastName
,DATE(HireDate)
,DATE('NOW')
,DATE ('Now')-HireDate AS time_worked
FROM Employees
WHERE time_worked >=15
ORDER BY LastName ASC;
CASE STATEMENTS
It´s a built-in function that mimics if-then-else statement found in most
programming languages. It is used to classify data, transform variables, or recode
data, and start bin groupings for different statements.
It can be used in SELECT, INSERT, UPDATE, and DELETE statements.
CASE
WHEN C1 THEN E1
WHEN C2 THEN E2
…
ELSE [result else]
END [new column name]
SELECT City, Country FROM
Customers
WHERE country= ‘germany’
UNION
SELECT City, country FROM
Suppliers
WHERE Country= ‘Germany’
ORDER BY city;
CONCATENATIONS:
Used to bring together different text strings
Sql uses + instead of ||
SELECT
ContactName
,CompanyName || ‘ (‘|| ContactName||’)’
FROM customers
Trimming strings
TRIM, RTRIM (from the right), and LTRIM (from the left)
To trim the leading or trailing space from a string .
EX:
SELECT TRIM (“ You the best. ”) AS TrimmedString;
Substring
Allows you to pull apart just a portion of the string that you’re looking at. So, we can
shorten a name or create a password with this function. It is required the position
number of the characters within this query.
SUBSTR (String name, string position, number of characters to be returned);
SELECT
FirstName
,LastName
,LOWER (SUBSTR (FirstName,1,4)||SUBSTR(lastName,1,2))
FROM Employees;
EXMPLE:
SELECT
EmployeeId
,FirstName
,LastName
,City
CASE City
WHEN ‘Calgary’ THEN ‘Calgary’
ELSE ‘Other’
END Calgary
FROM Employees
ORDER BY LastName, FirstName;
VIEWS
it is a store query. it helps us create an illusion of a table.