You are on page 1of 11

* all columns

Relational Databases
A relational database is a database that organizes information into one or more
tables. Here, the relational database contains one table.

A table is a collection of data organized into rows and columns. Tables are
sometimes referred to as relations. Here the table is celebs.

A column is a set of data values of a particular type. Here, id, name, and age are
the columns.

A row is a single record in a table.

Statements
A statement is text that the database recognizes as a valid command. Statements
always end in a semicolon ;.

CREATE TABLE table_name (


column_1 data_type,
column_2 data_type,
column_3 data_type
);

CREATE TABLE celebs (


id INTEGER,
name TEXT,
age INTEGER
);

CREATE TABLE is a clause. Clauses perform specific tasks in SQL. By convention,


clauses are written in capital letters. Clauses can also be referred to as
commands.
table_name refers to the name of the table that the command 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. Here, the parameter is a list of column names and the associated
data type.

INSERT INTO celebs (id, name, age)


VALUES (1, 'Justin Bieber', 22);

SELECT name FROM celebs;


SELECT * FROM celebs;

ALTER TABLE celebs


ADD COLUMN twitter_handle TEXT;

UPDATE celebs
SET twitter_handle = '@taylorswift13'
WHERE id = 4;
at 4th row it is updated

DELETE FROM celebs


WHERE twitter_handle IS NULL;
rows with null value will get deleted

Constraints
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. The statement
below sets constraints on the celebs table.

CREATE TABLE celebs (


id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
date_of_birth TEXT NOT NULL,
date_of_death TEXT DEFAULT 'Not Applicable'
);
1. 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.

2. UNIQUE columns have a different value for every row. This is similar to PRIMARY
KEY except a table can have many different UNIQUE columns.

3. 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.

4. 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.

SELECT column1, column2


FROM table_name;

SELECT name AS 'Titles'


FROM movies;
It will rename Name table into Titles

DISTINCT is used to return unique values in the output. It filters out all
duplicate values in the specified column(s).

SELECT tools
FROM inventory;
might produce:

tools
Hammer
Nails
Nails
Nails

By adding DISTINCT before the column name,

SELECT DISTINCT tools


FROM inventory;
the result would now be:

tools
Hammer
Nails
SELECT *
FROM movies
WHERE name LIKE 'Se_en';
to search name starting with se and end with en, & has only single letter in the
middle

SELECT *
FROM movies
WHERE name LIKE 'A%';

SELECT *
FROM movies
WHERE name LIKE '%man%';

SELECT name
FROM movies
WHERE imdb_rating IS NOT NULL;

SELECT name
FROM movies
WHERE imdb_rating IS NULL;

SELECT *
FROM movies
WHERE name BETWEEN 'A' AND 'J';

SELECT *
FROM movies
WHERE year BETWEEN 1990 AND 1999;

SELECT *
FROM movies
WHERE name BETWEEN 'A' AND 'J';

AND
SELECT *
FROM movies
WHERE year BETWEEN 1970 AND 1979
AND imdb_rating > 8;

SELECT *
FROM movies
WHERE genre = 'horror'
AND year < 1985;

SELECT *
FROM movies
WHERE year BETWEEN 1990 AND 1999
AND genre = 'romance';

AND operator displays a row if all the conditions are true.


OR operator displays a row if any condition is true.

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

SELECT *
FROM movies
WHERE imdb_rating > 8
ORDER BY year DESC;

DESC is a keyword used in ORDER BY to sort the results in descending order (high to
low or Z-A).

ASC is a keyword used in ORDER BY to sort the results in ascending order (low to
high or A-Z).

The column that we ORDER BY doesn’t even have to be one of the columns that we’re
displaying.

Note: ORDER BY always goes after WHERE (if WHERE is present).

SELECT name, year, imdb_rating


FROM movies
ORDER BY imdb_rating DESC;

ELECT *
FROM movies
ORDER BY imdb_rating DESC
LIMIT 3;

SELECT *
FROM movies
LIMIT 10;

SELECT name,
CASE
WHEN imdb_rating > 8 THEN 'Fantastic'
WHEN imdb_rating > 6 THEN 'Poorly Received'
ELSE 'Avoid at All Costs'
END
FROM movies;

SELECT name,
CASE
WHEN genre = 'romance' THEN 'Chill'
WHEN genre = 'comedy' THEN 'Chill'
ELSE 'Intense'
END AS 'Mood'
FROM movies;

COUNT(): count the number of rows


SUM(): the sum of the values in a column
MAX()/MIN(): the largest/smallest value
AVG(): the average of the values in a column
ROUND(): round the values in the column
count how many apps are in the table.
SELECT COUNT(*)
FROM fake_apps

WHERE clause in the previous query to count how many free apps are in the table.
SELECT COUNT(*)
FROM fake_apps
WHERE price = 0;

SELECT SUM(downloads)
FROM fake_apps;

The MAX() and MIN() functions return the highest and lowest values in a column,
respectively.
SELECT MAX(downloads)
FROM fake_apps;
MAX() takes the name of a column as an argument and returns the largest value in
that column. Here, we returned the largest value in the downloads column.

MIN() works the same way but it does the exact opposite; it returns the smallest
value.

SELECT MAX(price)
FROM fake_apps;
returns the price of the most expensive app.

SELECT AVG(downloads)
FROM fake_apps;
The AVG() function works by taking a column name as an argument and returns the
average value for that column.
SELECT AVG(price)
FROM fake_apps;

Round
By default, SQL tries to be as precise as possible without rounding. We can make
the result table easier to read using the ROUND() function.

ROUND() function takes two arguments inside the parenthesis:

a column name
an integer
It rounds the values in the column to the number of decimal places specified by the
integer.
SELECT name, ROUND(price, 0)
FROM fake_apps;

SELECT ROUND(AVG(price), 2)
FROM fake_apps;

Group By I
SELECT year,
AVG(imdb_rating)
FROM movies
GROUP BY year
ORDER BY year;

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.

The GROUP BY statement comes after any WHERE statements, but before ORDER BY or
LIMIT.

query that calculates the total number of downloads for each category.
SELECT category, SUM(downloads)
FROM fake_apps
GROUP BY category;

Group By II
SELECT category,
price,
AVG(downloads)
FROM fake_apps
GROUP BY category, price;

SELECT category,
price,
AVG(downloads)
FROM fake_apps
GROUP BY 1, 2;
number given as per this table that we give category, price, AVG(downloads)

Having
GROUP BY, SQL also allows you to filter which groups to include and which to
exclude

For instance, imagine that we want to see how many movies of different genres were
produced each year, but we only care about years and genres with at least 10
movies.

We can’t use WHERE here because we don’t want to filter the rows; we want to filter
groups.

This is where HAVING comes in.

HAVING is very similar to WHERE. In fact, all types of WHERE clauses you learned
about thus far can be used with HAVING
HAVING statement always comes after GROUP BY, but before ORDER BY and LIMIT.

It returns the average downloads (rounded) and the number of apps – at each price
point.

However, certain price points don’t have very many apps, so their average downloads
are less meaningful.

Add a HAVING clause to restrict the query to price points that have more than 10
apps.

SELECT price,
ROUND(AVG(downloads)),
COUNT(*)
FROM fake_apps
GROUP BY price
HAVING COUNT(*) > 10;

SELECT price,
ROUND(AVG(downloads)),
COUNT(*)
FROM fake_apps
GROUP BY price
HAVING COUNT(name) > 10;

JOINS

tablename.column name

SELECT *
FROM orders
JOIN subscriptions
ON orders.subscription_id = subscriptions.subscription_id;

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

Inner Join

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().

SELECT COUNT(*)
FROM newspaper;

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

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

SELECT *
FROM newspaper
LEFT JOIN online
ON newspaper.id=online.id
WHERE online.id IS NULL;
INNER JOIN
SELECT *
FROM classes
INNER JOIN students
ON classes.id = students.class_id;

CROSS JOIN
SELECT COUNT(*)
FROM newspaper
WHERE start_month <= 3 AND end_month >= 3;

SELECT *
FROM newspaper
CROSS JOIN months;

SELECT *
FROM newspaper
CROSS JOIN months
WHERE start_month <= month AND end_month >= month;

SELECT month,
COUNT(*)
FROM newspaper
CROSS JOIN months
WHERE start_month <= month AND end_month >= month
GROUP BY month;

union
SELECT *
FROM newspaper
UNION
SELECT *
FROM online;

WITH previous_query AS (
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;

ORDER BY RIGHT(name,3),ID
substring(name, lenght(name)-2,3)

select ceil(avg(Salary) - avg(replace (Salary,'0','')))


from EMPLOYEES;

SELECT ROUND(LONG_W,4)
FROM STATION
WHERE LAT_N = (SELECT MAX(LAT_N)
FROM STATION
WHERE LAT_N < 137.2345);
SELECT ABS(ROUND((MIN(LAT_N) - MAX(LAT_N)) + (MIN(LONG_W) - MAX(LONG_W)),4))
FROM STATION;

SELECT round(sqrt(power((MAX(LAT_N) - MIN(LAT_N)),2) + power((MAX(LONG_W) -


MIN(LONG_W)),2)),4)
FROM STATION;

GIVE SUM FOR total population of all cities, COUNT for counting the no of cities
SELECT SUM(POPULATION)
FROM CITY
WHERE DISTRICT = 'CALIFORNIA';

SELECT
case
WHEN grade < 8 THEN 'NULL'
ELSE Name
END,
Grade, Marks
FROM Students
left JOIN Grades
ON Students.Marks >= Grades.Min_Mark AND Students.Marks <= Grades.Max_Mark
ORDER BY
Grade DESC,
case when grade between 1 and 7 then MARKS END ASC,
case when grade between 8 and 10 then Name END ASC;

Write a query to print the hacker_id, name, and total score of the hackers ordered
by the descending score. If more than one hacker achieved the same total score,
then sort the result by ascending hacker_id. Exclude all hackers with a total score
of from your result.

SELECT Hackers.hacker_id, Hackers.name, sum(mark.sco)


FROM Hackers
LEFT JOIN (SELECT hacker_id, max(score) as sco
FROM Submissions
group by hacker_id,challenge_id) as mark
ON Hackers.hacker_id = mark.hacker_id
group by Hackers.hacker_id, Hackers.name
HAVING sum(mark.sco) > 0
ORDER BY sum(mark.sco) DESC,Hackers.hacker_id asc;
=========================================================

SELECT h.hacker_id, MIN(h.name) FROM hackers h


JOIN Submissions s ON h.hacker_id = s.hacker_id
JOIN Challenges c ON s.challenge_id = c.challenge_id
JOIN Difficulty d ON c.difficulty_level = d.difficulty_level
WHERE s.score = d.score
GROUP BY h.hacker_id
HAVING COUNT(h.hacker_id) > 1
ORDER BY COUNT(h.hacker_id) DESC, h.hacker_id;
=======================================================
SELECT CONCAT(Name,'(',UPPER(Left(Occupation,1)),')') as occup
FROM OCCUPATIONS
ORDER BY Name asc;
SELECT CONCAT("There are a total of ", COUNT(Occupation), " ", LOWER(Occupation),
's.') as occup
FROM OCCUPATIONS
group by occupation
order by count(occupation) asc, occupation;
===================================================================
Pattern
MS SQL SERVER

Declare @variable_name DATATYPE -- first declare all the


-- variables with datatype
-- like (int)

select @variable = WITH_ANY_VALUE -- select the variable and


-- initialize with value

while CONDITION -- condition like @variable > 0

begin -- begin

print replicate('*', @variable) -- replicate insert the *


-- character in variable times

set increment/decrement -- in increment/decrement


-- @variable= @variable+1
END -- end while loop
===============================
DECLARE @R INT
SELECT @R = 20
WHILE @R > 0
BEGIN
PRINT REPLICATE('* ',@R)
SET @R = @R - 1
END
======================
* * * * *
* * * *
* * *
* *
*
=================
DECLARE @R Int
SELECT @R = 1
WHILE @R <= 20
BEGIN
PRINT REPLICATE('* ',@R)
SET @R = @R + 1
END
*
* *
* * *
* * * *
* * * * *

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX("https://www.google.co.in/root/subdir/
file.extension?p1=v1&p2=v2", '\/', -1),'\?',1);

# Write your MySQL query statement below


SELECT score,
DENSE_RANK () OVER (
ORDER BY score desc
) 'rank'
FROM Scores;

You might also like