Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Learn SQL Course

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 7

SQL

SELECT * FROM celebs;


#presenta la tabla celebs

CREATE TABLE table_name ( column_1 data_type, column_2 data_type, column_3


data_type);

CREATE TABLE #es una clausula y cumplen funciones especificas, por convencion se
escribe en mayusculas
table_name #refers to the name of the table that the comand is applied to
(column_1 data_type, column_2 data_type, column_3 data_type) #is a parameter. A
parameter is a list of columns, data types, or values that are passed to a clause
as an argument

CREATE TABLE celebs (


id INTEGER,
name TEXT,
age INTEGER
);
#id is the first column in the table. It stores values of data type INTEGER
#name is the second column in the table. It stores values of data type TEXT
#age is the third column in the table. It stores values of data type INTEGER

INSERT INTO celebs (id, name, age)


VALUES (1, 'Justin Bieber', 22);
INSERT INTO celebs (id, name, age)
VALUES (2, 'Beyonce Knowles', 33);
INSERT INTO celebs (id, name, age)
VALUES (3, 'Jeremy Lin',26);
INSERT INTO celebs (id, name, age)
VALUES (4, 'Taylor Swift', 26);

SELECT name FROM celebs;


#name is a column of the celebs table

Alter
ALTER TABLE statement adds a new column to a table.
ALTER TABLE celebs
ADD COLUMN twitter_handle TEXT; # is the data type for the new column
SELECT * FROM celebs;
NULL # is a special value in SQL that represent missing or unknown data. In this
case column was added have NULL (∅) values for twitter_handle.

Update #statement edits a row in a table. You can use the UPDATE statement when you
want to change existing records.
UPDATE celebs
SET twitter_handle = '@taylorswift13'
WHERE id = 4;

SELECT * FROM celebs;

Delete # DELETE FROM statement deletes one or more rows from a table.
DELETE FROM celebs
WHERE twitter_handle IS NULL;

SELECT * FROM celebs;


# en este caso elimina todos en donde twitter_handle is NULL, dejando
solamente Taylor Swift que fue agregada anteriormente.
Constraints # that add information about how a column can be used are invoked after
specifying the data type for a column. They can be used to tell the database to
reject inserted data that does not adhere to a certain restriction
CREATE TABLE awards (
id INTEGER PRIMARY KEY,
recipient TEXT NOT NULL,
award_name TEXT DEFAULT
'Grammy'
);

PRIMARY KEY columns can be used to uniquely identify the row. Attempts to
insert a row with an identical value to a row already in the table will result in a
constraint violation which will not allow you to insert the new row.
UNIQUE columns have a different value for every row. This is similar to
PRIMARY KEY except a table can have many different UNIQUE columns.
NOT NULL columns must have a value. Attempts to insert a row without a value
for a NOT NULL column will result in a constraint violation and the new row will
not be inserted.
DEFAULT columns take an additional argument that will be the assumed value
for an inserted row if the new row does not specify a value for that column.

Review
CREATE TABLE creates a new table.
INSERT INTO adds a new row to a table.
SELECT queries data from a table.
ALTER TABLE changes an existing table.
UPDATE edits a row in a table.
DELETE FROM deletes rows from a table.

Queries

Select
SELECT column1, column2 FROM table_name;
SELECT name, genre, year FROM movies;
# con esto se consulta en la consola el nombre, el genero y el año de las movies

As # is a keyword in SQL that allows you to rename a column or table using an


alias

SELECT imdb_rating AS 'IMDb' FROM movies;

Distinct # regresa el valor unico de salida, flitra todos los valores duplicados in
una columna(s) especifica
SELECT DISTINCT genre FROM movies;
#retorna cada uno de los generos que se tiene como (accion, comedia, romance,
etc)

Where # clause in order to obtain only the information we want.


SELECT * FROM movies WHERE year > 2014;
#con esto solo mostramos las movies mayores al 2014, solo sigue la condicion
si es verdadera y el operador solo puede ser evaluados con verdadero o falso

Like I #can be a useful operator when you want to compare similar values
SELECT * FROM movies WHERE name LIKE 'Se_en';
# Se_en represents a pattern with a wildcard character
#The _ means you can substitute any individual character here without reaking
the pattern
Like II # The percentage sign % is another wildcard character that can be used with
LIKE.

SELECT * FROM MOVIES WHERE name LIKE '%man%; # cuantos titulos de movies
tienen la palabra 'man'
A% matches all movies with names that begin with letter ‘A’ # si quiere
comprobar The se usa un espacio 'The %'
%a matches all movies that end with 'a’

Is Null #los valores desconocidos son indicados por NULL


SELECT name FROM movies WHERE imdb_rating IS NULL; #muestra solo las
movies que IMDBb is NULL

Between # is used in a WHERE clause to filtr the result set within a certain range.
Example WHERE year BETWEEN 1990 AND 1999. Inclusive filters the result set for
within the alphabetical range WHERE name BETWEEN 'A' AND 'J'; t hat begin with the
letter ‘A’ up to, but not including ones that begin with ‘J’.

SELECT * FROM movies WHERE name BETWEEN 'D ' AND 'G'; #name begins with the
letter 'D', 'E' and 'F'
SELECT * FROM movies WHERE year BETWEEN 1970 AND 1979;

AND # used to combine multiple conditions in a WHERE clause to make the result set
more specific and useful

SELECT * FROM movies WHERE year BETWEEN 1970 AND 1979 AND imdb_rating > 8;
SELECT * FROM movies WHERE year < 1985 AND genre = 'horror';

OR #operator displays a row if any condition is true

SELECT *FROM movies WHERE year > 2014 OR genre = 'action';


SELECT * FROM movies WHERE genre = 'romance' OR genre = 'comedy';

Order By # Ordenar por


SELECT name, year FROM movies ORDER BY name;
SELECT name, year, imdb_rating FROM movies ORDER BY imdb_rating DESC #ASC =
ascendente; DESC = descendente

Limit # is a clause that lets you specify the maximum number of rows the result set
will have.
SELECT * FROM movies ORDER BY imdb_rating DESC LIMIT 3; # con esto se limita
a las mejores tres peliculas calificadas, seleccionando todas las columnas

Case # nos permite crear diferentes outputs (if, if, else)


SELECT name,
CASE
WHEN genre = 'romance' THEN 'Chill'
WHEN genre = 'comedy' THEN 'Chill'
ELSE 'Intense'
END AS 'Mood'
FROM movies;
# muestra el nombre y el mood que tiene la pelicula, el THEN nombra la
pelicula en la nueva categoria Mood

REVIEW Initial
SELECT is the clause we use every time we want to query information from a
database.
AS renames a column or table.
DISTINCT return unique values.
WHERE is a popular command that lets you filter the results of the query
based on conditions that you specify.
LIKE and BETWEEN are special operators.
AND and OR combines multiple conditions.
ORDER BY sorts the result.
LIMIT specifies the maximum number of rows that the query will return.
CASE creates different outputs.

Aggregate Functions
COUNT(): count the number of rows # SELECT COUNT(column_name) FROM
table_name;
SUM(): the sum of the values in a column #SELECT SUM(column_name) FROM
table_name;
MAX()/MIN(): the largest/smallest value # SELECT MAX/MIN(column_name) FROM
table_name;
AVG(): the average of the values in a column # SELECT AVG(column_name) FROM
table_name;
ROUND(): round the values in the column # SELECT names,
ROUND(AVG(test_scores), 2) AS semester_avg FROM grades GROUP BY names;
#ROUND(value, decimal_places)

Count
SELECT COUNT (*) FROM fake_apps; # count how many apps are in the table
SELECT COUNT (*) FROM fake_apps WHERE price = 0; # count how many free apps
are in the table
Sum
SELECT SUM(downloads) FROM fake_apps;

Min
SELECT MIN(downloads) FROM fake_apps;

Max
SELECT MAX(price) FROM fake_apps;

Average
SELECT AVG(downloads) FROM fake_apps;
Round
SELECT name, ROUND(price, 0) FROM fake_apps;
SELECT ROUND(AVG(price), 2) FROM fake_apps; #we were able to get the
average price of an app ($2.02365) using this query

Group By I # GROUP BY is a clause in SQL that is used with aggregate functions. It


is used in collaboration with the SELECT statement to arrange identical data into
groups. # GROUP BY statement comes after any WHERE statements, but before ORDER BY
or LIMIT.

SELECT price, COUNT(*) FROM fake_apps GROUP BY price;

Multiple Tables
SELECT * FROM orders LIMIT 5; # order would contain just the information
necessary to describe what was ordered: order_id, customer_id, subscription_id,
purchase_date

SELECT * FROM subscriptions LIMIT 5; #subscription_id, description,


price_per_month, subscription_length

SELECT * FROM customers LIMIT 5; #customer_id, customer_name, address

Combining Tables Manually


orders; subscriptions; customers

Combining Tables with SQL


# If we want to combine orders and costumers
SELECT * FROM orders JOIN customers
ON orders.customer_id = customers.customer_id;

# Instructions
1 # Join orders table and subscriptions table and select all columns. Make
sure to join on the subscription_id column.
2 # Don't remove the previous query. Add a second query after your first
one that only select rows from the join where description is equal to 'Fashion
Magazine'.
-- First query
SELECT * FROM orders JOIN subscriptions
ON orders.subscription_id = subscriptions.subscription_id;

-- Second query
SELECT * FROM orders JOIN subscriptions
ON orders.subscription_id = subscriptions.subscription_id
WHERE subscriptions.description = 'Fashion Magazine';

Inner Joins # when we perform a simple JOIN (often called an inner join-union
interna) our result only includes rows that match our ON condition.

Instructions
1 # Suppose we are working for The Codecademy Times, a newspaper with two
types of subscriptions: print newspaper, online articles. Some users subscribe to
just the newspaper, some subscribe to just the online edition, and some subscribe
to both. There is a newspaper table that contains information about the newspaper
subscribers. Count the number of subscribers who get a print newspaper using
COUNT().

2 # Don't remove your previous query. There is also an online table that
contains information about the online subscribers. Count the number of subscribers
who get an online newspaper using COUNT().

3 # Joins newspaper table and online table on their id columns (the unique ID
of the subscriber). How many rows are in this table?

SELECT COUNT(*) FROM newspaper;


SELECT COUNT(*) FROM online;
SELECT COUNT(*) FROM newspaper
JOIN online
ON newspaper.id = online.id;

Left Joins # A left join will keep all rows from the first table, regardless of
whether there is a matching row in the second table.
SELECT * FROM table1 LEFT JOIN table2 ON table1.c2 = table2.c2;

Example
SELECT * FROM newspaper
LEFT JOIN online
ON newspaper.id = online.id;
SELECT * FROM newspaper
LEFT JOIN online
On newspaper.id = online.id;

Primary Key vs Foreign Key


SELECT * FROM classes
JOIN students
ON classes.id = students.class_id;
#las claves primarias 1. Ninguno de los valores puede ser NULL. 2. Cada valor
debe ser unico (es decir, no puede haber dos clientes con el mismo customer_id en
la customers tabla). 3. Una tabla no puede tener mas de una columna de clave
principal Siendo customer_id(la clave principal para customers)
# cuando la clave principal de una tabla aparece en una tabla diferenete, se
denomina Foreing Key

Cross Join
SELECT shirts.shirt_color, pants.pants_color
FROM shirts
CROSS JOIN pants;

Suppose we wanted to know how many users were subscribed during each month of
the year. For each month of the year. For each month (1, 2, 3) we would need to
know if a user was subscribed. Follow the steps below to see how we can use a CROSS
JOIN to solved this problem.
1# Let’s start by counting the number of customers who were subscribed to the
newspaper during March.
Use COUNT(*) to count the number of rows and a WHERE clause to restrict to
two conditions: start_month <= 3
end_month >= 3
2# The previous query lets us investigate one month at a time. In order to
check across all months, we’re going to need to use a cross join. Our database
contains another table called months which contains the numbers between 1 and 12.
Select all columns from the cross join of newspaper and months.
3# Create a third query where you add a WHERE statement to your cross join to
restrict to two conditions: start_month <= month end_month >= month. This will
select all months where a user was subscribed.
4# Create a final query where you aggregate over each month to count the
number of subscribers.

-First query
SELECT COUNT(*)
FROM newspaper
WHERE start_month <= 3
AND end_month >= 3;
-Second query
SELECT *
FROM newspaper
CROSS JOIN months;
- Third query
SELECT *
FROM newspaper
CROSS JOIN months
WHERE start_month <= month
AND end_month >= month;
- Fourth query
SELECT month,
COUNT (*)
FROM newspaper
CROSS JOIN months
WHERE start_month <= month
AND end_month >= month
GROUP BY month;

UNION
Sometimes we just want to stack one dataset on top of the other. Well, the UNION
operator allows us to do that. 1# Tables must have the same number of columns. 2#
The columns must have the same data types in the same order as the first table.

EXERCISE
Let’s return to our newspaper and online subscriptions. We’d like to
create one big table with both sets of data. Use UNION to stack the newspaper table
on top of the online table.
SELECT *
FROM newspaper
UNION
SELECT *
FROM online;
WITH
Essentially, we are putting a whole first query inside the parentheses () and
giving it a name. After that, we can use this name as if it’s a table and write a
new query using the first query.
WITH previous_query AS( SELECT customer_id,
SELECT customer_id,
COUNT(subscription_id) AS
'subscriptions'
FROM orders
GROUP by customer_id
)
SELECT customers.customer_name,
previous_query.subscriptions
FROM previous_query
JOIN customers
ON previous_query.customer_id = customers.customer_id;

Review Multiple Tables

JOIN will: combine rows from different tables if the join condition is true.
LEFT JOIN: will return every row in the left table, and if th join condition
is not met, NULL values are used to fill in the columns from the right table.
PRIMARY KEY: is a column that serves a unique identifier for the rows in the
table.
FOREING KEY: is a column that contains the primary key to another table.
CROSS JOIN: lets us combine all rows of one table with all rows of another
table.
UNION: stacks one dataset on top of another.
WITH: allows us to define one or more temporary tables that can be used in
the final query.

You might also like