fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,8 @@
---
title: SQL
---
## SQL
SQL stands for Structured Query Language. It is the most common tool used to manipulate and manage data in a relational database (often referred to as a "SQL database").
SQL is commonly pronounced "sequel." Its most popular variants are MySQL, PostgreSQL, and SQLite - a version of SQL which is commonly used for prototyping. It introduced the concept of accessing many records with one single command, using SQL Queries.

View File

@ -0,0 +1,61 @@
---
title: SQL Aliases
---
## SQL Aliases
## Using AS to assign meaningful or simpler names
You can use AS to assign a name to a column of data you are selecting or that has been calculated.
```sql
SELECT user_only_num1 AS AgeOfServer, (user_only_num1 - warranty_period) AS NonWarrantyPeriod FROM server_table
```
This results in output as below.
```text
+-------------+------------------------+
| AgeOfServer | NonWarrantyPeriod |
+-------------+------------------------+
| 36 | 24 |
| 24 | 12 |
| 61 | 49 |
| 12 | 0 |
| 6 | -6 |
| 0 | -12 |
| 36 | 24 |
| 36 | 24 |
| 24 | 12 |
+-------------+------------------------+
```
You can also use AS to assign a name to a table to make it easier to reference in joins.
```sql
SELECT ord.product, ord.ord_number, ord.price, cust.cust_name, cust.cust_number FROM customer_table AS cust
JOIN order_table AS ord ON cust.cust_number = ord.cust_number
```
This results in output as below.
```text
+-------------+------------+-----------+-----------------+--------------+
| product | ord_number | price | cust_name | cust_number |
+-------------+------------+-----------+-----------------+--------------+
| RAM | 12345 | 124 | John Smith | 20 |
| CPU | 12346 | 212 | Mia X | 22 |
| USB | 12347 | 49 | Elise Beth | 21 |
| Cable | 12348 | 0 | Paul Fort | 19 |
| Mouse | 12349 | 66 | Nats Back | 15 |
| Laptop | 12350 | 612 | Mel S | 36 |
| Keyboard| 12351 | 24 | George Z | 95 |
| Keyboard| 12352 | 24 | Ally B | 55 |
| Air | 12353 | 12 | Maria Trust | 11 |
+-------------+------------+-----------+-----------------+--------------+
```

View File

@ -0,0 +1,43 @@
---
title: SQL Alter Table Statement
---
## SQL Guide - ALTER TABLE
## Introduction
This guide will introduce you to and attempt to explain some of the basics of the SQL alter table functions within a relational database.
**IMPORTANT Safety Tip: ALWAYS backup your data before making changes!**
We will be using MySQL for all examples throughout this freeCodeCamp SQL guide. The reasons for selecting MySQL are 1) it is very commonly used on websites for the backend database, 2) it's free, and is fun and easy to use.
## Covered in this Guide
We will use the tables created in the “CREATE TABLE” guide. Feel free to review that guide if you are not familiar with creating a table.
* Altering the created table will alter it in several different ways.
* We'll change its name and modify columns
* Add columns (while adding columns we will also review several of the most important column types and their use).
* Drop columns (meaning remove the column).
* Creating a table by importing a CSV file and altering that table.
* Creating and modifying tables with MySQL workbench tools.
Most of this will be done using SQL statements in the MySQL workbench scripting tool but we will also review how to alter a table using the workbench interface instead of with SQL statements.
## The table before alterations:
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/alter_table01a.JPG?raw=true)
Add date and email address columns (a date and a character column):
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/alter_table01.JPG?raw=true)
Add a numeric column (note that it was added in a specific location in the table):
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/alter_table02.JPG?raw=true)
Rename some columns:
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/alter_table03.JPG?raw=true)
Remove a column:
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/alter_table04.JPG?raw=true)
You can also use the alter table workbench tool. Just RIGHT click on the table you want to change and change as you wish.
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/alter_table05.JPG?raw=true)
There is much more that can be done, check the manual of your database management software to learn more.

View File

@ -0,0 +1,41 @@
---
title: SQL and Operator
---
## SQL AND operator
AND is used in a WHERE clause or a GROUP BY HAVING clause to limit the rows returned from the executed statement. Use AND when it's required to have more than one condition met.
We'll use the student table to present examples.
Here's the student table without a WHERE clause:
```sql
select * from student;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/and_operator01.JPG?raw=true)
Now the WHERE clause is added to display only programming students:
```sql
select * from student
where programOfStudy = 'Programming';
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/and_operator02.JPG?raw=true)
Now the WHERE clause is updated with AND to show results for programming students that also have a SAT score greater than 800:
```sql
select * from student
where programOfStudy = 'Programming'
and sat_score > 800;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/and_operator03.JPG?raw=true)
This is a more complex example from the campaign contributions table. This example has a GROUP BY clause with HAVING clause using an AND to restrict the returned records to candates from 2016 with contributions between $3 Million and $18 Million in total.
```sql
select Candidate, Office_Sought, Election_Year, FORMAT(sum(Total_$),2) from combined_party_data
where Office_Sought = 'PRESIDENT / VICE PRESIDENT'
group by Candidate, Office_Sought, Election_Year
having Election_Year = 2016 and sum(Total_$) between 3000000 and 18000000
order by sum(Total_$) desc;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/and_operator06.JPG?raw=true)

View File

@ -0,0 +1,25 @@
---
title: SQL Avg Function
---
## SQL Average (AVG) Function
"Average" is an Aggregate (Group By) Function. It's used to calculate the average of a numeric column from the set of rows returned by a SQL statement.
Here is the syntax for using the function:
```sql
select groupingField, avg(num_field)
from table1
group by groupingField
```
Here's an example using the student table:
```sql
select studentID, FullName, avg(sat_score)
from student
group by studentID, FullName;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/avg_function01.JPG?raw=true)

View File

@ -0,0 +1,51 @@
---
title: SQL Between Operator
---
## SQL Between Operator
The BETWEEN Operator is useful because of the SQL Query Optimizer. Although BETWEEN is functionally the same as:
x <= element <= y, the SQL Query Optimizer will recognize this command faster, and has optimized code for running it.
This operator is used in a WHERE clause or in a GROUP BY HAVING clause.
Rows are selected that have a value greater than the minimum value and less than the maximum value.
It's important to keep in mind that the values entered in the command are **excluded** from the result. We get just what is between them.
Here is the syntax for using the function in a WHERE Clause:
```sql
select field1, testField
from table1
where testField between min and max
```
Here is an example using the student table and the WHERE clause:
```sql
-- no WHERE clause
select studentID, FullName, studentID
from student;
-- WHERE clause with between
select studentID, FullName, studentID
from student
where studentID between 2 and 7;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/between01.JPG?raw=true)
Here is an example using the campaign funds table and the having clause.
This will return rows where the sum of the donations for a candidate are between $3 Million and $18 Million based on the HAVING clause in the GROUP BY part of the statement. More on aggregation in that guide.
```sql
select Candidate, Office_Sought, Election_Year, format(sum(Total_$),2)
from combined_party_data
where Election_Year = 2016
group by Candidate, Office_Sought, Election_Year
having sum(Total_$) between 3000000 and 18000000
order by sum(Total_$) desc;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/between02.JPG?raw=true)

View File

@ -0,0 +1,82 @@
---
title: SQL CHECK Constraint
---
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
### SQL CHECK on CREATE TABLE
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The CHECK constraint ensures that you can not have any person below 18 years:
**MySQL:**
```sql
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
```
**SQL Server / Oracle / MS Access:**
```sql
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
```
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
**MySQL / SQL Server / Oracle / MS Access:**
```sql
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
```
### SQL CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when the table is already created, use the following SQL:
**MySQL / SQL Server / Oracle / MS Access:**
```sql
ALTER TABLE Persons
ADD CHECK (Age>=18);
```
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
**MySQL / SQL Server / Oracle / MS Access:**
```sql
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
```
### DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
**SQL Server / Oracle / MS Access:**
```sql
ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;
```
**MySQL:**
```sql
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
```

View File

@ -0,0 +1,54 @@
---
title: SQL COUNT Aggregate Function
---
## SQL COUNT Aggregate Function
The COUNT operator is usually used in combination with a GROUP BY clause. It is one of the SQL "aggregate" functions, which include AVG (average) and SUM.
This function will count the number of rows and return that count as a column in the result set.
Here are examples of what you would use COUNT for:
* Counting all rows in a table (no group by required)
* Counting the totals of subsets of data (requires a Group By section of the statement)
For reference, here is the current data for all the rows in our example student database.
```sql
select studentID, FullName, programOfStudy, sat_score from student; -- all records with fields of interest
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/count01.JPG?raw=true)
This SQL statement provides a count of all rows. Note that you can give the resulting COUNT column a name using "AS".
```sql
select count(*) AS studentCount from student; -- count of all records
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/count02.JPG?raw=true)
Here we get a count of students in each field of study.
```sql
select programOfStudy, count(*) AS studentCount from the student table with a group by programOfStudy;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/count03.JPG?raw=true)
Here we get a count of students with the same SAT scores.
```sql
select sat_score, count(*) AS studentCount from the student table with a group by sat_score;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/count04.JPG?raw=true)
Here is an example using the campaign funds table. This is a sum total of the dollars in each transaction and the number of contributions for each political party during the 2016 US Presidential Campaign.
```sql
select Specific_Party, Election_Year, format(sum(Total_$),2) AS contribution$Total, count(*) AS numberOfContributions
from combined_party_data
group by Specific_Party,Election_Year
having Election_Year = 2016;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/count05.JPG?raw=true)
As with all of these things there is much more to it, so please see the manual for your database manager and have fun trying different tests yourself.

View File

@ -0,0 +1,39 @@
---
title: SQL CREATE INDEX Statement
---
## SQL CREATE INDEX Statement
This statement is used to create an "index" on a column in an existing table.
Key points on indexes:
* They are used to improve the efficiency of searches for data, presenting the data in a specific order, when joining tables (see the "JOIN" Guides) and more.
* An index is a "system" object, meaning that it is used by the database manager.
* Part of this usage is for the database manager to update the index when the data used by the index changes in the related table. Keep this in mind because as the number of indexes increase in a database overall system performance can be impacted.
* If you find that your SQLs are running slow on a given table or tables, creating an index is the first thing to consider to correct the issue.
Here's an example of the syntax of the Create Index Statement. Note that the syntax allows for an index to be over more than one column.
```sql
CREATE INDEX index_name
ON table_name (column1, column2, ...);
```
Creating a new index on the student table's field, programOfStudy.
For reference, here is the current definition of the student table.
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create-index-statement01.JPG?raw=true)
Here's a statement to create the index, and a screen shot of the updated table definition:
```sql
create index pStudyIndex
on student (programOfStudy);
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create-index-statement02.JPG?raw=true)
In MySQL, you use the ALTER TABLE command to change and drop indexes. The MySQL Workbench also provides GUI tools to manage indexes.
As with all of these things there is much more to it so please see the manual for your database manager, and have fun trying different options yourself.

View File

@ -0,0 +1,69 @@
---
title: SQL CREATE INDEX Statement
---
The CREATE INDEX statement is used to create indexes in tables.
Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are just used to speed up searches/queries.
> **Note:** Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So, only create indexes on columns that will be frequently searched against.
#### CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
```sql
CREATE INDEX index_name
ON table_name (column1, column2, ...);
```
#### CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
```sql
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
```
> **Note:** The syntax for creating indexes varies among different databases. Therefore: Check the syntax for creating indexes in your database.
#### CREATE INDEX Example
The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the "Persons" table:
```sql
CREATE INDEX idx_lastname
ON Persons (LastName);
```
If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
CREATE INDEX idx_pname
```sql
ON Persons (LastName, FirstName);
```
#### DROP INDEX Statement
The DROP INDEX statement is used to delete an index in a table.
**MS Access:**
```sql
DROP INDEX index_name ON table_name;
```
**SQL Server:**
```sql
DROP INDEX table_name.index_name;
```
**DB2/Oracle:**
```sql
DROP INDEX index_name;
```
**MySQL:**
```sql
ALTER TABLE table_name
DROP INDEX index_name;
```

View File

@ -0,0 +1,35 @@
---
title: SQL Create Table Statement
---
## SQL Create Table Statement
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
A table is a group of data stored in a database.
To create a table in a database you use the `CREATE TABLE` statement. You give a name to the table and a list of columns with its datatypes.
```
CREATE TABLE TABLENAME(Attribute1 Datatype, Attribute2 Datatype,........);
```
Heres an example creating a table named Person:
```sql
CREATE TABLE Person(
Id int not null,
Name varchar not null,
DateOfBirth date not null,
Gender bit not null,
PRIMARY KEY( Id )
);
```
In the example above, each Person has a Name, a Date of Birth and a Gender. The Id column is the key that identifies one person in the table. You use the keyword `PRIMARY KEY` to configure one or more columns as a primary key.
A column can be `not null` or `null` indicating whether it is mandatory or not.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,134 @@
---
title: SQL Create Table
---
# SQL CREATE TABLE
## Introduction
This guide is an overview to the basics of the SQL `CREATE TABLE` functions.
We will be using MySQL for all examples throughout these freeCodeCamp SQL guides. MySQL is a used frequently on websites for the backend database, 2) it's free, and is fun and easy to use.
## Covered in this Guide
* Creating a schema, the container for all our database objects.
* Create a table so we have something to alter.
* Creating a table by importing a CSV file and altering that table
* Creating a table using the MySQL workbench tool
We do most of this work with SQL statements in the MySQL workbench scripting tool. We will also see how to Create a table using the workbench interface instead of with SQL statements.
## High level structure of a Relational Database
1. Highest level; The Database; the database system installation. In this case, its MySQL. Called “Local instance MySQL Router” in the screen shots above.
2. Next is a Schema; a container for the objects needed to managed data in a relational database system.
3. Objects we create (tables, indexes, stored procedures, functions) to manage the system and its data
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create_table01.JPG?raw=true)
## Creating a MySQL schema
The schema is a container for a the objects required to manage the data for a given subject or process. We show examples as we progress in this guide.
Well create the schema for our learning and testing using the SQL command;
```
create database fCC_alterTableGuide;
```
This instances schema structure prior to running this command
![image-2](https://github.com/SteveChevalier/guide-images/blob/master/create_table02.JPG?raw=true)
This instances schema structure after running the SQL statement
![image-3](https://github.com/SteveChevalier/guide-images/blob/master/create_table03.JPG?raw=true)
## Creating a table, add test data with "insert", rename the table (alter)
Well create a Student Table.
The steps will be:
1. make sure we dont have the table already
2. create the table
3. insert the test data.
* Data Types: the student name is a character field limited to 90 characters
* The student ID is a number (integer) (range of -2147483648 to 2147483647). This will be the primary key for the table and will auto increment when a record is added.
* There will also be two "time-stamp" fields to play with as well
Create statement and display of results from execution;
![image-4](https://github.com/SteveChevalier/guide-images/blob/master/create_table04.JPG?raw=true)
Using a Select statement we'll see that the table is there but now records have been added.
![image-5](https://github.com/SteveChevalier/guide-images/blob/master/create_table05.JPG?raw=true)
Now to insert some data and see what our new table looks like with records in it (and understand create and update timestamps);
![image-6](https://github.com/SteveChevalier/guide-images/blob/master/create_table06.JPG?raw=true)
The first time stamp is the creation data and time and the 2nd is the update date and time. Changing a record should update ts2 but not ts1. Let's take a look.
![image-7](https://github.com/SteveChevalier/guide-images/blob/master/create_table07.JPG?raw=true)
## Create a table with the MySql Workbench
Right click on the "Tables" under the schema you want the new file placed in. Select Create Table.
![image-8](https://github.com/SteveChevalier/guide-images/blob/master/create_table08.JPG?raw=true)
Complete the form as desired and click Apply
![image-9](https://github.com/SteveChevalier/guide-images/blob/master/create_table09.JPG?raw=true)
## Create Table as Select (CTAS)
A quick way to create a copy of a table, including data is to create table as select.
CREATE TABLE my_table as (SELECT * FROM orig_tbl);
## Create and populate a table by importing a CSV file
Right click on the "Tables" under the schema you want the new file placed in. Select Table Data Import.
![image-10](https://github.com/SteveChevalier/guide-images/blob/master/create_table10.JPG?raw=true)
Select the CSV file to import and click NEXT
Usually you create a new table from the data, select the options desired and click NEXT
![image-11](https://github.com/SteveChevalier/guide-images/blob/master/create_table11.JPG?raw=true)
Adjust the data types as needed and click NEXT
![image-12](https://github.com/SteveChevalier/guide-images/blob/master/create_table12.JPG?raw=true)
Click NEXT (on this screen and the next one that is displayed) to import the data into the table
Youll see completion status, review and click FINISH
![image-13](https://github.com/SteveChevalier/guide-images/blob/master/create_table13.JPG?raw=true)
![image-14](https://github.com/SteveChevalier/guide-images/blob/master/create_table14.JPG?raw=true)
## Other Material
There lots more detail to cover this topic so install MySQL and have fun!
### Where to get MySQL
Try [this download for Windows users[(https://dev.mysql.com/downloads/windows/)
### MySQL documentation
* <a href='https://dev.mysql.com/doc/refman/5.7/en/alter-table.html' target='_blank' rel='nofollow'>manual page</a>
* <a href='https://dev.mysql.com/doc/refman/5.7/en/alter-table-examples.html' target='_blank' rel='nofollow'>examples from manual</a>
### SQL Server documentation
* <a href='https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql' target='_blank' rel='nofollow'>Microsoft Docs</a>

View File

@ -0,0 +1,75 @@
---
title: SQL Create View Statement
---
## SQL Create View Statement
### What is a View?
A View is a database object that presents data existing in one or more tables. Views are used in a similar way to tables, but they don't contain any data. They just "point" to the data that exists elsewhere (tables or views, for example).
### Why do we like them?
* Views are a way to limit the data presented. For example, the human resources department data filtered to only present non-sensitve information. Sensitive information in this case could be social security numbers, sex of employee, payrate, home address, etc.
* Complex data across more than one table can be combined into a single "view." This can make life easier for your business analysts and programmers.
### Important Safety Tips
* Views are managed by the system. When data in the related tables are changed, added, or updated, the View is updated by the system. We want to use these only when needed to manage use of system resources.
* In MySQL, changes to the table design (that is, new or dropped columns) made AFTER a view is created are not updated in the view itself. The view would have to be updated or recreated.
* Views are one of the four standard database object types. The others are tables, stored procedures, and functions.
* Views can usually be treated as you would a table, but updates are limited or not available when the view contains more than one table.
* There are many other details about views that are beyond the scope of this introductory guide. Spend time with your database managers manual and have fun with this powerful SQL object.
### Syntax of the Create View Statement (MySQL)
```sql
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
```
*This guide will cover this part of of the statement....*
```sql
CREATE
VIEW view_name [(column_list)]
AS select_statement
```
### Sample View creation from the student tables
Notes:
* The name of the view has a "v" at the end. It's recommended that the view name indicate that it's a view in some way to make life easier for programmers and database administrators. Your IT shop should have its own rules on naming objects.
* The columns in the view are limited by the SELECT and the rows of data by the WHERE clause.
* the "\`" character around the view names is required because of the "-" in the names. MySQL reports an error without them.
```sql
create view `programming-students-v` as
select FullName, programOfStudy
from student
where programOfStudy = 'Programming';
select * from `programming-students-v`;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create-view-statement01.JPG?raw=true)
### Sample of using a View to combine data from more than one table
A Student demographics table was added to the database to demonstrate this usage. This view will combine these tables.
Notes:
* To "join" tables, the tables must have fields in common (usually primary keys) that uniquely identity each row. In this case it's the student ID. (More on this in the [SQL Joins](../sql-joins/index.md) guide.)
* Notice the "alias" given to each table ("s" for student and "sc" for student contact). This is a tool to shorten the table names and make it easier to identify which table is being used. It's easier than typing long table names repeatedly. In this example, it was required because studentID is the same column name in both tables, and the system would present an "ambiguous column name error" without specifying which table to use.
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create-view-statement02.JPG?raw=true)
*As with all of these things there is MUCH MORE to Views. Please see the manual for your database manager and have fun trying different options yourself.*

View File

@ -0,0 +1,47 @@
---
title: SQL Data Types
---
# SQL Data Types
Each column in a table must have a data type. It indicates the type of value that the column stores.
Each database can accept differents data types, but in general, the list of data types is:
### Strings Types
Data type | Description
------------ | -------------
`CHAR(n)`| Character string. Fixed-length n. Minimal length is 1. If you assign a value to a CHAR column containing fewer characters than the defined length, the remaining space is filled with blanks characters.
`VARCHAR(n)` | Character string. Variable length. Maximum length n. Minimal length is 1
`BINARY(n)` | Binary string. Fixed-length n
`VARBINARY(n)` or `BINARY VARYING(n)` | Binary string. Variable length. Maximum length n
### Numerics Types
Data type | Description
------------ | -------------
`INTEGER` | Integer numerical. From -2,147,483,648 to 2,147,483,647.
`SMALLINT` | Integer numerical. From -32,768 to 32,767
`BIGINT` | Integer numerical. From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
`DECIMAL(p,s)` or `NUMERIC(p,s)` | Exact numerical, precision p, scale s. Precision is the maximum total number of decimal digits that will be stored, both to the left and to the right of the decimal point. Scale is the number of decimal digits that will be stored to the right of the decimal point. This number is subtracted from p to determine the maximum number of digits to the left of the decimal point. Example: decimal(5,2) is a number that has 3 digits before the decimal and 2 digits after the decimal.
`FLOAT(p)` | Approximate numerical, mantissa precision p. A floating number in base 10 exponential notation. The size argument for this type consists of a single number specifying the minimum precision
`REAL` | Approximate numerical, mantissa precision 7
`FLOAT` | Approximate numerical, mantissa precision 16
`DOUBLE PRECISION` | Approximate numerical, mantissa precision 16
### Date and Time Types
Data type | Description
------------ | -------------
`DATE` | Stores year, month, and day values
`TIME` | Stores hour, minute, and second values
`DATETIME` | Stores year, month, day, hour, minute, and second values
`TIMESTAMP` | Stores the number of seconds since the Unix epoch
`TIME WITH TIME ZONE` | Stores time of day with time zone
`TIMESTAMP WITH TIME ZONE` | Stores timestamp with time zone
### Other Data Types
Data type | Description
------------ | -------------
`BOOLEAN` | Stores `TRUE` or `FALSE` values
`ARRAY` | A set-length and ordered collection of elements
`MULTISET` | A variable-length and unordered collection of elements
`XML` | Stores XML data

View File

@ -0,0 +1,69 @@
---
title: SQL Date Functions
---
## SQL Date Functions
### Introduction
There are 61 Date Functions defined in MySQL. Don't worry, we won't review them all here. This guide will give you an introduction to some of the common ones, and enough exposure for you to comfortably to explore on your own.
We will cover:
* Getting the current date
* Date Math
* Dates in a where or having clause
### Getting the current date
Getting the date from the system can be very handy for processing data using SQL.
```sql
-- current date
select now(), sysdate(), current_date(), current_time(), -- date and time from the system on execution
dayofyear(now()) as NumDaysSoFarThisYr,
EXTRACT(YEAR FROM now()) as theYearPart,
EXTRACT(YEAR_MONTH FROM now()) as theYrMonPart,
date_format(now(), '%W %M %Y') as oneOfManyFormats;
;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/date-functions04.JPG)
In SQL query, we see the following:
* The first two columns in the result are two ways to get the same information: the date on the system at the time the SQL is executed.
* The next two columns slice out just the Date and Time parts of the system date.
* The next one presents the "day number" of the system date in this year. You'll notice that this is one day more than the math shown in the next example.
* The next two extract just the year and then both the year and month
* Last, but not least, there is a single example of one of the many ways to format this dates.
### Date Math
```sql
select now(), current_date(),
datediff(now(),'2017-01-01') as daysThisYear,
subdate(current_date(), interval 150 day) as '150DaysAgo',
adddate(now(), interval 7 day) as dateInA_Week -- date in a week
;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/date-functions02.jpg)
Here we see:
* The first two columns are just the system date and time for reference.
* The second column is the date difference (datediff) between the first of January 2017 and the system date.
* The last two columns are examples of subtracting and adding dates.
### In a where or having clause
Here are two examples of using date math in a where clause:
```sql
select * from student; - to show the current data being used for the example
select * from student where recordCreated < '2017-01-01';
select * from student where recordCreated < subdate(current_date(), interval 225 day);
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/date-functions03.jpg)
Regarding the HAVING part: Keep in mind, most of the WHERE clause logic will also work in the HAVING clause of a GROUP BY. The difference between the two is that the WHERE clause runs against the full data, and the HAVING runs against the data aggregated by the GROUP BY clause.
*As with all of these things there is MUCH MORE to them than what's in this introductory guide. I hope this at least gives you enough to get started. Please see the manual for your database manager and have fun trying different options yourself.*

View File

@ -0,0 +1,33 @@
---
title: SQL Delete Statement
---
## SQL Delete Statement
To delete a record in a table you use the `DELETE` statement.
Be careful. You can delete all records of the table or just a few. Use the `WHERE` condition to specify which records do you want to delete. The syntax is:
```sql
DELETE FROM table_name
WHERE condition;
```
Here is an example deleting from the table Person the record with Id 3:
```sql
DELETE FROM Person
WHERE Id = 3;
```
Using DELETE to remove all records from a given table
```sql
DELETE * FROM Person
;
```
Or depending on your RDBMS you could use the TRUNCATE TABLE statement which deletes all records from a table and depending on your RDBMS may or may not allow rollback. DELETE is DML and TRUNCATE is DDL.
```sql
TRUNCATE TABLE Person;
```

View File

@ -0,0 +1,68 @@
---
title: SQL Drop View Statement
---
## SQL Drop View Statement
### Introduction
This guide covers the SQL statement for dropping (deleting) one or more view objects.
A View is an object that presents data from one or more tables.
Note: before deleting or changing data or objects, remember to have a fresh backup.
We will cover:
* Using SQL to drop a table
* Using the workbench to drop a view
We'll be using MySQL for the demontration. Check the manual for this function in other Database Managers.
We'll drop the view called `students_dropMe_v`, which was created just for this purpose.
### Basic Syntax
```sql
DROP VIEW [IF EXISTS]
view_name [, view_name] ...
```
### Drop View SQL
The if exists portion will "trap" errors, should the view not exist.
```sql
drop view if exists students_dropMe_v;
```
The view after creation:
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/drop-view01.JPG)
Above command executed and views shown:
![image-2](https://github.com/SteveChevalier/guide-images/blob/master/drop-view02.JPG)
### Using the Workbench
From the workbench:
1) Right click on the view to drop
2) select drop view from the menu
3) Select either either a) run SQL to review the SQL statement to be executed or b) drop new
![image-3](https://github.com/SteveChevalier/guide-images/blob/master/drop-view03.JPG)
*As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide. I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.*
### Extra
Here's the SQL I used to create the table that we just dropped:
```sql
create view `students_dropMe_v` as
select FullName, programOfStudy
from student
where programOfStudy = 'Programming';
```

View File

@ -0,0 +1,97 @@
---
title: SQL Foreign Key Constraint
---
## SQL Foreign Key Constraint
A Foreign Key is a key used to link two tables. The table with the Foreign Key Constraint (aka "child table") is connected to another table (aka, the "parent table"). The connection is between the child table's Foreign Key Constraint and the parent table's Primary Key.
Foreign Key Constraints are used to help maintain consistency between the tables. For example, if a parent table record is deleted and the child table has records, the system could also delete the child records.
They also help prevent entering inaccurate data in the child table by requiring that a parent table record exists for every record that is entered in the child table.
### Example of use
For this guide we'll take a closer look at the student (parent) and student contact (child) tables.
### The parent table's primary key
Note that the student table has a one column primary key of studentID.
```sql
SHOW index FROM student;
```
```text
+---------+------------+----------+--------------+-------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name |
+---------+------------+----------+--------------+-------------+
| student | 0 | PRIMARY | 1 | studentID |
+---------+------------+----------+--------------+-------------+
1 row in set (0.00 sec) (some columns removed on the right for clarity)
```
### The child table's primary and foreign keys
The student contact info table has one primary key that is also the studentID. This is because there is a one-to-one relationship between the two tables. In other words, we expect only one student and one student contact record per student.
```sql
SHOW index FROM `student-contact-info`;
```
```text
+----------------------+------------+----------+--------------+-------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name |
+----------------------+------------+----------+--------------+-------------+
| student-contact-info | 0 | PRIMARY | 1 | studentID |
+----------------------+------------+----------+--------------+-------------+
1 row in set (0.00 sec) (some columns removed on the right for clarity)
```
```sql
SELECT concat(table_name, '.', column_name) AS 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) AS 'references'
FROM information_schema.key_column_usage
WHERE referenced_table_name IS NOT NULL
AND table_schema = 'fcc_sql_guides_database'
AND table_name = 'student-contact-info';
```
```text
+--------------------------------+-------------------+
| foreign key | references |
+--------------------------------+-------------------+
| student-contact-info.studentID | student.studentID |
+--------------------------------+-------------------+
1 row in set (0.00 sec)
```
### Example report using the student parent table and the contact child table
```sql
SELECT a.studentID, a.FullName, a.programOfStudy,
b.`student-phone-cell`, b.`student-US-zipcode`
FROM student AS a
JOIN `student-contact-info` AS b ON a.studentID = b.studentID;
```
```text
+-----------+------------------------+------------------+--------------------+--------------------+
| studentID | FullName | programOfStudy | student-phone-cell | student-US-zipcode |
+-----------+------------------------+------------------+--------------------+--------------------+
| 1 | Monique Davis | Literature | 555-555-5551 | 97111 |
| 2 | Teri Gutierrez | Programming | 555-555-5552 | 97112 |
| 3 | Spencer Pautier | Programming | 555-555-5553 | 97113 |
| 4 | Louis Ramsey | Programming | 555-555-5554 | 97114 |
| 5 | Alvin Greene | Programming | 555-555-5555 | 97115 |
| 6 | Sophie Freeman | Programming | 555-555-5556 | 97116 |
| 7 | Edgar Frank "Ted" Codd | Computer Science | 555-555-5557 | 97117 |
| 8 | Donald D. Chamberlin | Computer Science | 555-555-5558 | 97118 |
+-----------+------------------------+------------------+--------------------+--------------------+
```
### Conclusion
Foreign Key Constraints are a great data integrity tool. Take the time to learn them well.
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,61 @@
---
title: SQL General Data Types
---
## SQL General Data Types
# SQL Data Types
Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside each column when creating a table. The data type is a guideline for SQL to understand what type of data is expected inside of each column, and it also identifies how SQL will interact with the stored data.
# MySQL Data Types
SQL general data types consist of the following:
1. A text- and/or numeric-based value, often referred to as a STRING
2. A numeric-only value, often referred to as an INTEGER
3. A calendar- and/or clock-based value, often reffered to as DATE or TIME
4. A database-specific value such as a boolean (two-option) flag, an array that stores multiple values within one data point
## Text data types:
| Data type |Description |
| ------------- |:-------------:|
| CHAR(size) | Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters|
| VARCHAR(size) | Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type |
| TINYTEXT | Holds a string with a maximum length of 255 characters |
| TEXT | Holds a string with a maximum length of 65,535 characters |
| BLOB | For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data |
| MEDIUMTEXT | Holds a string with a maximum length of 16,777,215 characters |
| MEDIUMBLOB | For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data |
| LONGTEXT | Holds a string with a maximum length of 4,294,967,295 characters |
| LONGBLOB | For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data |
| ENUM(x,y,z,etc.) | Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z') |
| SET | Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice |
# Number data types:
| Data type |Description |
| ------------- |:-------------:|
| TINYINT(size) | -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis |
| SMALLINT(size) | -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis |
| MEDIUMINT(size) | -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis |
| INT(size) | -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis |
| BIGINT(size) | -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis |
| FLOAT(size,d) | A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter |
| DOUBLE(size,d) | A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter |
| DECIMAL(size,d) | A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter |
# Date data types:
| Data type |Description |
| ------------- |:-------------:|
| DATE() | A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31' |
| DATETIME() | A date and time combination. Format: YYYY-MM-DD HH:MI:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59' |
| TIMESTAMP() | A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MI:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC |
| TIME() | A time. Format: HH:MI:SS Note: The supported range is from '-838:59:59' to '838:59:59' |
| YEAR() | A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069 |
<!-- Please add any articles you think might be helpful to read before writing the article -->
#### More Information:
More information on the specific data types in SQL can be found in the [SQL Data Types] (https://guide.freecodecamp.org/sql/sql-data-types/) section of freeCodeCamp.

View File

@ -0,0 +1,46 @@
---
title: SQL Group By Statement
---
## SQL Group By Statemet
### Example of use
GROUP BY gives us a way to combine rows and aggregate data.
The data used is from the campaign contributions data we've been using in some of these guides.
The following SQL statement is answering the question: "which candidates received the largest total contributions in 2016 BUT only those that had more than $20 Million USD?"
Ordering this data set in a descending (DESC) order places the candidates with the largest total contributions at the top of the list.
```sql
SELECT Candidate, Election_year, sum(Total_$), count(*)
FROM combined_party_data
WHERE Election_year = 2016
GROUP BY Candidate, Election_year -- this tells the DBMS to summarize by these two columns
HAVING sum(Total_$) > 20000000 -- limits the rows presented from the summary of money ($20 Million USD)
ORDER BY sum(Total_$) DESC; -- orders the presented rows with the largest ones first.
```
```text
+--------------------------------------------------+---------------+-------------------+----------+
| Candidate | Election_year | sum(Total_$) | count(*) |
+--------------------------------------------------+---------------+-------------------+----------+
| CLINTON, HILLARY RODHAM & KAINE, TIMOTHY M (TIM) | 2016 | 568135094.4400003 | 126 |
| TRUMP, DONALD J & PENCE, MICHAEL R (MIKE) | 2016 | 366853142.7899999 | 114 |
| SANDERS, BERNARD (BERNIE) | 2016 | 258562022.17 | 122 |
| CRUZ, RAFAEL EDWARD (TED) | 2016 | 93430700.29000005 | 104 |
| CARSON, BENJAMIN S (BEN) | 2016 | 62202411.12999996 | 93 |
| RUBIO, MARCO ANTONIO | 2016 | 44384313.9 | 106 |
| BUSH, JOHN ELLIS (JEB) | 2016 | 34606731.78 | 97 |
+--------------------------------------------------+---------------+-------------------+----------+
7 rows in set (0.01 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,47 @@
---
title: SQL Having Clause
---
## SQL Having Clause
HAVING gives the DBA or SQL-using programmer a way to filter the data aggregated by the GROUP BY clause so that the user gets a limited set of records to view.
### Example of use
The HAVING clause is like the WHERE clause, exept it acts on the grouped data. In this case, the user will only see the largest amounts.
This data is from the campaign contributions data we've been using in some of these guides.
This SQL statement is answering the question: "which candidates received the largest total contributions in 2016 BUT only those that had more than 8$20 Million USD?"
Ordering this data set in a descending (DESC) order places the candidates with the largest total contributions at the top of the list.
```sql
SELECT Candidate, Election_year, sum(Total_$), count(*)
FROM combined_party_data
WHERE Election_year = 2016
GROUP BY Candidate, Election_year -- this tells the DBMS to summarize by these two columns
HAVING sum(Total_$) > 20000000 -- limits the rows presented from the summary of money ($20 Million USD)
ORDER BY sum(Total_$) DESC; -- orders the presented rows with the largest ones first.
```
```text
+--------------------------------------------------+---------------+-------------------+----------+
| Candidate | Election_year | sum(Total_$) | count(*) |
+--------------------------------------------------+---------------+-------------------+----------+
| CLINTON, HILLARY RODHAM & KAINE, TIMOTHY M (TIM) | 2016 | 568135094.4400003 | 126 |
| TRUMP, DONALD J & PENCE, MICHAEL R (MIKE) | 2016 | 366853142.7899999 | 114 |
| SANDERS, BERNARD (BERNIE) | 2016 | 258562022.17 | 122 |
| CRUZ, RAFAEL EDWARD (TED) | 2016 | 93430700.29000005 | 104 |
| CARSON, BENJAMIN S (BEN) | 2016 | 62202411.12999996 | 93 |
| RUBIO, MARCO ANTONIO | 2016 | 44384313.9 | 106 |
| BUSH, JOHN ELLIS (JEB) | 2016 | 34606731.78 | 97 |
+--------------------------------------------------+---------------+-------------------+----------+
7 rows in set (0.01 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,51 @@
---
title: SQL In Operator
---
## SQL In Operator
## IN Operator defined
The `IN` operator is used in a `WHERE` or `HAVING` (as part of the `GROUP BY`) to limit the selected rows to the items "IN" a list.
Here is the current full student list to compare to the `WHERE` clause result set:
```sql
select studentID, FullName, sat_score, rcd_updated from student;
```
```text
+-----------+------------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+------------------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 |
| 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+---------------------+
9 rows in set (0.00 sec)
```
Rows will be presented that have an SAT score in this list (1000, 2400):
```sql
select studentID, FullName, sat_score, rcd_updated
from student
where sat_score in (1000, 2400);
```
```text
+-----------+------------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+------------------------+-----------+---------------------+
| 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+---------------------+
4 rows in set (0.00 sec)
```

View File

@ -0,0 +1,20 @@
---
title: SQL Injection
---
## SQL Injection
SQL injection is a malicious technique that is meant to compromise or destroy databases. It is one of the most common web-hacking techniques.
SQL injection is performed by placing malicious code in SQL statements via an input.
The following example is a code snippet that will retrieve a user from a database based on an `AccountId`.
```
passedInAccountId = getRequestString("AccountId");
sql = "select * from Accounts where AccountId = " + passedInAccountId;
```
SQL injection can be used to compromise this code by injecting a `1=1;` statement for `AccountId`.
`https://www.foo.com/get-user?AccountId="105 OR 1=1;"`
`1=1` will always evaluate to `TRUE`. This will cause the executed code to output all of the Accounts table.

View File

@ -0,0 +1,97 @@
---
title: SQL Inner Join Keyword
---
## SQL Inner Join Keyword
### Example of use
For this guide we'll discuss the SQL (INNER) Joins
### Join (same as Inner Join)
The student table will be in the FROM clause so it will be a starting or LEFT table.
We'll JOIN this to the student contact table or RIGHT table.
You'll see that all of the students appear that ALSO are in the contact table. As shown in the tables below, studentID 9 is in the student table but NOT in the contact table so won't appear in a join.
SQL Statement
```sql
SELECT a.studentID, a.FullName, a.programOfStudy,
b.`student-phone-cell`, b.`student-US-zipcode`
FROM student AS a
INNER JOIN `student-contact-info` AS b ON a.studentID = b.studentID;
```
"Joined" data
``` text
+-----------+------------------------+------------------+--------------------+--------------------+
| studentID | FullName | programOfStudy | student-phone-cell | student-US-zipcode |
+-----------+------------------------+------------------+--------------------+--------------------+
| 1 | Monique Davis | Literature | 555-555-5551 | 97111 |
| 2 | Teri Gutierrez | Programming | 555-555-5552 | 97112 |
| 3 | Spencer Pautier | Programming | 555-555-5553 | 97113 |
| 4 | Louis Ramsey | Programming | 555-555-5554 | 97114 |
| 5 | Alvin Greene | Programming | 555-555-5555 | 97115 |
| 6 | Sophie Freeman | Programming | 555-555-5556 | 97116 |
| 7 | Edgar Frank "Ted" Codd | Computer Science | 555-555-5557 | 97117 |
| 8 | Donald D. Chamberlin | Computer Science | 555-555-5558 | 97118 |
+-----------+------------------------+------------------+--------------------+--------------------+
```
### Complete table listings for reference
Student table SQL
```sql
SELECT a.studentID, a.FullName, sat_score, a.programOfStudy, schoolEmailAdr
FROM student AS a;
```
student or LEFT table
```text
+-----------+------------------------+-----------+------------------+------------------------+
| studentID | FullName | sat_score | programOfStudy | schoolEmailAdr |
+-----------+------------------------+-----------+------------------+------------------------+
| 1 | Monique Davis | 400 | Literature | Monique@someSchool.edu |
| 2 | Teri Gutierrez | 800 | Programming | Teri@someSchool.edu |
| 3 | Spencer Pautier | 1000 | Programming | Spencer@someSchool.edu |
| 4 | Louis Ramsey | 1200 | Programming | Louis@someSchool.edu |
| 5 | Alvin Greene | 1200 | Programming | Alvin@someSchool.edu |
| 6 | Sophie Freeman | 1200 | Programming | Sophie@someSchool.edu |
| 7 | Edgar Frank "Ted" Codd | 2400 | Computer Science | Edgar@someSchool.edu |
| 8 | Donald D. Chamberlin | 2400 | Computer Science | Donald@someSchool.edu |
| 9 | Raymond F. Boyce | 2400 | Computer Science | Raymond@someSchool.edu |
+-----------+------------------------+-----------+------------------+------------------------+
9 rows in set (0.00 sec)
```sql
SELECT * FROM `student-contact-info` AS b;
```
student contact table or RIGHT table
``` text
+-----------+----------------------------------+--------------------+--------------------+
| studentID | studentEmailAddr | student-phone-cell | student-US-zipcode |
+-----------+----------------------------------+--------------------+--------------------+
| 1 | Monique.Davis@freeCodeCamp.org | 555-555-5551 | 97111 |
| 2 | Teri.Gutierrez@freeCodeCamp.org | 555-555-5552 | 97112 |
| 3 | Spencer.Pautier@freeCodeCamp.org | 555-555-5553 | 97113 |
| 4 | Louis.Ramsey@freeCodeCamp.org | 555-555-5554 | 97114 |
| 5 | Alvin.Green@freeCodeCamp.org | 555-555-5555 | 97115 |
| 6 | Sophie.Freeman@freeCodeCamp.org | 555-555-5556 | 97116 |
| 7 | Maximo.Smith@freeCodeCamp.org | 555-555-5557 | 97117 |
| 8 | Michael.Roach@freeCodeCamp.ort | 555-555-5558 | 97118 |
+-----------+----------------------------------+--------------------+--------------------+
8 rows in set (0.00 sec)
```
### Conclusion
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,27 @@
---
title: SQL Insert into Select Statement
---
## SQL Insert into Select Statement
You can insert records in a table using data that are already stored in the database. This is only a copy of data and it doesnt affect the origin table.
The `INSERT INTO SELECT` statement combines `INSERT INTO` and `SELECT` statements and you can use any conditions you want. The syntax is:
```sql
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
```
Here is an example that inserts in the table Person all the male students from the table Students.
```sql
INSERT INTO Person(Id, Name, DateOfBirth, Gender)
SELECT Id, Name, DateOfBirth, Gender
FROM Students
WHERE Gender = M
```

View File

@ -0,0 +1,44 @@
---
title: SQL Insert into Statement
---
## SQL Insert into Statement
To insert a record in a table you use the `INSERT INTO` statement.
You can do it in two ways, if you want to insert values only in some columns, you have to list their names including all mandatory columns. The syntax is:
```sql
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
```
The other way is inserting values to all columns in the table, it is not necessary to specify the columns names. The syntax is:
```sql
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
```
Heres an example inserting a record in the table Person in both ways:
```sql
INSERT INTO Person
VALUES (1, John Lennon, 1940-10-09, M);
```
And
```sql
INSERT INTO Person(Id, Name, DateOfBirth, Gender)
VALUES (1, John Lennon, 1940-10-09, M);
```
Some SQL versions (for example, MySQL) support inserting multiple rows at once. For example:
```sql
INSERT INTO Person(Id, Name, DateOfBirth, Gender)
VALUES (1, John Lennon, 1940-10-09, M), (2, Paul McCartney, 1942-06-18, M),
(3, George Harrison, 1943-02-25, M), (4, Ringo Starr, 1940-07-07, M)
```
Note that the entire original query remains intact - we simple add on data rows encloded by paranthesis and separated by commas.

View File

@ -0,0 +1,34 @@
---
title: SQL Insert Query
---
## SQL Insert Query
Insert queries are a way to insert data into a table. Let's say we have created a table using
`CREATE TABLE example_table ( name varchar(255), age int)`
**example_table**
| Name | Age |
| --- | --- |
Now to add some data to this table , we'll use **INSERT** in the following way:
`INSERT INTO example_table (column1,column2) VALUES ("Andrew",23)`
**example_table**
| Name | Age |
| --- | --- |
| Andrew | 23 |
Even the following will work, but it's always a good practice to specify which data is going into which column.
`INSERT INTO table_name VALUES ("John", 28)`
**example_table**
| Name | Age |
| --- | --- |
| Andrew | 23 |
| John | 28 |

View File

@ -0,0 +1,157 @@
---
title: SQL Interview Questions
---
## SQL Interview Questions
### What is an inner join in SQL?
This is the default type of join if no join is specified. It returns all rows in which there is at least one match in both tables.
```sql
SELECT * FROM A x JOIN B y ON y.aId = x.Id
```
### What is a left join in SQL?
A left join returns all rows from the left table, and the matched rows from the right table. Rows in the left table will be returned even if there was no match in the right table. The rows from the left table with no match in the right table will have `null` for right table values.
```sql
SELECT * FROM A x LEFT JOIN B y ON y.aId = x.Id
```
### What is a right join in SQL?
A right join returns all rows from the right table, and the matched rows from the left table. Opposite of a left join, this will return all rows from the right table even where there is no match in the left table. Rows in the right table that have no match in the left table will have `null` values for left table columns.
```sql
SELECT * FROM A x RIGHT JOIN B y ON y.aId = x.Id
```
### What is a full join in SQL?
A full join returns all rows for which there is a match in either of the tables. So if there are rows in the left table that do not have matches in the right table, those will be included. As well as if there are rows in the right table that do not have matches in the left table, those will be included.
```sql
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName
```
### What is the result of the following command?
```
DROP VIEW view_name
```
Here it'll be an error because we can't perform a DML operation on a view.
### Can we perform a rollback after using ALTER command?
No, because ALTER is a DDL command and Oracle server performs an automatic COMMIT when the DDL statements are executed.
### Which is the only constraint that enforces rules at column level?
NOT NULL is the only constraint that works at the column level.
### What are the pseudocolumns in SQL? Give some examples?
A pseudocolumn is a function which returns a system generated value. The reason it is known as so because a pseudocolumn is an Oracle assigned value used in the same context as an Oracle database column but not stored on disk.
``` Some examples of it are:
ROWNUM, ROWID, USER, CURRVAL, NEXTVAL etc.
```
### Create a user my723acct with password kmd26pt. Use the user_data and temporary data tablespaces provided by PO8 and provide to this user 10M of storage space in user_data and 5M of storage space in temporary_data.
``` sql
CREATE USER my723acct IDENTIFIED BY kmd26pt
DEFAULT TABLESPACE user_data
TEMPORARY TABLESPACE temporary_data
QUOTA 10M on user_data QUOTA 5M on temporary_data
```
### Create the role role_tables_and_views.
``` sql
CREATE ROLE role_tables_and_views
```
### Grant to the role of the previous question the privileges to connect to the database and the privileges to create tables and views.
The privilege to connect to the database is CREATE SESSION
The privilege to create table is CREATE TABLE
The privilege to create view is CREATE VIEW
``` sql
GRANT Create session, create table, create view TO role_tables_and_views
```
### Grant the previous role in the question to the users anny and rita
``` sql
GRANT role_tables_and_views TO anny, rita
```
### Create a user my723acct with password kmd26pt. Use the user_data and temporary data tablespaces provided by PO8 and provide to this user 10M of storage space in user_data and 5M of storage space in temporary_data.
``` sql
CREATE USER my723acct IDENTIFIED BY kmd26pt
DEFAULT TABLESPACE user_data
TEMPORARY TABLESPACE temporary_data
QUOTA 10M on user_data QUOTA 5M on temporary_data
```
### Create the role role_tables_and_views.
``` sql
CREATE ROLE role_tables_and_views
```
### Grant to the role of the previous question the privileges to connect to the database and the privileges to create tables and views.
The privilege to connect to the database is CREATE SESSION
The privilege to create table is CREATE TABLE
The privilege to create view is CREATE VIEW
``` sql
GRANT Create session, create table, create view TO role_tables_and_views
```
### Grant the previous role in the question to the users anny and rita
``` sql
GRANT role_tables_and_views TO anny, rita
```
### Write a command to change the password of the user rita from abcd to dfgh
``` sql
ALTER USER rita IDENTIFIED BY dfgh
```
### The users rita and anny do not have SELECT privileges on the table INVENTORY that was created by SCOTT. Write a command to allow SCOTT to grant the users SELECT priviliges on these tables.
``` sql
GRANT select ON inventory TO rita, anny
```
### User rita has been transferred and no longer needs the privilege that was granted to her through the role role_tables_and_views. Write a command to remove her from her previous given priviliges except that she still could connect to the database.
``` sql
REVOKE select ON scott.inventory FROM rita
REVOKE create table, create view FROM rita
```
### The user rita who was transferred is now moving to another company. Since the objects that she created is of no longer use, write a commmand to remove this user and all her objects.
Here CASCADE option is necessary to remove all the objects of the user in the database.
``` sql
DROP USER rita CASCADE
### User rita has been transferred and no longer needs the privilege that was granted to her through the role role_tables_and_views. Write a command to remove her from her previous given priviliges except that she still could connect to the database.
``` sql
REVOKE select ON scott.inventory FROM rita
REVOKE create table, create view FROM rita
```
### The user rita who was transferred is now moving to another company. Since the objects that she created is of no longer use, write a commmand to remove this user and all her objects.
Here CASCADE option is necessary to remove all the objects of the user in the database.
``` sql
DROP USER rita CASCADE
```
### Write SQL query to find the nth highest salary from table.
``` sql
SELECT TOP 1 Salary
FROM (
SELECT DISTINCT TOP N Salary
FROM Employee
ORDER BY Salary DESC
)
ORDER BY Salary ASC
```

View File

@ -0,0 +1,145 @@
---
title: SQL Joins
---
## SQL Joins
### Example of use
For this guide we'll discuss the JOIN section of the SQL statement.
### SQL syntax with focus on Join
```sql
SELECT col1, col2, col3, etc....
FROM tableNameOne AS a
JOIN tableNameTwo AS b ON a.primeKey = b.primeKey
etc...
```
The JOIN statement could be just JOIN or INNER JOIN, which are the same, or LEFT JOIN (described below).
### Different Types of JOINs
- (INNER) JOIN
- Return records that have matching values in both tables
- LEFT (OUTER) JOIN
- Return all records from the left table, and the matched records from the right table
- RIGHT (OUTER) JOIN
- Return all records from the right table, and the matched records from the left table
- FULL (OUTER) JOIN
- Return all records when there is a match in either left or right table
### Join
The student table will be in the FROM clause so it will be a starting or LEFT table.
We'll JOIN this to the student contact table or RIGHT table.
You'll see that all of the students appear that are also in the contact table.
As shown in the tables below, studentID 9 is in the student table but NOT in the contact table so won't appear in a join.
SQL Statement
```sql
SELECT a.studentID, a.FullName, a.programOfStudy,
b.`student-phone-cell`, b.`student-US-zipcode`
FROM student AS a
JOIN `student-contact-info` AS b ON a.studentID = b.studentID;
```
"Joined" data:
``` text
+-----------+------------------------+------------------+--------------------+--------------------+
| studentID | FullName | programOfStudy | student-phone-cell | student-US-zipcode |
+-----------+------------------------+------------------+--------------------+--------------------+
| 1 | Monique Davis | Literature | 555-555-5551 | 97111 |
| 2 | Teri Gutierrez | Programming | 555-555-5552 | 97112 |
| 3 | Spencer Pautier | Programming | 555-555-5553 | 97113 |
| 4 | Louis Ramsey | Programming | 555-555-5554 | 97114 |
| 5 | Alvin Greene | Programming | 555-555-5555 | 97115 |
| 6 | Sophie Freeman | Programming | 555-555-5556 | 97116 |
| 7 | Edgar Frank "Ted" Codd | Computer Science | 555-555-5557 | 97117 |
| 8 | Donald D. Chamberlin | Computer Science | 555-555-5558 | 97118 |
+-----------+------------------------+------------------+--------------------+--------------------+
```
### Left Join
Using the keyword LEFT before JOIN causes the system to start with the student (LEFT) table but will return NULL from the RIGHT table if there are no rows for the LEFT table student.
Note that studentID 9 appears here but the data from the contact table is just shown as NULL.
```sql
SELECT a.studentID, a.FullName, a.programOfStudy,
b.`student-phone-cell`, b.`student-US-zipcode`
FROM student AS a
LEFT JOIN `student-contact-info` AS b ON a.studentID = b.studentID;
```
``` text
+-----------+------------------------+------------------+--------------------+--------------------+
| studentID | FullName | programOfStudy | student-phone-cell | student-US-zipcode |
+-----------+------------------------+------------------+--------------------+--------------------+
| 1 | Monique Davis | Literature | 555-555-5551 | 97111 |
| 2 | Teri Gutierrez | Programming | 555-555-5552 | 97112 |
| 3 | Spencer Pautier | Programming | 555-555-5553 | 97113 |
| 4 | Louis Ramsey | Programming | 555-555-5554 | 97114 |
| 5 | Alvin Greene | Programming | 555-555-5555 | 97115 |
| 6 | Sophie Freeman | Programming | 555-555-5556 | 97116 |
| 7 | Edgar Frank "Ted" Codd | Computer Science | 555-555-5557 | 97117 |
| 8 | Donald D. Chamberlin | Computer Science | 555-555-5558 | 97118 |
| 9 | Raymond F. Boyce | Computer Science | NULL | NULL |
+-----------+------------------------+------------------+--------------------+--------------------+
9 rows in set (0.00 sec)
```
### Complete table listings for reference
Student table listings
```sql
SELECT a.studentID, a.FullName, sat_score, a.programOfStudy, schoolEmailAdr
FROM student AS a;
```
student or LEFT table
```text
+-----------+------------------------+-----------+------------------+------------------------+
| studentID | FullName | sat_score | programOfStudy | schoolEmailAdr |
+-----------+------------------------+-----------+------------------+------------------------+
| 1 | Monique Davis | 400 | Literature | Monique@someSchool.edu |
| 2 | Teri Gutierrez | 800 | Programming | Teri@someSchool.edu |
| 3 | Spencer Pautier | 1000 | Programming | Spencer@someSchool.edu |
| 4 | Louis Ramsey | 1200 | Programming | Louis@someSchool.edu |
| 5 | Alvin Greene | 1200 | Programming | Alvin@someSchool.edu |
| 6 | Sophie Freeman | 1200 | Programming | Sophie@someSchool.edu |
| 7 | Edgar Frank "Ted" Codd | 2400 | Computer Science | Edgar@someSchool.edu |
| 8 | Donald D. Chamberlin | 2400 | Computer Science | Donald@someSchool.edu |
| 9 | Raymond F. Boyce | 2400 | Computer Science | Raymond@someSchool.edu |
+-----------+------------------------+-----------+------------------+------------------------+
9 rows in set (0.00 sec)
```sql
SELECT * from `student-contact-info` AS b;
```
student contact or RIGHT table
``` text
+-----------+----------------------------------+--------------------+--------------------+
| studentID | studentEmailAddr | student-phone-cell | student-US-zipcode |
+-----------+----------------------------------+--------------------+--------------------+
| 1 | Monique.Davis@freeCodeCamp.org | 555-555-5551 | 97111 |
| 2 | Teri.Gutierrez@freeCodeCamp.org | 555-555-5552 | 97112 |
| 3 | Spencer.Pautier@freeCodeCamp.org | 555-555-5553 | 97113 |
| 4 | Louis.Ramsey@freeCodeCamp.org | 555-555-5554 | 97114 |
| 5 | Alvin.Green@freeCodeCamp.org | 555-555-5555 | 97115 |
| 6 | Sophie.Freeman@freeCodeCamp.org | 555-555-5556 | 97116 |
| 7 | Maximo.Smith@freeCodeCamp.org | 555-555-5557 | 97117 |
| 8 | Michael.Roach@freeCodeCamp.ort | 555-555-5558 | 97118 |
+-----------+----------------------------------+--------------------+--------------------+
8 rows in set (0.00 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,91 @@
---
title: SQL Left Join
---
## SQL Left Join
### Example of use
For this guide we'll discuss the SQL LEFT JOIN.
### Left Join
Using the keyword LEFT before JOIN causes the system to start with the student (LEFT) table but will return NULL from the RIGHT table if there are no rows for the LEFT table student.
Note that studentID 9 appears here but the data from the contact table is just shown as NULL.
```sql
SELECT a.studentID, a.FullName, a.programOfStudy,
b.`student-phone-cell`, b.`student-US-zipcode`
FROM student AS a
LEFT JOIN `student-contact-info` AS b ON a.studentID = b.studentID;
```
``` text
+-----------+------------------------+------------------+--------------------+--------------------+
| studentID | FullName | programOfStudy | student-phone-cell | student-US-zipcode |
+-----------+------------------------+------------------+--------------------+--------------------+
| 1 | Monique Davis | Literature | 555-555-5551 | 97111 |
| 2 | Teri Gutierrez | Programming | 555-555-5552 | 97112 |
| 3 | Spencer Pautier | Programming | 555-555-5553 | 97113 |
| 4 | Louis Ramsey | Programming | 555-555-5554 | 97114 |
| 5 | Alvin Greene | Programming | 555-555-5555 | 97115 |
| 6 | Sophie Freeman | Programming | 555-555-5556 | 97116 |
| 7 | Edgar Frank "Ted" Codd | Computer Science | 555-555-5557 | 97117 |
| 8 | Donald D. Chamberlin | Computer Science | 555-555-5558 | 97118 |
| 9 | Raymond F. Boyce | Computer Science | NULL | NULL |
+-----------+------------------------+------------------+--------------------+--------------------+
9 rows in set (0.00 sec)
```
### Complete table listings for reference
student or LEFT table SQL
```sql
SELECT a.studentID, a.FullName, sat_score, a.programOfStudy, schoolEmailAdr
FROM student AS a;
```
student or LEFT table data
```text
+-----------+------------------------+-----------+------------------+------------------------+
| studentID | FullName | sat_score | programOfStudy | schoolEmailAdr |
+-----------+------------------------+-----------+------------------+------------------------+
| 1 | Monique Davis | 400 | Literature | Monique@someSchool.edu |
| 2 | Teri Gutierrez | 800 | Programming | Teri@someSchool.edu |
| 3 | Spencer Pautier | 1000 | Programming | Spencer@someSchool.edu |
| 4 | Louis Ramsey | 1200 | Programming | Louis@someSchool.edu |
| 5 | Alvin Greene | 1200 | Programming | Alvin@someSchool.edu |
| 6 | Sophie Freeman | 1200 | Programming | Sophie@someSchool.edu |
| 7 | Edgar Frank "Ted" Codd | 2400 | Computer Science | Edgar@someSchool.edu |
| 8 | Donald D. Chamberlin | 2400 | Computer Science | Donald@someSchool.edu |
| 9 | Raymond F. Boyce | 2400 | Computer Science | Raymond@someSchool.edu |
+-----------+------------------------+-----------+------------------+------------------------+
9 rows in set (0.00 sec)
student contact or RIGHT table SQL
```sql
select * from `student-contact-info` as b;
```
student contact or RIGHT table data
``` text
+-----------+----------------------------------+--------------------+--------------------+
| studentID | studentEmailAddr | student-phone-cell | student-US-zipcode |
+-----------+----------------------------------+--------------------+--------------------+
| 1 | Monique.Davis@freeCodeCamp.org | 555-555-5551 | 97111 |
| 2 | Teri.Gutierrez@freeCodeCamp.org | 555-555-5552 | 97112 |
| 3 | Spencer.Pautier@freeCodeCamp.org | 555-555-5553 | 97113 |
| 4 | Louis.Ramsey@freeCodeCamp.org | 555-555-5554 | 97114 |
| 5 | Alvin.Green@freeCodeCamp.org | 555-555-5555 | 97115 |
| 6 | Sophie.Freeman@freeCodeCamp.org | 555-555-5556 | 97116 |
| 7 | Maximo.Smith@freeCodeCamp.org | 555-555-5557 | 97117 |
| 8 | Michael.Roach@freeCodeCamp.ort | 555-555-5558 | 97118 |
+-----------+----------------------------------+--------------------+--------------------+
8 rows in set (0.00 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,95 @@
---
title: SQL LIKE Operator
---
## SQL LIKE Operator
### LIKE Operator defined
The `LIKE` operator is used in a `WHERE` or `HAVING` (as part of the `GROUP BY`) to limit the selected rows to the items when a column has a certain pattern of characters contained in it.
### This guide will demonstrate:
* Determining if a string starts or ends with a given string pattern
* Determining if a pattern exists in the middle of the string
* Determining if a string is not contained in the string
### A column starts or ends with a given string pattern
This SQL will select students that have `FullName` starting with "Monique" or ending with "Greene".
```sql
SELECT studentID, FullName, sat_score, rcd_updated
FROM student
WHERE
FullName LIKE 'Monique%' OR -- note the % at the end but not the beginning
FullName LIKE '%Greene'; -- note the % at the beginning but not the end
```
```text
+-----------+---------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+---------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
+-----------+---------------+-----------+---------------------+
2 rows in set (0.00 sec)
```
### A string pattern is in the middle of the column
This SQL will select students that have "ree" anywhere in the name.
```sql
SELECT studentID, FullName, sat_score, rcd_updated
FROM student
WHERE FullName LIKE '%ree%'; -- note the % at the beginning AND at the end
```
```text
+-----------+----------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+----------------+-----------+---------------------+
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 |
+-----------+----------------+-----------+---------------------+
2 rows in set (0.00 sec)
```
### A string is NOT in the column
You can place "NOT" before LIKE to exclude the rows with the string pattern instead of selecting them.
This SQL excludes records that contain "cer Pau" and "Ted" in the FullName column.
```sql
SELECT studentID, FullName, sat_score, rcd_updated
FROM student
WHERE FullName NOT LIKE '%cer Pau%' AND FullName NOT LIKE '%"Ted"%';
```
```text
+-----------+----------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+----------------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 |
+-----------+----------------------+-----------+---------------------+
7 rows in set (0.00 sec)
```
*Here is the current full student list to compare to the where clause result sets above.*
```sql
SELECT studentID, FullName, sat_score, rcd_updated FROM student;
```
```text
+-----------+------------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+------------------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 |
| 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+---------------------+
9 rows in set (0.00 sec)

View File

@ -0,0 +1,17 @@
---
title: SQL not Operator
---
## SQL not Operator
You can use the `NOT` operator in the `WHERE` clause of `SELECT` statement. You use it when you want to select a condition that is not true.
Here is an example that selects all persons that are not male:
```sql
SELECT Id, Name, DateOfBirth, Gender
FROM Person
WHERE NOT Gender = "M"
```

View File

@ -0,0 +1,24 @@
---
title: SQL or Operator
---
## SQL or Operator
You can use the `OR` operator in the `WHERE` clause of `SELECT` statement. You use it when you want to select a record that satisfies at least one of the conditions in your `OR` statement.
Here is an example that selects all records from the Person table who are either male or who have the name “Mary”:
```sql
SELECT Id, Name, DateOfBirth, Gender
FROM Person
WHERE Gender = M OR Name = Mary
```
You can combine others operators in the `WHERE` clause (use parenthesis to indicate the order of operations) like in this example:
```sql
SELECT Id, Name, DateOfBirth, Gender
FROM Person
WHERE Gender = M AND (Name = Peter OR Name = John)
```
This example selects all records where Gender is "M" and Name is "Peter" as well as where Gender is "M" and Name is "John".

View File

@ -0,0 +1,59 @@
---
title: SQL Order By Keyword
---
## SQL Order By Keyword
### Order By (ASC, DESC)
ORDER BY gives us a way to SORT the result set by one or more of the items in the SELECT section. Here is an SQL sorting the students by FullName in descending order. The default sort order is ascending (ASC) but to sort in the opposite order (descending) you use DESC.
```sql
SELECT studentID, FullName, sat_score
FROM student
ORDER BY FullName DESC;
```
```text
+-----------+------------------------+-----------+
| studentID | FullName | sat_score |
+-----------+------------------------+-----------+
| 2 | Teri Gutierrez | 800 |
| 3 | Spencer Pautier | 1000 |
| 6 | Sophie Freeman | 1200 |
| 9 | Raymond F. Boyce | 2400 |
| 1 | Monique Davis | 400 |
| 4 | Louis Ramsey | 1200 |
| 7 | Edgar Frank "Ted" Codd | 2400 |
| 8 | Donald D. Chamberlin | 2400 |
| 5 | Alvin Greene | 1200 |
+-----------+------------------------+-----------+
9 rows in set (0.00 sec)
```
*Here is the UN-ORDERED, current, full student list to compare to the above.*
```sql
SELECT studentID, FullName, sat_score, rcd_updated FROM student;
```
```text
+-----------+------------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+------------------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 |
| 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+---------------------+
9 rows in set (0.00 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,45 @@
---
title: SQL Primary Key Constraint
---
## Primary Key Constraint
### Introduction
A primary key is a column or a set of columns that uniquely identifies each row in a table.
It's called a "constraint" because it causes the system to restrict the data allowed in these column(s). In this case....
* to contain data (NOT NULL)
* be UNIQUE from all other rows in the table.
* Each table can have only ONE primary key
Primary keys are mostly used to maintain the data integrity of each row.
It also allows the system and applications to be sure they are reading, updating and joining the data correctly.
### Example with create table
Here is a create table command that will also create a primary key using two fields.
```sql
CREATE TABLE priKeyExample(
rcdKey_id_a INT NOT NULL,
rcdKeySeq_id INT NOT NULL,
someData varchar(256) NOT NULL,
PRIMARY KEY(rcdKey_id_a,rcdKeySeq_id));
```
### Example with alter table
The existing one must be deleted first
```sql
DROP INDEX `primary` ON priKeyExample;
```
Now we'll add the new one.
```sql
ALTER TABLE priKeyExample
ADD CONSTRAINT myPriKey PRIMARY KEY(rcdKey_id_a,rcdKeySeq_id);
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,111 @@
---
title: SQL Replace VIEW Statement
---
## SQL Replace VIEW Statement
## Introduction
A View is a database object that presents data from in one or more tables. The same SQL statement used to create a view can also be used to replace an existing view.
This guide will update (replace) the existing view "programming-students-v" with one that is slightly different and has a different name.
Safety tip: always backup the schema before making changes to it.
### General sytax
```sql
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
```
### SQL Used to create the view and the current data
```sql
create view `programming-students-v` as
select FullName, programOfStudy
from student
where programOfStudy = 'Programming';
```
```sql
select * from `programming-students-v`;
```
Current Data:
```text
+-----------------+----------------+
| FullName | programOfStudy |
+-----------------+----------------+
| Teri Gutierrez | Programming |
| Spencer Pautier | Programming |
| Louis Ramsey | Programming |
| Alvin Greene | Programming |
| Sophie Freeman | Programming |
+-----------------+----------------+
5 rows in set (0.00 sec)
```
A list of the existing views:
```sql
SHOW FULL TABLES IN fcc_sql_guides_database WHERE TABLE_TYPE LIKE 'VIEW';
```
```text
+-----------------------------------+------------+
| Tables_in_fcc_sql_guides_database | Table_type |
+-----------------------------------+------------+
| programming-students-v | VIEW |
| students-contact-info_v | VIEW |
| students_dropme_v | VIEW |
+-----------------------------------+------------+
3 rows in set (0.00 sec)
```
### Replacing the view
```sql
create or replace view `programming-students-v` as
select FullName, programOfStudy, sat_score
from student
where programOfStudy = 'Programming';
```
```sql
select * from `programming-students-v`;
```
Note: the view now shows the sat_score.
```text
+-----------------+----------------+-----------+
| FullName | programOfStudy | sat_score |
+-----------------+----------------+-----------+
| Teri Gutierrez | Programming | 800 |
| Spencer Pautier | Programming | 1000 |
| Louis Ramsey | Programming | 1200 |
| Alvin Greene | Programming | 1200 |
| Sophie Freeman | Programming | 1200 |
+-----------------+----------------+-----------+
```
Note: the list of views hasn't change, our view is replaced.
```text
mysql> SHOW FULL TABLES IN fcc_sql_guides_database WHERE TABLE_TYPE LIKE 'VIEW';
+-----------------------------------+------------+
| Tables_in_fcc_sql_guides_database | Table_type |
+-----------------------------------+------------+
| programming-students-v | VIEW |
| students-contact-info_v | VIEW |
| students_dropme_v | VIEW |
+-----------------------------------+------------+
3 rows in set (0.00 sec)
```
*As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide. I hope this at least gives you enough to get started. Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,77 @@
---
title: SQL Right Join
---
## SQL Right Join
### Example of use
For this guide we'll discuss the SQL RIGHT JOIN.
### Right Join
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from the left table(table1) . The result is NULL from the left side, when there is no match.
```sql
SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
```
### Complete table listings for reference
food or LEFT table data
```text
+---------+--------------+-----------+------------+
| ITEM_ID | ITEM_NAME | ITEM_UNIT | COMPANY_ID |
+---------+--------------+-----------+------------+
| 1 | Chex Mix | Pcs | 16 |
| 6 | Cheez-It | Pcs | 15 |
| 2 | BN Biscuit | Pcs | 15 |
| 3 | Mighty Munch | Pcs | 17 |
| 4 | Pot Rice | Pcs | 15 |
| 5 | Jaffa Cakes | Pcs | 18 |
| 7 | Salt n Shake | Pcs | |
+---------+--------------+-----------+------------+
company or RIGHT table data
``` text
+------------+---------------+--------------+
| COMPANY_ID | COMPANY_NAME | COMPANY_CITY |
+------------+---------------+--------------+
| 18 | Order All | Boston |
| 15 | Jack Hill Ltd | London |
| 16 | Akas Foods | Delhi |
| 17 | Foodies. | London |
| 19 | sip-n-Bite. | New York |
+------------+---------------+--------------+
```
To get company name from company table and company ID, item name columns from foods table, the following SQL statement can be used:
```sql
SELECT company.company_id,company.company_name,
company.company_city,foods.company_id,foods.item_name
FROM company
RIGHT JOIN foods
ON company.company_id = foods.company_id;
```
OUTPUT
``` text
COMPANY_ID COMPANY_NAME COMPANY_CITY COMPANY_ID ITEM_NAME
---------- ------------------------- ------------------------- ---------- --------------
18 Order All Boston 18 Jaffa Cakes
15 Jack Hill Ltd London 15 Pot Rice
15 Jack Hill Ltd London 15 BN Biscuit
15 Jack Hill Ltd London 15 Cheez-It
16 Akas Foods Delhi 16 Chex Mix
17 Foodies. London 17 Mighty Munch
NULL NULL NULL NULL Salt n Shake
```

View File

@ -0,0 +1,51 @@
---
title: SQL Select Distinct Statement
---
## SQL Select Distinct Statement
### Introduction
This keyword allows us to get lists of unique values in a column. This guide will demonstrate that.
### Full display of the data in the student table
```sql
USE fcc_sql_guides_database;
SELECT studentID, FullName, sat_score, programOfStudy, rcd_Created, rcd_Updated FROM student;
```
```text
+-----------+------------------------+-----------+------------------+---------------------+---------------------+
| studentID | FullName | sat_score | programOfStudy | rcd_Created | rcd_Updated |
+-----------+------------------------+-----------+------------------+---------------------+---------------------+
| 1 | Monique Davis | 400 | Literature | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 3 | Spencer Pautier | 1000 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | Computer Science | 2017-08-16 15:35:33 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | Computer Science | 2017-08-16 15:35:33 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | Computer Science | 2017-08-16 15:35:33 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+------------------+---------------------+---------------------+
9 rows in set (0.00 sec)
```
### Get list of fields of study
```sql
SELECT DISTINCT programOfStudy FROM student;
```
```text
+------------------+
| programOfStudy |
+------------------+
| Literature |
| Programming |
| Computer Science |
+------------------+
3 rows in set (0.00 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,42 @@
---
title: SQL Select into Statement
---
## SQL Select into Statement
The `SELECT INTO` statement is a query that allows you to create a *new* table and populate it with the result set of a `SELECT statement`. To add data to an existing table, see the [INSERT INTO](guides/src/pages/sql/sql-insert-into-select-statement/index.md) statement instead.
`SELECT INTO` can be used when you are combining data from several tables or views into a new table.<sup>1</sup> The original table is not affected.
The general syntax is:
```sql
SELECT column-names
INTO new-table-name
FROM table-name
WHERE EXISTS
(SELECT column-name
FROM table-name
       WHERE condition)
```
This example shows a set of a table that was "copied" from the "Supplier" table to a new one called SupplierUSA which holds the set related to the column country of value 'USA'.
```sql
SELECT * INTO SupplierUSA
FROM Supplier
WHERE Country = 'USA';
```
**Results**: 4 rows affected <sup>2</sup>
| ID | CompanyName | ContactName | City | Country | Phone |
|----|-----------------------------|:--------------:|-------------|:--------:|:--------------:|
| 2 | New Orleans Cajun Delights | Shelley Burke | New Orleans | USA | (100) 555-4822 |
| 3 | Grandma Kelly's Homestead | Regina Murphy | Ann Arbor | USA | (313) 555-5735 |
| 16 | Bigfoot Breweries | Cheryl Saylor | Bend | USA | NULL |
| 19 | New England Seafood Cannery | Robb Merchant | Boston | USA | (617) 555-3267 |
Please see the manual for your database manager and have fun trying different options yourself.
## Sources
1. (Microsoft - Inserting Rows by Using SELECT INTO)[https://technet.microsoft.com/en-us/library/ms190750(v=sql.105).aspx]
2. (dofactory - SQL SELECT INTO Statement)[http://www.dofactory.com/sql/select-into]

View File

@ -0,0 +1,39 @@
---
title: SQL Select Statement
---
## SQL Select Statement
## Select and From clauses
The SELECT part of a query is normally to determine which columns of the data to show in the results. There are also options you can apply to show data that is not a table column.
This example shows three columns selected from the "student" table and one calculated column. The database stores the studentID, FirstName, and LastName of the student. We can combine the First and the Last name columns to create the FullName calculated column.
```sql
select studentID, FirstName, LastName, FirstName + ' ' + LastName as FullName
from student;
```
```text
+-----------+-------------------+------------+------------------------+
| studentID | FirstName | LastName | FullName |
+-----------+-------------------+------------+------------------------+
| 1 | Monique | Davis | Monique Davis |
| 2 | Teri | Gutierrez | Teri Gutierrez |
| 3 | Spencer | Pautier | Spencer Pautier |
| 4 | Louis | Ramsey | Louis Ramsey |
| 5 | Alvin | Greene | Alvin Greene |
| 6 | Sophie | Freeman | Sophie Freeman |
| 7 | Edgar Frank "Ted" | Codd | Edgar Frank "Ted" Codd |
| 8 | Donald D. | Chamberlin | Donald D. Chamberlin |
| 9 | Raymond F. | Boyce | Raymond F. Boyce |
+-----------+-------------------+------------+------------------------+
9 rows in set (0.00 sec)
```
*As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,46 @@
---
title: SQL Server Convert Function
---
## SQL Server Convert Function
Converts from one data type to another data type.
### Syntax
`CONVERT (_New Data Type, Expression, Style_)`
- **New Data Type:** New data type to be converted too. For example: nvarchar, integer, decimal, date
- **Expression:** Data to be converted.
- **Style:** Format. For example: The style 110 is USA Date format mm-dd-yyyy
### Example: Convert a Decimal Number to An Integer
`SELECT CONVERT(INT, 23.456) as IntegerNumber`
![convert a decimal number to integer number](https://user-images.githubusercontent.com/12566249/31314884-6c94db4a-ac57-11e7-842f-710fad511131.png)
Note: The result is truncated.
### Example: Convert a String to a Date
`SELECT CONVERT(DATE, '20161030') as Date`
![convert a string to a date type](https://user-images.githubusercontent.com/12566249/31314912-c25bbb52-ac57-11e7-880d-6d81041b1728.png)
### Example: Convert a Decimal to a String
`SELECT CONVERT(nvarchar, 20.123) as StringData`
![convert a decimal to a string](https://user-images.githubusercontent.com/12566249/31314923-fb04e410-ac57-11e7-9646-94061e1f0ec2.png)
### Example: Convert an Integer Number to a Decimal Number
`SELECT CONVERT(DECIMAL (15,3), 13) as DecimalNumber`
![convert an integer to a decimal number](https://user-images.githubusercontent.com/12566249/31314932-1c8668ca-ac58-11e7-8cee-4d57fc523704.png)
### Example: Convert a String to Date Format in USA Date Style
`SELECT CONVERT(DATE, '20171030' , 110) To_USA_DateFormat`
![convert a string to date format in usa date style](https://user-images.githubusercontent.com/12566249/31314937-35155d06-ac58-11e7-9d5d-823b66c41d0d.png)
### More Information:
- Information on Convert function: <a href='https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql' target='_blank' rel='nofollow'>Microsoft</a>

View File

@ -0,0 +1,47 @@
---
title: SQL Sum Function
---
## SQL Sum Function
This is one of the aggregate functions (as is count, average, max, min, etc.). They are used in a GROUP BY clause as it aggregates data presented by the SELECT FROM WHERE portion of the statement.
### Example of use
"sum(Total_$)" in the SELECT statement is aggregated in the GROUP BY clause. "Count(\*)" provides the number of contributions.
This data is from the campaign contributions data we've been using in some of these guides.
This SQL statement is answering the question: "which candidates received the largest total contribution dollars in 2016 BUT only those that had more than $20 Million USD for all contributions combined?"
Ordering this data set in a descending (DESC) order places the candidates with the largest total contributions at the top of the list.
```sql
SELECT Candidate, Election_year, sum(Total_$), count(*)
FROM combined_party_data
WHERE Election_year = 2016
GROUP BY Candidate, Election_year -- this tells the DBMS to summarize by these two columns
HAVING sum(Total_$) > 20000000 -- limits the rows presented from the summary of money ($20 Million USD)
ORDER BY sum(Total_$) DESC; -- orders the presented rows with the largest ones first.
```
```text
+--------------------------------------------------+---------------+-------------------+----------+
| Candidate | Election_year | sum(Total_$) | count(*) |
+--------------------------------------------------+---------------+-------------------+----------+
| CLINTON, HILLARY RODHAM & KAINE, TIMOTHY M (TIM) | 2016 | 568135094.4400003 | 126 |
| TRUMP, DONALD J & PENCE, MICHAEL R (MIKE) | 2016 | 366853142.7899999 | 114 |
| SANDERS, BERNARD (BERNIE) | 2016 | 258562022.17 | 122 |
| CRUZ, RAFAEL EDWARD (TED) | 2016 | 93430700.29000005 | 104 |
| CARSON, BENJAMIN S (BEN) | 2016 | 62202411.12999996 | 93 |
| RUBIO, MARCO ANTONIO | 2016 | 44384313.9 | 106 |
| BUSH, JOHN ELLIS (JEB) | 2016 | 34606731.78 | 97 |
+--------------------------------------------------+---------------+-------------------+----------+
7 rows in set (0.01 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,110 @@
---
title: SQL Syntax
---
## SQL Syntax
### Introduction
This guide provides a basic, high level description of the syntax for SQL statements.
SQL is an international standard (ISO), but you will find many differences between implementations. This guide uses MySQL as an example. If you use one of the many other Relational Database Managers (DBMS) you'll need to check the manual for that DBMS if needed.
### What we will cover
* Use (sets what database the statement will use)
* Select and From clauses
* Where Clause (and / or, IN, Between, LIKE)
* Order By (ASC, DESC)
* Group by and Having
### How to use this
This is used to select the database containing the tables for your SQL statements:
```sql
use fcc_sql_guides_database; -- select the guide sample database
```
### Select and From clauses
The Select part is normally used to determine which columns of the data you want to show in the results. There are also options you can use to show data that is not a table column.
This example shows two columns selected from the "student" table, and two calculated columns. The first of the calculated columns is a meaningless number, and the other is the system date.
```sql
select studentID, FullName, 3+2 as five, now() as currentDate
from student;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/syntax01.JPG)
### Where Clause (and / or, IN, Between and LIKE)
The WHERE clause is used to limit the number of rows returned.
In this case all five of these will be used is a somewhat ridiculous Where clause.
Compare this result to the above SQL statement to follow this logic.
Rows will be presented that:
* Have Student IDs between 1 and 5 (inclusive)
* or studentID = 8
* or have "Maxmimo" in the name
The following example is similar, but it further specifies that if any of the students have certain SAT scores (1000, 1400), they will not be presented:
```sql
select studentID, FullName, sat_score, recordUpdated
from student
where (
studentID between 1 and 5
or studentID = 8
or FullName like '%Maximo%'
)
and sat_score NOT in (1000, 1400);
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/syntax02.JPG)
### Order By (ASC, DESC)
Order By gives us a way to sort the result set by one or more of the items in the SELECT section. Here is the same list as above, but sorted by the students Full Name. The default sort order is ascending (ASC), but to sort in the opposite order (descending) you use DESC, as in the example below:
```sql
select studentID, FullName, sat_score
from student
where (studentID between 1 and 5 -- inclusive
or studentID = 8
or FullName like '%Maximo%')
and sat_score NOT in (1000, 1400)
order by FullName DESC;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/syntax03.JPG)
### Group By and Having
Group By gives us a way to combine rows and aggregate data. The Having clause is like the above Where clause, except that it acts on the grouped data.
This data is from the campaign contributions data we've been using in some of these guides.
This SQL statement answers the question: "which candidates recieved the largest number of contributions (not $ amount, but count (\*)) in 2016, but only those who had more than 80 contributions?"
Ordering this data set in a descending (DESC) order places the candidates with the largest number of contributions at the top of the list.
```sql
select Candidate, Election_year, sum(Total_$), count(*)
from combined_party_data
where Election_year = 2016
group by Candidate, Election_year
having count(*) > 80
order by count(*) DESC;
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/syntax04.JPG)
*As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide. I hope this at least gives you enough to get started. Please see the manual for your database manager and have fun trying different options yourself.*

View File

@ -0,0 +1,89 @@
---
title: SQL Union Operator
---
## SQL Union Operator
### Description
For this guide we'll discuss the UNION Operator section of the SQL statement.
The UNION Operator is used to combine the results of multiple select statements into one result set.
The SQL statements must have the same number of columns in their Select Statement.
### Basic Example
SQL Statement
```sql
SELECT 'aaaaa'
UNION
SELECT 'bbbbbbbbb';
```
Output
```text
+-----------+
| aaaaa |
+-----------+
| aaaaa |
| bbbbbbbbb |
+-----------+
2 rows in set (0.00 sec)
```
### Example using the student tables
SQL Statement
```sql
SELECT StudentID, FullName FROM student WHERE studentID BETWEEN 1 AND 5
UNION
SELECT studentID, studentEmailAddr FROM `student-contact-info` WHERE studentID BETWEEN 7 AND 8;
```
Output
``` text
+-----------+--------------------------------+
| StudentID | FullName |
+-----------+--------------------------------+
| 1 | Monique Davis |
| 2 | Teri Gutierrez |
| 3 | Spencer Pautier |
| 4 | Louis Ramsey |
| 5 | Alvin Greene |
| 7 | Maximo.Smith@freeCodeCamp.org |
| 8 | Michael.Roach@freeCodeCamp.ort |
+-----------+--------------------------------+
7 rows in set (0.00 sec)
```
## SQL UNION ALL Operator
The UNION ALL operator is an extension to UNION operator where it should result you a A+B of rows in the ouptput assuming A and B is your input, in simple terms UNION ALL doesn't deduplicate.
### Basic Syntax
SQL Statement
```sql
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
UNION ALL
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,121 @@
---
title: SQL Update Query
---
## SQL Update Query
### What an Update query can do
An update query gives the DBA or SQL-using programmer the ability to update many records with one command.
Important Safety Tip! Always have a backup copy of what you are about to change BEFORE you change it!
This guide will:
* add a new field to the student table
* test the logic to update that field with a school assigned email address
* update the new field.
Here is the student table as we start this process
```sql
SELECT * FROM student;
```
```text
+-----------+------------------------+-----------+------------------+---------------------+---------------------+
| studentID | FullName | sat_score | programOfStudy | rcd_Created | rcd_Updated |
+-----------+------------------------+-----------+------------------+---------------------+---------------------+
| 1 | Monique Davis | 400 | Literature | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 3 | Spencer Pautier | 1000 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | Programming | 2017-08-16 15:34:50 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | Computer Science | 2017-08-16 15:35:33 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | Computer Science | 2017-08-16 15:35:33 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | Computer Science | 2017-08-16 15:35:33 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+------------------+---------------------+---------------------+
9 rows in set (0.00 sec)
```
### Alter the table and add a new field
```sql
ALTER TABLE `fcc_sql_guides_database`.`student`
ADD COLUMN `schoolEmailAdr` VARCHAR(125) NULL AFTER `programOfStudy`;
```
The student table after the alter is executed.
```text
mysql> SELECT FullName, sat_score, programOfStudy, schoolEmailAdr FROM student;
+------------------------+-----------+------------------+----------------+
| FullName | sat_score | programOfStudy | schoolEmailAdr |
+------------------------+-----------+------------------+----------------+
| Monique Davis | 400 | Literature | NULL |
| Teri Gutierrez | 800 | Programming | NULL |
| Spencer Pautier | 1000 | Programming | NULL |
| Louis Ramsey | 1200 | Programming | NULL |
| Alvin Greene | 1200 | Programming | NULL |
| Sophie Freeman | 1200 | Programming | NULL |
| Edgar Frank "Ted" Codd | 2400 | Computer Science | NULL |
| Donald D. Chamberlin | 2400 | Computer Science | NULL |
| Raymond F. Boyce | 2400 | Computer Science | NULL |
+------------------------+-----------+------------------+----------------+
9 rows in set (0.00 sec)
```
### TESTING the logic (VERY important step!)
```sql
SELECT FullName, instr(FullName," ") AS firstSpacePosition,
concat(substring(FullName,1,instr(FullName," ")-1),"@someSchool.edu") AS schoolEmail
FROM student;
```
```text
+------------------------+--------------------+------------------------+
| FullName | firstSpacePosition | schoolEmail |
+------------------------+--------------------+------------------------+
| Monique Davis | 8 | Monique@someSchool.edu |
| Teri Gutierrez | 5 | Teri@someSchool.edu |
| Spencer Pautier | 8 | Spencer@someSchool.edu |
| Louis Ramsey | 6 | Louis@someSchool.edu |
| Alvin Greene | 6 | Alvin@someSchool.edu |
| Sophie Freeman | 7 | Sophie@someSchool.edu |
| Edgar Frank "Ted" Codd | 6 | Edgar@someSchool.edu |
| Donald D. Chamberlin | 7 | Donald@someSchool.edu |
| Raymond F. Boyce | 8 | Raymond@someSchool.edu |
+------------------------+--------------------+------------------------+
9 rows in set (0.00 sec)
```
*A note about concat(): in MySQL this command is used to combined strings, not so in other SQL versions (check your manual). In this usage it works like this: The substring of the FullName field up to but not including the first space is combined with "@someSchool.edu". In the real world this would HAVE TO be much more complex and you would need to ensure that the email address is unique.*
### Doing the update
We'll pretend that this is what we want and update the table with this information:
```sql
UPDATE student SET schoolEmailAdr = concat(substring(FullName,1,instr(FullName," ")-1),"@someSchool.edu")
WHERE schoolEmailAdr is NULL;
```
Success!
```text
mysql> SELECT FullName, sat_score, programOfStudy, schoolEmailAdr FROM student;
+------------------------+-----------+------------------+------------------------+
| FullName | sat_score | programOfStudy | schoolEmailAdr |
+------------------------+-----------+------------------+------------------------+
| Monique Davis | 400 | Literature | Monique@someSchool.edu |
| Teri Gutierrez | 800 | Programming | Teri@someSchool.edu |
| Spencer Pautier | 1000 | Programming | Spencer@someSchool.edu |
| Louis Ramsey | 1200 | Programming | Louis@someSchool.edu |
| Alvin Greene | 1200 | Programming | Alvin@someSchool.edu |
| Sophie Freeman | 1200 | Programming | Sophie@someSchool.edu |
| Edgar Frank "Ted" Codd | 2400 | Computer Science | Edgar@someSchool.edu |
| Donald D. Chamberlin | 2400 | Computer Science | Donald@someSchool.edu |
| Raymond F. Boyce | 2400 | Computer Science | Raymond@someSchool.edu |
+------------------------+-----------+------------------+------------------------+
9 rows in set (0.00 sec)
```
As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.

View File

@ -0,0 +1,42 @@
---
title: SQL Update Statement
---
## SQL Update Statement
To update a record in a table you use the `UPDATE` statement.
Be careful. You can update all records of the table or just a few. Use the `WHERE` condition to specify which records do you want to update. It is possible to update one or more columns at a time. The syntax is:
```sql
UPDATE table_name
SET column1 = value1,
column2 = value2, ...
WHERE condition;
```
Here is an example updating the Name of the record with Id 4:
```sql
UPDATE Person
SET Name = Elton John
WHERE Id = 4;
```
You can also update columns in a table by using values from other tables. Use `JOIN` clause to get data from multiple tables. The syntax is:
```sql
UPDATE table_name1
SET table_name1.column1 = table_name2.columnA
table_name1.column2 = table_name2.columnB
FROM table_name1
JOIN table_name2 ON table_name1.ForeignKey = table_name2.Key
```
Here is an example updating Manager of all records:
```sql
UPDATE Person
SET Person.Manager = Department.Manager
FROM Person
JOIN Department ON Person.DepartmentID = Department.ID
```

View File

@ -0,0 +1,69 @@
---
title: SQL Where Clause
---
## SQL Where Clause
### `WHERE` Clause (and/or, `IN`, `BETWEEN`, and `LIKE`)
The `WHERE` clause is used to limit the number of rows returned.
In this case all five of these will be used is a some what ridiculous `WHERE` clause.
Here is the current full student list to compare to the `WHERE` clause result set:
```sql
select studentID, FullName, sat_score, rcd_updated from student;
```
```text
+-----------+------------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+------------------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 |
| 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 |
| 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
| 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+---------------------+
9 rows in set (0.00 sec)
```
Rows will be presented that....
* `WHERE` Student IDs are between 1 and 5 (inclusive)
* `OR` studentID = 8
Here's an updated query, where any record that has an SAT score that's in this list (1000, 1400) will not be presented:
```sql
select studentID, FullName, sat_score, recordUpdated
from student
where (studentID between 1 and 5 or studentID = 8)
and
sat_score NOT in (1000, 1400);
```
```text
+-----------+----------------------+-----------+---------------------+
| studentID | FullName | sat_score | rcd_updated |
+-----------+----------------------+-----------+---------------------+
| 1 | Monique Davis | 400 | 2017-08-16 15:34:50 |
| 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 |
| 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 |
| 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 |
| 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 |
+-----------+----------------------+-----------+---------------------+
5 rows in set (0.00 sec)
```
*As with all of these SQL things there is MUCH MORE to them than what's in this introductory guide.
I hope this at least gives you enough to get started.
Please see the manual for your database manager and have fun trying different options yourself.