Data Camp SQL
Data Camp SQL
WHERE
nerc_region and event_date You won't usually want to retrieve every row in
your database. You'll have specific information
SELECT you need in order to answer questions from your
TOP (20) description, boss or colleagues.
nerc_region,
event_date The WHERE clause is essential for selecting,
FROM updating (and deleting!) data from your tables.
grid You'll continue working with the grid dataset for
-- Order by nerc_region, affected_customers & this exercise.
event_date
-- Event_date should be in descending order -- Select description and event_year
ORDER BY SELECT
nerc_region, description,
affected_customers, event_year
event_date DESC; FROM
grid
-- Filter the results
WHERE
description = 'Vandalism';
SELECT
artist,
release_year,
song
FROM
songlist
-- Choose the correct artist and specify the
release year
WHERE
(
artist LIKE 'B%'
AND release_year = 1986
)
-- Or return all songs released after 1990
OR release_year > 1990
-- Order the results
ORDER BY
release_year,
artist,
song;
Aggregating Data
SUM – calculeaza suma unei coloane COUNT – insumeaza sau arata suma tuturor
Ex: randurilor dintr-o coloanal (numarul de
SELECT inregistrari)
SUM (affected_customers) AS total_affected EX:
SUM (demand_loss) AS dm_loss SELECT
FROM grid; COUNT (affected_customers) AS count_affected
Nu e necesar AS, dar ne ajuta sa denumin FROM grid;
capul de table
EX2:
SELECT
COUNT (DISTINCT affected_customers) AS
unique_count_affected
FROM grid;
EXEMPLUL 4
-- Find the minimum number of affected
customers
SELECT
MIN (affected_customers) AS
min_affected_customers
FROM
grid
-- Only retrieve rows where demand_loss_mw
has a value
WHERE
demand_loss_mw IS NOT NULL;
Strings
LEN (column) – dimensiunea in numar de caractere a unui string, incluzand spatiile
LEFT (coloanal, numar_caractere) – extragerea unui numar de caractere de la inceputul unui string in
fata
RIGHT (coloanal, numar_caracetere) – extragerea unui numar de caractere de la sfarsitul unui string in
spate
CHARINDEX (‘caracterul’, coloanal) - ne ajuta sa gasim un anume character dintr-un string, ‘’ necesare
SUBSTRING (coloanal, numarul caracterului de unde pornim, numarul de caractere pe care ne dorim sa-l
extragem) – extractia din mijlocul sirului
REPLACE (coloanal, caracterul care va fi schimbat, caracterul cu care-l vom schimba). EX:
SELECT
FROM courses;
EX. 1-- Calculate the length of the description EX 2.-- Select the first 25 characters from the left
column of the description column
SELECT SELECT
LEN(description) AS description_length LEFT(description, 25) AS first_25_left
FROM FROM
grid; Grid;
EX 3. -- Amend the query to select 25 characters EX. 4. You can use CHARINDEX to find a
from the right of the description column specific character or pattern within a column.
SELECT Edit the query to return the CHARINDEX of the
RIGHT(description, 25) AS last_25_right string 'Weather' whenever it appears within
FROM the description column.
grid; -- Complete the query to find `Weather` within
the description column
SELECT
description,
CHARINDEX('Weather', description)
FROM
grid
WHERE description LIKE '%Weather%';
EX. 5
HAVING e o alta conditie ca WHERE care se pune dupa GROUP BY. WHERE FILTERS ON ROW VALUES
.HAVING APPEARS AFTER THE GROUP BY CLAUSE AND FILTERS ON GROUPS OR AGGREGATES
EX.4 EX. 5
-- Obtain a count for each country SELECT
SELECT country,
COUNT(country) AS country_count, COUNT (country) AS country_count,
-- Retrieve the country column AVG (place) AS avg_place,
country, AVG (points) AS avg_points,
-- Return the average of the Place column MIN (points) AS min_points,
AVG(place) AS average_place, MAX (points) AS max_points
AVG(points) AS avg_points, FROM
MIN(points) AS min_points, eurovision
MAX(points) AS max_points GROUP BY
FROM country
eurovision -- The country column should only contain those
GROUP BY with a count greater than 5
country; HAVING
COUNT (country) > 5 – NU PUTEM ADAUGA
DIRECT country_count!!!
-- Arrange columns in the correct order
ORDER BY
avg_place ASC,
avg_points DESC;
Joining tables
We use Primary Key and Foreign Key to join tables
INNER JOIN – se poate aplica pe mai multe tabele si amesteca rezultatele cu cheile care exista in ambele
tabele
SELECT INNER JOIN SYNTAX
Album_id, SELECT
Title, Table_a.columnX,
album. Artist_id, Table_b.columnY,
name AS artist_name Table_c.columnZ
FROM album FROM table_A
INNER JOIN artist ON INNER JOIN table_B ON
artist.artist_id=album.artist_id table_B.foreign_key=table_A.primary_key
WHERE album.artist_id=1; INNER JOIN table_C ON
table_C.foreign_key=table_B.primary_key;
EX.1. SELECT EX.2-- Select album_id and title from album, and
track_id, name from artist
name AS track_name, SELECT
title AS album_title album_id,
FROM track title,
-- Complete the join type and the common name AS artist
joining column -- Enter the main source table name
INNER JOIN album on album.album_id = FROM artist
track.album_id; -- Perform the inner join
INNER JOIN album on album.artist_id =
artist.artist_id;
Qualify the name column by specifying the correct table prefix in both cases.
Complete both INNER JOIN clauses to join album with track,
and artist with album.
SELECT track_id,
-- Enter the correct table name prefix when retrieving the name column from the track table
track.name AS track_name,
title as album_title,
-- Enter the correct table name prefix when retrieving the name column from the artist table
artist.name AS artist_name
FROM track
-- Complete the matching columns to join album with track, and artist with album
RIGHT JOIN – toate liniile din tabelul din dreapta, matchuirile din tabelul din stanga si NULLS pentru non-
matches
DIFERENTELE MAJORE:
INNER JOIN – returneaza liniile matchuite din ambele tabele – INNER JOIN only ever return matching
rown from both tables
LEFT or RIGHT JOIN : returneaza toate liniile din tabelul principal plus matchurile din tabelul cu care s-a
facut join. All rows from the main tables plus matches from the joining table
LEFT JOIN SI RIGHT JOIN SUNT INTERSHIMBABILE. Putem rescrie un LEFT sau RIGHT si RIGHT to a LEFT
An INNER JOIN shows you exact matches. What about when you want to compare all the
values in one table with another, to see which rows match? That's when you can use a LEFT
JOIN.
SELECT
album.album_id,
title,
album.artist_id,
artist.name as artist
FROM album
INNER JOIN artist ON album.artist_id =
artist.artist_id
-- Perform the correct join type to return
matches or NULLS from the track table
RIGHT JOIN track on album.album_id =
track.album_id –inainte de ON punem tabelul
principal
WHERE album.album_id IN (213,214)
UNION & UNION ALL
- UNION ne ajuta sa combinam rezultatele prin doua queriuri dintr-un table sau din mai multe
tabele!
- UNION exclude duplicatele
EX1.-- Create the table EX2. Insert the track 'Basket Case', from the album 'Dookie', with a
track length of 3, into the appropriate columns.
CREATE TABLE tracks( -- Create the table
-- Create track column CREATE TABLE tracks( -- Create track column
track VARCHAR(200),
-- Create album column
track VARCHAR(200),
album VARCHAR(160),
-- Create album column
-- Create track_length_mins column
album VARCHAR(160),
track_length_mins INT -- Create track_length_mins column
); track_length_mins INT
-- Select all columns from the new table );
SELECT -- Complete the statement to enter the data to the
* table
FROM INSERT INTO tracks
tracks; -- Specify the destination columns
(track, album, track_length_mins)
-- Insert the appropriate values for track, album and
track length
VALUES
('Basket Case', 'Dookie', 3);
-- Select all columns from the new table
SELECT
*
FROM
tracks;
EX.3.-- Run the query EX.4-- Select the album
SELECT SELECT
title title
FROM FROM
album album
WHERE WHERE
album_id = 213; album_id = 213;
-- UPDATE the album table -- UPDATE the title of the album
UPDATE UPDATE
album album
-- SET the new title SET
SET title = 'Pure Cult: The Best Of The Cult'
title = 'Pure Cult: The Best Of The Cult' WHERE
WHERE album_id = 213; album_id = 213;
-- Run the query again
SELECT
title
FROM
album ;
You may not have permissions to delete from your database, but it is safe to practice it
here in this course!
Remember - there is no confirmation before deleting. When you execute the statement,
the record(s) are deleted immediately. Always ensure you test with
a SELECT and WHERE in a separate query to ensure you are selecting and deleting the
correct records. If you forget so specify a WHERE condition, you will delete ALL rows from
the table.