Monday, September 8, 2014

Union, Intersect and Except



SELECT title FROM job_current
UNION
SELECT title FROM job_desired
UNION
SELECT title FROM job_listings;

Rules

1. UNION can only take one ORDER BY at the end of the statement.

SELECT title FROM job_current
UNION
SELECT title FROM job_desired
UNION
SELECT title FROM job_listings
ORDER BY title;

2. The number of columns in each SELECT must match.
3. Must also have the same expressions and aggregate functions in each SELECT statement.
4. SQL suppresses duplicate values from the results of a union.

UNION ALL

same as UNION but does not suppress duplicates

SELECT title FROM job_current
UNION ALL
SELECT title FROM job_desired
UNION ALL
SELECT title FROM job_listings
ORDER BY title;

Creating a table from your union

CREATE TABLE my_union AS
SELECT title FROM job_current UNION
SELECT title FROM job_desired
UNION SELECT title FROM job_listings

INTERSECT

To find parts of queries that overlap.

SELECT title FROM job_current
INTERSECT
SELECT title FROM job_desired;


EXCEPT

EXCEPT returns only those columns that are in the first query, but not in the second query.

SELECT title FROM job_current
EXCEPT
SELECT title FROM job_desired;


Outer join

An outer join returns all rows from one of the tables, along with matching information from another table.

With an inner join, you are comparing rows from two tables, but the order of those two tables does not matter.

Difference between an outer join and an inner join

An outer join gives a row whether there's a match with the other table or not.

A NULL value in the results of a left outer join means that the right table has no values that correspond to the left table.

Sunday, September 7, 2014

Subquery

A subquery is a query that is wrapped within another query. It's also called an INNER query.

SELECT mc.first_name, mc.last_name, mc.phone, jc.title
FROM job_current AS jc NATURAL JOIN my_contacts AS mc
WHERE jc.title IN (SELECT title FROM job_listings);

SELECT some_column, another_column
FROM table
WHERE column = (SELECT column FROM table)

Correlated subqueries

In a non correlated subquery the inner query, or subquery, gets interpreted by the RDBMS followed by the outer query.

SELECT mc.first_

Cartesian Join

The CROSS JOIN returns every row from one table crossed with every row from the second.

It is also called Cartesian Product, cross product, cross join or no join.

SELECT t.toy, b.boy
FROM toys AS t
CROSS JOIN
boys AS b;

or

SELECT toys.toy, boys.boy FROM toys, boys




Inner Join

An inner join is a cross join with some result rows removed by a condition in the query.
An inner join combines the records from two tables using comparison operators in a condition.

SELECT <some columns>
FROM table1
INNER JOIN
table2
ON <some conditions>

SELECT mc.last_name, mc.first_name, p.profession
FROM my_contacts AS mc
INNER JOIN
profession AS p
ON mc.contact_id = p.prof_id;

Equijoin

Inner joins test for equality

SELECT boys.boy, toys.toy
FROM boys
INNER JOIN
toys
ON boys.toy_id = toys.toy_id;

Non-Equijoin

Inner joins test for inequality.

SELECT boys.boy, toys.toy
FROM boys
INNER JOIN
toys
ON boys.toy_id <> toys.toy_id
ORDER BY boys.boy;

Natural Join

Natural join only work if the column you are joining by has the same name in both tables.

Natural join will recognize the same column name in each table and return matching rows.

SELECT boys.boy, toys.toy
FROM boys
NATURAL JOIN
toys;

Foreign Key



The foreign key is a column in a table that references the primary key of another table.


A NULL foreign key means that there is no matching primary key in the parent table.

Referential Integrity

You will only be able to insert values into your foreign key that exist in the table the key came from, the parent table.


You can use foreign key to reference a unique value in the parent table.
It does not have to be the primary key of the parent table, but it must be unique.

One-to-One: exactly one row of a parent table is related to one row of a child table.
It is not used that often.

One-to-many: a record in a table A can have many matching records in an other table B, but record in table B can only match ONE record in table A.

Many-to-Many: needs a junction table to avoid duplicates
It is usually made up of two one-to-many relationships with a junction table in between




Functions

RIGHT/LEFT

//start at the right side of location and get 2 characters
SELECT RIGHT(location, 2) FROM my_contacts

SELECT LEFT(location, 2) FROM my_contacts

SUBSTRING_INDEX

SELECT SUBSTRING_INDEX(location, ',', 1) FROM my_contacts
Finds everything in front of a specific character or string
If 1 were to be 2, then the second occurrence of the , would be looked and everything until that would be returned

SUM

SELECT SUM(sales)
FROM cookie_sales
WHERE first_name = 'Keith';

Normalization



To make tables completely normal, we need to give each record a primary key.

A primary key is a column in your table that makes each record unique. 





First Normal Form

Rule1: Columns contain only atomic values
Rule 2: No repeating groups of data





Composite key

A composite key is a primary key composed of multiple columns, creating a unique key.

Alteration

Altering a table

CHANGE both the name and data type of an existing column
MODIFY the data type or position of an existing column
ADD a column to the table
DROP a column from the table

CHANGE

ALTER TABLE project_list
CHANGE COLUMN number proj_id INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY ('proj_id');

Changing more than one column
ALTER TABLE project_list
CHANGE COLUMN descriptionofproj proj_desc VARCHAR(100),
CHANGE COLUMN contractoronjob con_name VARCHAR(30);

changing data type
ALTER TABLE project_list
MODIFY COLUMN proj_desc VARCHAR(120);

ADD

ALTER TABLE my_contacts
ADD COLUMN contact_id INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (contact_id);

ALTER TABLE my_contacts
ADD COLUMN phone VARCHAR(10) AFTER first_name;

ALTER TABLE my_contacts
ADD COLUMN phone VARCHAR(10) FIFTH first_name;

ALTER TABLE my_contacts
ADD COLUMN phone VARCHAR(10) LAST first_name;

ALTER TABLE my_contacts
ADD COLUMN phone VARCHAR(10) first_name;  //adds as the last column

DROP

ALTER TABLE project_table
DROP COLUMN start_date;

Renaming the table

ALTER TABLE projekts RENAME TO project_list;

Other Examples

ALTER TABLE car_table
CHANGE COLUMN mo model VARCHAR(20),
MODIFY COLUMN color AFTER model;

Saturday, September 6, 2014

Updation

UPDATE my_table
SET
type  = 'glazed'
WHERE
type = 'plain glazed';

UPDATE drink_info
SET
cost = 3.5
WHERE
drink_name = 'Blue Moon';

UPDATE drink_info
SET
cost = cost + 1
WHERE
drink_name = 'pepsi'
OR
drink_name = 'coke';

UPDATE my_table
SET new_column=
CASE
      WHEN column1 = somevalue1 THEN newvalue1
      WHEN column2 = somevalue2 THEN newvalue2
      ELSE newvalue3
END;

UPDATE movie_table
SET CATEGORY =
CASE
    WHEN drama =  'T' THEN 'drama'
    WHEN comedy = 'T' THEN 'comedy'
    WHEN cartoon= 'T' AND rating='G' THEN 'comedy'
    ELSE 'misc'
END;

UPDATE movie_table
SET CATEGORY =
CASE
    WHEN drama =  'T' THEN 'drama'
    WHEN comedy = 'T' THEN 'comedy'
    WHEN cartoon= 'T' AND rating='G' THEN 'comedy'
    ELSE 'misc'
END
WHERE <CONDITION>

Deletion

DELETE from clown_info
WHERE
activities = 'dancing';

Be careful with your DELETE

Change only the records you mean to by using a SELECT statement first

Selection

SELECT * FROM my_table;

SELECT * FROM my_table WHERE first_name='Keith';

SELECT <column names> FROM my_table WHERE first_name='Keith';

AND/OR
SELECT location FROM my_table WHERE first_name='Keith' AND last_name='Tapp';

NOT EQUAL
<>

SELECT drink_name FROM drink_info WHERE drink_name >= 'L' AND drink_name < 'M';

LIKE

SELECT * FROM my_contact
WHERE
location = 'San Fran, CA'
OR
location = 'San Fran, CALIFORNIA'
OR
location = 'San Fransisco, CA'
OR
location = 'San Frans, CA'
OR
location = 'San Fransci, CA'
OR
location = 'SanDiago, CA'

SELECT * FROM my_contact WHERE location LIKE '%CA';
Finds all values in the location column that end with CA

% is stand-in for any number of characters
_ is stand-in for just one character

BETWEEN

SELECT drink_name FROM drink_info WHERE calories BETWEEN 30 AND 60;

order matters ... so BETWEEN 60 AND 30 would yield nothing

IN

SELECT data_name FROM black_book WHERE rating IN ('innovative', 'fabulous', 'delightful', 'pretty good');

NOT

SELECT data_name FROM black_book
WHERE
rating
NOT IN ('innovative', 'fabulous', 'delightful', 'pretty good');

SELECT * FROM easy_drinks
WHERE
NOT MAIN IS NULL;

When used with AND or OR, it goes right after the AND or OR

SELECT date_name from black_book
WHERE 
NOT date_name LIKE 'A%'
AND 
NOT date_name LIKE 'B%';

SELECT * FROM easy_drinks
WHERE 
NOT main = 'soda'
AND 
NOT main = 'iced tea';

SELECT drink_name FROM drink_info
WHERE 
NOT carbs BETWEEN 3 AND 5;

ORDER BY

You can tell SQL to select something and ORDER the data it returns BY another column from the table.
By default is ascending order.
To change order, use DESC after column name in ORDER BY clauses.

SELECT title, category
FROM movie_table
WHERE LIKE 'A%'
AND
CATEGORY = 'family'
ORDER BY title;

can order multiple columns in the same statement
SELECT title, category, purchased
FROM movie_table
ORDER BY category, purchased;

First ordered by category .. will get every movie in the store ordered by category
and then ordered by purchased ... after the category column has been ordered



SELECT title, purchased
FROM movie_table
ORDER BY title ASC, purchased DESC;

SUM

//Group together all first_name values
SELECT first_name, SUM(sales)
FROM cookie_sales
GROUP BY first_name
ORDER BY SUM(sales) DESC;

AVG

Average adds up all the values in a group and divides it by the number of entries in the group

SELECT first_name, AVG(sales)
FROM cookie_sales
GROUP BY first_name;

MAX/MIN

SELECT first_name, MAX(sales)
FROM cookie_sales
GROUP BY first_name;

COUNT

SELECT COUNT(sale_date)
FROM cookie_sales;

DISTINCT (keyword)

SELECT DISTINCT sale_date
FROM cookie_sales
ORDER BY sale_date;

SELECT COUNT (DISTINCT sale_date)
FROM cookie_sales

LIMIT

// Limit results to first 2

SELECT first_name, SUM(sales)
FROM cookie_sales
GROUP BY first_name
ORDER BY SUM(sales) DESC
LIMIT 2;

If you want to see top 20 to 30 songs

LIMIT 19, 10; // indexing starts from 0

i.e. LIMIT start index, number of them

Creation

A database is a container that holds tables and other SQL structures related to those tables

Creating a database
create database <name of the database>;

Describing a database
DESC <name of the database>

Creating a table
CREATE TABLE <name of the table>(<names of columns>)
CREATE TABLE doughnut_list
                   (doughnut_name VARCHAR(10),
                    doughnut_type VARCHAR(6));

CREATE TABLE my_contacts
(
   contact_id INT NOT NULL,
   last_name VARCHAR(30) DEFAULT NULL,
   PRIMARY KEY (contact_id)
);

To avoid inserting unique values for the primary key, set it to auto_increment
CREATE TABLE my_contacts
(
   contact_id INT NOT NULL AUTO_INCREMENT,
   last_name VARCHAR(30) DEFAULT NULL,
   PRIMARY KEY (contact_id)
);

inserting into a table with auto_increment
INSERT INTO my_table VALUES (NULL, 'Keith', 'Tapp');
INSERT INTO my_table VALUES ('', 'Keith', 'Tapp');
INSERT INTO my_table VALUES ('Keith', 'Tapp');
INSERT INTO my_table VALUES (99, 'Keith', 'Tapp');

VARCHAR(10) is a variable

What query has been used to create a table
SHOW CREATE TABLE my_contacts;

Certain columns in the table should always have values
CREATE TABLE my_contacts
             (last_name VARCHAR(30) NOT NULL,
              first_name VARCHAR(20) NOT NULL);

Filling default values
CREATE TABLE blah(cost DEC(3,2) NOT NULL DEFAULT 1.00)

CREATE TABLE interests (
int_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
interest VARCHAR(50) NOT NULL,
contact_id INT NOT NULL,
CONSTRAINT my_contacts_contact_id_fk FOREIGN KEY(contact_id)
REFERENCES my_contacts (contact_id);
)

Dropping a table
DROP TABLE <name of the table>

Inserting values into a table
insert into <name of the table> (<name of columns>) values (<values>)