You are on page 1of 18

1.-- Select the top 20 rows from description, 2.

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';

When filtering strings, you need to wrap your


value in 'single quotes', as you did in the previous
exercise. You don't need to do this for numeric
values, but you DO need to use single quotes for
date columns.

In this course, dates are always represented in


the YYYY-MM-DD format (Year-Month-Day),
which is the default in Microsoft SQL Server.

3. -- Select description and affected customers 4. -- Select description, affected_customers and


SELECT event date
description, SELECT
affected_customers description,
FROM affected_customers,
grid event_date
-- Retrieve rows where the event_date was the FROM
22nd December, 2013 grid
WHERE -- The affected_customers column should be >=
event_date = '2013-12-22'; 50000 and <=150000
WHERE
affected_customers BETWEEN 50000
AND 150000
-- Define the order
ORDER BY
event_date DESC;
5. -- Retrieve all columns 6. -- Retrieve the song, artist and release_year
SELECT columns
* SELECT
FROM song,
grid artist,
-- Return only rows where demand_loss_mw is release_year
missing or unknown FROM
WHERE songlist
demand_loss_mw IS NULL; -- Ensure there are no missing or unknown
values in the release_year column
WHERE
release_year IS NOT NULL;

7.-- Retrieve the song,artist and release_year 8.SELECT


columns song,
SELECT artist,
song, release_year
artist, FROM
release_year songlist
FROM WHERE
songlist -- Retrieve records greater than and including
-- Ensure there are no missing or unknown 1980
values in the release_year column release_year >= 1980
WHERE -- Replace AND with OR
release_year IS NOT NULL OR release_year <= 1990 --OR IN LOC DE AND
-- Arrange the results by the artist and ORDER BY
release_year columns artist,
ORDER BY release_year;
artist,
release_year;
9.Select all artists beginning with B who released
tracks in 1986, but also retrieve any records
where the release_year is greater than 1990.

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;

MIN – calculeaza minimul (incercam sa evitam 0) AVG – calculeaza media pe coloanal


EX: SELECT
MIN(affected_customers) AS EXEMPLUL 1
min_affected_customers -- Sum the demand_loss_mw column
FROM grid SELECT
WHERE affected_customers >0; SUM (demand_loss_mw) AS MRO_demand_loss
FROM
grid
WHERE
-- demand_loss_mw should not contain NULL
values
demand_loss_mw IS NOT NULL
-- and nerc_region should be 'MRO';
AND nerc_region = 'MRO';
EXEMPLUL 2 EXEMPLUL 3
-- Obtain a count of 'grid_id'
-- Obtain a count of 'grid_id' SELECT
SELECT COUNT(grid_id) AS RFC_count
COUNT (grid_id) AS grid_total FROM
FROM grid
grid; -- Restrict to rows where the nerc_region is 'RFC'
WHERE
nerc_region = 'RFC';

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

TOP (5) REPLACE (url,’_’,’_’) AS replace_with_hyphen

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

Now we use SUBSTRING to return everything


after Weather for the first ten rows. The start
index here is 15, because the CHARINDEX for
each row is 8, and the LEN of Weather is 7.
-- Complete the substring function to begin
extracting from the correct character in the
description column

SELECT TOP (10)


description,
CHARINDEX('Weather', description) AS
start_of_string,
LEN ('Weather') AS length_of_string,
SUBSTRING(
description,
15,
LEN(description)
) AS additional_description
FROM
grid
WHERE description LIKE '%Weather%';
Grouping and Having
Utilizand GROUP BY clause, care imparte datele in grupe in functie de valorile din coloane. Se utilieaza
cand avem agegari in select. GROUP BY inseamna separarea pe grupe. GROUP BY SPLITS THE DATA UP
INTO COMBINATIONS OF ONE OR MORE VALUES

EX. 1 EX1. In an earlier exercise, you wrote a


SELECT separate WHERE query to determine the
SUM(demand_loss_mw) AS lost_demand, amount of demand lost for a specific region.
Description We wouldn't want to have to write individual
FROM grid queries for every region. Fortunately,you
WHERE don't have to write individual queries
Description LIKE ‘%storm’ for every region. With GROUP BY, you can
AND demand_loss_mw IS NOT NULL obtain a sum of all the unique values for your
GROUP BY description; -> daca nu punem chosen column, all at once.
description o sa avem o eroare deoarece avem -- Select the region column
agregare SELECT
nerc_region,
-- Sum the demand_loss_mw column
SUM(demand_loss_mw) AS demand_loss
FROM
grid
-- Exclude NULL values of demand_loss
WHERE
demand_loss_mw IS NOT NULL
-- Group the results by nerc_region
GROUP BY
nerc_region
-- Order the results in descending order of
demand_loss
ORDER BY
demand_loss DESC;

EX2. WHERE is used to filter rows before any EX.3


grouping occurs. Once you have performed a -- Retrieve the minimum and maximum place
grouping operation, you may want to further values
restrict the number of rows returned. This is a SELECT
job for HAVING. In this exercise, you will MIN(place) AS min_place,
modify an existing query to use HAVING, so MAX(place) AS max_place,
that only those results with a sum of -- Retrieve the minimum and maximum points
over 10000 are returned. values
SELECT MIN(points) AS min_points,
nerc_region, MAX(points) AS max_points
SUM (demand_loss_mw) AS demand_loss FROM
FROM
grid eurovision;
-- Remove the WHERE clause
GROUP BY
nerc_region
-- Enter a new HAVING clause so that the sum of
demand_loss_mw is greater than 10000
HAVING
SUM(demand_loss_mw) > 10000
ORDER BY
demand_loss DESC;

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

INNER JOIN album on album.album_id = track.album_id

INNER JOIN artist on artist.artist_id = album.artist_id;

LEFT & RIGHT JOIN

Toate nepotrivirile se pun cu NULL


LEFT JOIN – returneaza toate coloanele din tabelul stang

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

NULL – apare cand nu exista match

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.

EX.1 Complete the LEFT JOIN, returning all rows EX.2.


from the specified columns from invoiceline and
any matches from invoice. Let's now try some RIGHT joins. A RIGHT join will return
SELECT all rows from the right hand table, plus any matches from
the left hand side table.
invoiceline_id,
unit_price,
In addition to performing a RIGHT join, you'll also learn
quantity, how to avoid problems when different tables have the
billing_state same column names, by fully qualifying the column in your
-- Specify the source table select statement. Remember, we do this by prefixing the
column name with the table name.
FROM invoiceline
-- Complete the join to the invoice tableL For this exercise, we'll return to the Chinook database
LEFT JOIN from earlier in the chapter.
invoice ON invoiceline.invoice_id =
invoice.invoice_id;  SELECT the fully qualified column
names album_id from album and name from artist.
Then, join the tables so that only matching rows
are returned (non-matches should be discarded).

EX.3.To complete the query, join


the album table to the track table using
the relevant fully
qualified album_id column. The album
table is on the left-hand side of the join, and
the additional join should return all matches
or NULLs.

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

UNION ALL – La fel ca UNION, dar nu explude duplicatele!


EX.1 Make the first selection from the album table. Then join the results by providing the
relevant keyword and selecting from the artist table.
SELECT
album_id AS ID,
title AS description,
'Album' AS Source
-- Complete the FROM statement
FROM album
-- Combine the result set using the relevant keyword
UNION
SELECT
artist_id AS ID,
name AS description,
'Artist' AS Source
-- Complete the FROM statement
FROM artist;

Creator – CRUD Operations – CREATE,


READ, UPDATE, DELETE
Insert, Update, Delete
DACA NU FOLOSIM WHERE SE VOR ACTUALIZA DOATE VALORILE DIN COLOANA!

ELIMINA TOT TABELUL DE ODATA!

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.

-- Run the query


SELECT
*
FROM
album
-- DELETE the record
DELETE FROM
album
WHERE
album_id = 1
-- Run the query again
SELECT
*
FROM
album;
Declare yourself – Variabiles, Temporary
tables
EX1. -- Declare the variable @region EX2.-- Declare @start
DECLARE @region VARCHAR(10)
DECLARE @start DATE;
-- Update the variable value
SET @region = 'RFC'
-- SET @start to '2014-01-24'
SELECT description,
nerc_region, SET @start='2014-01-24';
demand_loss_mw,
affected_customers
FROM grid
WHERE nerc_region = @region;
EX3.-- Declare your variables EX4.
Sometimes you might want to 'save' the
DECLARE @start DATE
results of a query so you can do some more
DECLARE @stop DATE work with the data. You can do that by
DECLARE @affected INT; creating a temporary table that remains in the
-- SET the relevant values for each database until SQL Server is restarted. In this
final exercise, you'll select the longest track
variable from every album and add that into a
SET @start = '2014-01-24' temporary table which you'll create as part of
SET @stop = '2014-07-02' the query.
SET @affected = 5000 ;
SELECT album.title AS album_title,
SELECT artist.name as artist,
description, MAX(track.milliseconds / (1000 * 60) %
nerc_region, 60 ) AS max_track_length_mins
demand_loss_mw, -- Name the temp table #maxtracks
affected_customers INTO #maxtracks
FROM FROM album
grid -- Join album to artist using artist_id
-- Specify the date range of the INNER JOIN artist ON album.artist_id =
event_date and the value for @affected artist.artist_id
WHERE event_date BETWEEN @start -- Join track to album using album_id
AND @stop INNER JOIN track ON
AND affected_customers >= @affected; album.album_id=track.album_id
GROUP BY artist.artist_id, album.title,
artist.name,album.album_id
-- Run the final SELECT query to retrieve
the results from the temporary table
SELECT album_title, artist,
max_track_length_mins
FROM #maxtracks
ORDER BY max_track_length_mins DESC,
artist;

You might also like