Removed images and added text tables (#35900)

This commit is contained in:
Uma Sankar
2019-06-28 12:51:21 +05:30
committed by Randell Dawson
parent b18560f8d6
commit 1f6b3c082d
13 changed files with 884 additions and 366 deletions

View File

@ -6,40 +6,164 @@ title: SQL Alter Table Statement
## 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.
ALTER TABLE statement is used to add, remove, change datatype or rename columns. It can be also used to add or remove the constraints of the table.**IMPORTANT Safety Tip: ALWAYS backup your data before making changes!**
ALTER TABLE statement is used to add, remove, change datatype or rename columns. It can be also used to add or remove the constraints of the table.
**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.
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.
* Adding a new column
* Change column name
* Change column definition
* Remove a Column
* Rename the Table
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)
## Alter Table:
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:
We will use the student table created in the “CREATE TABLE” guide.
To view all column names and their description of student Table, we will use below command through out this guide.
```sql
ALTER TABLE table_name DROP COLUMN column_name;
```
desc student;
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)
```
Result :
```text
+--------------------+----------------------+--------------+-------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+-------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| studentIO | NULL | YES | int(3) | |
| sat_score | NULL | YES | int(4) | |
| timeStampA | CURRENT TIMESTAMP | NO | timestamp | |
| timeStampB | 0000-00-00 00:00:00 | NO | timestamp | |
+--------------------+----------------------+--------------+-------------+------------+
```
* Adding a new column :
Let's add a new column, emailAddress.
```sql
alter table student add column emailAddress varchar(30) NULL ;
```
Result :
```sql
desc student;
```
```text
+--------------------+----------------------+--------------+-------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+-------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| studentIO | NULL | YES | int(3) | |
| sat_score | NULL | YES | int(4) | |
| timeStampA | CURRENT TIMESTAMP | NO | timestamp | |
| timeStampB | 0000-00-00 00:00:00 | NO | timestamp | |
| emailAddress | NULL | YES | varchar(30) | |
+--------------------+----------------------+--------------+-------------+------------+
```
* Change column name :
Let's Change the column name sat_score to satScore .
```sql
alter table student change sat_score satScore int(4) NULL ;
```
Result :
```sql
desc student;
```
```text
+--------------------+----------------------+--------------+-------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+-------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| studentIO | NULL | YES | int(3) | |
| satScore | NULL | YES | int(4) | |
| timeStampA | CURRENT TIMESTAMP | NO | timestamp | |
| timeStampB | 0000-00-00 00:00:00 | NO | timestamp | |
| emailAddress | NULL | YES | varchar(30) | |
+--------------------+----------------------+--------------+-------------+------------+
```
* Change column definition :
Let's Change the emailAddress field size from varchar(30) to varchar(50).
```sql
alter table student change emailAddress emailAddress varchar(50) NULL ;
```
Result :
```sql
desc student;
```
```text
+--------------------+----------------------+--------------+-------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+-------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| studentIO | NULL | YES | int(3) | |
| satScore | NULL | YES | int(4) | |
| timeStampA | CURRENT TIMESTAMP | NO | timestamp | |
| timeStampB | 0000-00-00 00:00:00 | NO | timestamp | |
| emailAddress | NULL | YES | varchar(50) | |
+--------------------+----------------------+--------------+-------------+------------+
```
* Remove a Column :
Let's remove emailAddress column which we added earlier.
```sql
alter table student drop column emailAddress ;
```
Result :
```sql
desc student;
```
```text
+--------------------+----------------------+--------------+-------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+-------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| studentIO | NULL | YES | int(3) | |
| satScore | NULL | YES | int(4) | |
| timeStampA | CURRENT TIMESTAMP | NO | timestamp | |
| timeStampB | 0000-00-00 00:00:00 | NO | timestamp | |
+--------------------+----------------------+--------------+-------------+------------+
```
* Rename the Table :
Let's rename the table student to students.
```sql
alter table student rename to students ;
```
Result :
we can also use describe command (alternative to desc) to see table description.
```sql
describe students
```
```text
+--------------------+----------------------+--------------+-------------+------------+
| column_name | column_default | is_nullable | column_type | column_key |
+--------------------+----------------------+--------------+-------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| studentIO | NULL | YES | int(3) | |
| satScore | NULL | YES | int(4) | |
| timeStampA | CURRENT TIMESTAMP | NO | timestamp | |
| timeStampB | 0000-00-00 00:00:00 | NO | timestamp | |
+--------------------+----------------------+--------------+-------------+------------+
```
There is much more that can be done, check the manual of your database management software to learn more.

View File

@ -7,40 +7,80 @@ AND is used in a WHERE clause or a GROUP BY HAVING clause to limit the rows retu
We'll use the student table to present examples.
Here's the student table without a WHERE clause:
```sql
select * from student;
```
* Here's the student table without a WHERE clause:
```sql
select * from student;
```
Result :
```text
+-----------+------------------+----------------+-----------+
| studentID | FullName | programOfStudy | sat_score |
+-----------+------------------+----------------+-----------+
| 1 | Monique Davis | Literature | 400 |
| 2 | Teri Gutierrez | Programming | 800 |
| 3 | Spencer Pautier | Programming | 1000 |
| 4 | Louis Ramsey | Programming | 1200 |
| 5 | Alvin Greene | Photography | 1400 |
| 6 | Sophie Freeman | Photography | 1600 |
| 7 | Maximo Smith | Photography | 1800 |
| 8 | Michael Roach | Literature | 800 |
+-----------+------------------+----------------+-----------+
```
![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:
Now the WHERE clause is added to display only programming students:
```sql
select * from student
where programOfStudy = 'Programming';
```
Result :
```text
+-----------+------------------+----------------+-----------+
| studentID | FullName | programOfStudy | sat_score |
+-----------+------------------+----------------+-----------+
| 2 | Teri Gutierrez | Programming | 800 |
| 3 | Spencer Pautier | Programming | 1000 |
| 4 | Louis Ramsey | Programming | 1200 |
+-----------+------------------+----------------+-----------+
```
```sql
select * from student
where programOfStudy = 'Programming';
```
* Now the WHERE clause is updated with AND to show results for programming students that also have a SAT score greater than 800:
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/and_operator02.JPG?raw=true)
```sql
select * from student
where programOfStudy = 'Programming'
and sat_score > 800;
```
Result :
```text
+-----------+------------------+----------------+-----------+
| studentID | FullName | programOfStudy | sat_score |
+-----------+------------------+----------------+-----------+
| 3 | Spencer Pautier | Programming | 1000 |
| 4 | Louis Ramsey | Programming | 1200 |
+-----------+------------------+----------------+-----------+
```
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 a HAVING clause using an AND to restrict the returned records to candidates 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
* This is a more complex example from the campaign contributions table. This example has a GROUP BY clause with a HAVING clause using an AND to restrict the returned records to candidates 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)
order by sum(Total_$) desc;
```
Result :
```text
+---------------------------------+----------------------------+---------------+------------------------+
| Candidate | office_Sought | Election_Year | format(sum(Total_$),2) |
+---------------------------------+----------------------------+---------------+------------------------+
| FLORINA. CARLY | PRESIDENT / VICE PRESIDENT | 2016 | 11,937,638.11 |
| PAUL. RANDAL (RAND) | PRESIDENT / VICE PRESIDENT | 2016 | 11,833,950.07 |
| CHRISTIE. CHRISTOPHER J (CHRIS) | PRESIDENT / VICE PRESIDENT | 2016 | 8,450,767.64 |
| WALKER. SCOTT K | PRESIDENT / VICE PRESIDENT | 2016 | 8,067,461.71 |
| GRAHAM. LINDSEY OLIN | PRESIDENT / VICE PRESIDENT | 2016 | 7,292,173.80 |
| OMALLEY. MARTIN JOSEPH | PRESIDENT / VICE PRESIDENT | 2016 | 5,669,814.82 |
| HUCKABEE. MIKE D | PRESIDENT / VICE PRESIDENT | 2016 | 3,064,303.84 |
+---------------------------------+----------------------------+---------------+------------------------+
```

View File

@ -13,13 +13,26 @@ from table1
group by groupingField
```
Here's an example using the student table:
* Here's an example using the student table:
```sql
select studentID, FullName, avg(sat_score)
from student
group by studentID, FullName;
```
```sql
select studentID, FullName, avg(sat_score)
from student
group by studentID, FullName;
```
Result :
```text
+-----------+------------------+----------------+
| studentID | FullName | avg(sat_score) |
+-----------+------------------+----------------+
| 1 | Monique Davis | 400.0000 |
| 2 | Teri Gutierrez | 800.0000 |
| 3 | Spencer Pautier | 1000.0000 |
| 4 | Louis Ramsey | 1200.0000 |
| 5 | Alvin Greene | 1400.0000 |
| 6 | Sophie Freeman | 1600.0000 |
| 7 | Maximo Smith | 1800.0000 |
+-----------+------------------+----------------+
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/avg_function01.JPG?raw=true)
```

View File

@ -20,32 +20,70 @@ from table1
where testField between min and max
```
Here is an example using the student table and the WHERE clause:
* Here is an example using the student table and the WHERE clause:
```sql
-- no WHERE clause
select studentID, FullName, studentID
from student;
```sql
-- no WHERE clause
select studentID, FullName, studentID
from student;
```
Result :
```text
+-----------+------------------+-----------+
| studentID | FullName | studentID |
+-----------+------------------+-----------+
| 1 | Monique Davis | 1 |
| 2 | Teri Gutierrez | 2 |
| 3 | Spencer Pautier | 3 |
| 4 | Louis Ramsey | 4 |
| 5 | Alvin Greene | 5 |
| 6 | Sophie Freeman | 6 |
| 7 | Maximo Smith | 7 |
+-----------+------------------+-----------+
```
```sql
-- WHERE clause with between
select studentID, FullName, studentID
from student
where studentID between 2 and 7;
```
Result :
```text
+-----------+------------------+-----------+
| studentID | FullName | studentID |
+-----------+------------------+-----------+
| 2 | Teri Gutierrez | 2 |
| 3 | Spencer Pautier | 3 |
| 4 | Louis Ramsey | 4 |
| 5 | Alvin Greene | 5 |
| 6 | Sophie Freeman | 6 |
| 7 | Maximo Smith | 7 |
+-----------+------------------+-----------+
```
-- 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.
* 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)
```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;
```
Result :
```text
+---------------------------------+----------------------------+---------------+------------------------+
| Candidate | office_Sought | Election_Year | format(sum(Total_$),2) |
+---------------------------------+----------------------------+---------------+------------------------+
| FLORINA. CARLY | PRESIDENT / VICE PRESIDENT | 2016 | 11,937,638.11 |
| PAUL. RANDAL (RAND) | PRESIDENT / VICE PRESIDENT | 2016 | 11,833,950.07 |
| CHRISTIE. CHRISTOPHER J (CHRIS) | PRESIDENT / VICE PRESIDENT | 2016 | 8,450,767.64 |
| WALKER. SCOTT K | PRESIDENT / VICE PRESIDENT | 2016 | 8,067,461.71 |
| GRAHAM. LINDSEY OLIN | PRESIDENT / VICE PRESIDENT | 2016 | 7,292,173.80 |
| OMALLEY. MARTIN JOSEPH | PRESIDENT / VICE PRESIDENT | 2016 | 5,669,814.82 |
| HUCKABEE. MIKE D | PRESIDENT / VICE PRESIDENT | 2016 | 3,064,303.84 |
+---------------------------------+----------------------------+---------------+------------------------+
```

View File

@ -17,38 +17,92 @@ For reference, here is the current data for all the rows in our example student
```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
Result :
```text
+-----------+------------------+----------------+-----------+
| studentID | FullName | programOfStudy | sat_score |
+-----------+------------------+----------------+-----------+
| 1 | Monique Davis | Literature | 400 |
| 2 | Teri Gutierrez | Programming | 800 |
| 3 | Spencer Pautier | Programming | 1000 |
| 4 | Louis Ramsey | Programming | 1200 |
| 5 | Alvin Greene | Photography | 1400 |
| 6 | Sophie Freeman | Photography | 1600 |
| 7 | Maximo Smith | Photography | 1800 |
| 8 | Michael Roach | Literature | 800 |
+-----------+------------------+----------------+-----------+
```
![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.
* This SQL statement provides a count of all rows. Note that you can give the resulting COUNT column a name using "AS".
```sql
```sql
select count(*) AS studentCount from student; -- count of all records
```
Result :
```text
+--------------+
| studentCount |
+--------------+
| 8 |
+--------------+
```
* 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)
```
Result :
```text
+----------------+--------------+
| programOfStudy | studentCount |
+----------------+--------------+
| Literature | 2 |
| photography | 3 |
| programming | 3 |
+----------------+--------------+
Here we get a count of students with the same SAT scores.
```sql
```
* 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)
```
Result :
```text
+-----------+--------------+
| sat_score | studentCount |
+-----------+--------------+
| 400 | 1 |
| 800 | 2 |
| 1000 | 1 |
| 1200 | 1 |
| 1400 | 1 |
| 1600 | 1 |
| 1800 | 1 |
+-----------+--------------+
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;
```
* 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;
```
Result :
```text
+----------------+---------------+--------------------+-----------------------+
| Specific_Party | Election_Year | contribution$Total | numberOfContributions |
+----------------+---------------+--------------------+-----------------------+
| DEMOCRATIC | 2016 | 833,592,846.09 | 361 |
| REPUBLICAN | 2016 | 676,149,662.07 | 1247 |
+----------------+---------------+--------------------+-----------------------+
```
![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

@ -23,16 +23,38 @@ 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);
```text
+--------------------+----------------------+--------------+---------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+---------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| sat_score | NULL | YEs | int(4) | |
| recordUpdated | CURRENT TIMESTAMP | NO | timestamp | |
| recordCreated | 0000-00-00 00:00:00 | NO | timestamp | |
| programOfStudy | NULL | YES | varchar(200) | |
+--------------------+----------------------+--------------+---------------+------------+
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create-index-statement02.JPG?raw=true)
* Here's a statement to create the index, and below is the updated table definition:
```sql
create index pStudyIndex
on student (programOfStudy);
```
```text
+--------------------+----------------------+--------------+---------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+---------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| sat_score | NULL | YEs | int(4) | |
| recordUpdated | CURRENT TIMESTAMP | NO | timestamp | |
| recordCreated | 0000-00-00 00:00:00 | NO | timestamp | |
| programOfStudy | NULL | YES | varchar(200) | MUL |
+--------------------+----------------------+--------------+---------------+------------+
```
In MySQL, you use the ALTER TABLE command to change and drop indexes. The MySQL Workbench also provides GUI tools to manage indexes.

View File

@ -24,98 +24,83 @@ We do most of this work with SQL statements in the MySQL workbench scripting too
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;
```
```sql
create database fCC_alterTableGuide;
```
This instances schema structure prior to running this command
* ## Creating a table, add test data with "insert".
![image-2](https://github.com/SteveChevalier/guide-images/blob/master/create_table02.JPG?raw=true)
Well create a Student Table.
This instances schema structure after running the SQL statement
The steps will be:
![image-3](https://github.com/SteveChevalier/guide-images/blob/master/create_table03.JPG?raw=true)
1. make sure we dont have the table already
2. create the table
3. insert the test data.
## Creating a table, add test data with "insert", rename the table (alter)
Data Types: the student name is a character field limited to 90 characters. <br/>
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.<br/>
There will also be two "time-stamp" fields to play with as well.
Well create a Student Table.
Let's create a student table statement.
The steps will be:
```sql
create table student(
studentId int(11) not null primary key ,
FullName varchar(90),
sat_score int(4),
ts1 timestamp,
ts2 timestamp default current_timestamp,
programOfStudy varchar(200)
);
```
1. make sure we dont have the table already
Now to insert some data and see what our new table looks like with records in it.
```sql
insert into student(studentId, FullName,sat_score,ts1,ts2,programOfStudy)
values(1, "Lorah sey", 400 ,now(),now(),"programming");
--to display records in table
select * from student;
```
Result :
```text
+-----------+----------------+-----------+---------------------+----------------------+----------------+
| studentId | FullName | sat_score | ts1 | ts2 | programOfStudy |
+-----------+----------------+-----------+---------------------+----------------------+----------------+
| 1 | Lorah sey | 400 | 2019-04-28 13:55:11 | 2019-04-28 13:55:11 | programming |
+-----------+----------------+-----------+---------------------+----------------------+----------------+
```
* ## 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.
* Complete the form as desired and click Apply
2. create the table
3. insert the test data.
* ## Create Table as Select (CTAS)
* 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
A quick way to create a copy of a table, including data is to create table as select.
```sql
CREATE TABLE my_table as (SELECT * FROM orig_tbl);
```
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)
* ## 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.
* 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.
* Adjust the data types as needed and click NEXT
* Click NEXT to import the data into the table
* Youll see completion status, review and click FINISH
## Other Material

View File

@ -40,36 +40,54 @@ CREATE
AS select_statement
```
### Sample View creation from the student tables
* ### Sample View creation from the student tables :
Notes:
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 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 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.
* 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';
```sql
create view `programming-students-v` as
select FullName, programOfStudy
from student
where programOfStudy = 'Programming';
select * from `programming-students-v`;
```
select * from `programming-students-v`;
```
Result :
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/create-view-statement01.JPG?raw=true)
```text
+------------------------+------------------+
| FullName | programOfStudy |
+------------------------+------------------+
| Teri Gutierrez | Programming |
| Spencer Pautier | Programming |
| Louis Ramsey | Programming |
| Alvin Greene | Programming |
| Sophie Freeman | Programming |
+------------------------+------------------+
```
### Sample of using a View to combine data from more than one table
* ### 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.
A Student demographics table was added to the database to demonstrate this usage. This view will combine these tables.
Notes:
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.
* 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.)
```sql
CREATE VIEW View_name AS
SELECT Table1_name.Column1_name , Table1_name.Column2_name , Table2_name.Column1_name ,
Table1_name.Column2_name
FROM Table1 , Table2
WHERE Table1_name.Column1_name = Table2_name.Column1_name;
```
![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

@ -12,57 +12,114 @@ We will cover:
* Date Math
* Dates in a where or having clause
### Getting the current date
### Let's Get Started :
* ### Getting the current date :
Getting the date from the system can be very handy for processing data using SQL.
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;
;
```
```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;
;
```
Result :
```text
+--------------------+----------------------+
| now() | 2019-04-27 18:06:48 |
| sysdate() | 2019-04-27 18:06:48 |
| current_date() | 2019-04-27 |
| current_time() | 18:06:48 |
| NumDaysSoFarThisYr | 117 |
| theYearPart | 2019 |
| theYrMonPart | 201904 |
| oneOfManyFormats | Saturday April 2019 |
+--------------------+----------------------+
```
![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.
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 :
### 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
;
```
```text
+------------------+----------------------+
| now() | 2019-04-27 18:19:59 |
| current_date() | 2019-04-27 |
| daysThisYear | 846 |
| 150DaysAgo | 2018-11-28 |
| dateInA_Week | 2019-05-04 18:19:59 |
+------------------+----------------------+
```
```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
;
```
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.
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/date-functions02.jpg)
* ### In a where or having clause :
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.
Here are two examples of using date math in a where clause:
### In a where or having clause
```sql
select * from student; - to show the current data being used for the example
select * from student where recordCreated < '2017-08-14';
select * from student where recordCreated < subdate(current_date(), interval 628 day);
```
Result :
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)
```text
+------------+---------------------+-----------+---------------+
| studentID | FullName | sat_score | recordCreated |
+------------+---------------------+-----------+---------------+
| 1 | Jon snow | 200 | 2017-08-03 |
| 2 | Stan Lee | 900 | 2017-08-05 |
| 3 | Vincent Uvalle | 400 | 2017-08-07 |
| 4 | Merle Veres | 800 | 2017-08-07 |
| 5 | Donte Emmons | 1000 | 2017-08-07 |
| 6 | Demetrius Mccaster | 1200 | 2017-08-07 |
| 7 | Tim Goudy | 1400 | 2017-08-07 |
| 8 | Stephan Monfort | 1600 | 2017-08-07 |
| 9 | Maximo Backstrom | 1800 | 2017-08-14 |
| 10 | Dean Pickel | 800 | 2017-08-14 |
+------------+---------------------+-----------+---------------+
```
```text
+------------+---------------------+-----------+---------------+
| studentID | FullName | sat_score | recordCreated |
+------------+---------------------+-----------+---------------+
| 1 | Jon snow | 200 | 2017-08-03 |
| 2 | Stan Lee | 900 | 2017-08-05 |
| 3 | Vincent Uvalle | 400 | 2017-08-07 |
| 4 | Merle Veres | 800 | 2017-08-07 |
| 5 | Donte Emmons | 1000 | 2017-08-07 |
| 6 | Demetrius Mccaster | 1200 | 2017-08-07 |
| 7 | Tim Goudy | 1400 | 2017-08-07 |
| 8 | Stephan Monfort | 1600 | 2017-08-07 |
+------------+---------------------+-----------+---------------+
```
```text
+------------+---------------------+-----------+---------------+
| studentID | FullName | sat_score | recordCreated |
+------------+---------------------+-----------+---------------+
| 1 | Jon snow | 200 | 2017-08-03 |
| 2 | Stan Lee | 900 | 2017-08-05 |
+------------+---------------------+-----------+---------------+
```
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.

View File

@ -18,12 +18,53 @@ We will cover:
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.
we'll use student table in this tutorial.
```sql
select studentID,FullName,sat_score from student;
```
Result :
```text
+------------+---------------------+-----------+
| studentID | FullName | sat_score |
+------------+---------------------+-----------+
| 1 | Vincent Uvalle | 400 |
| 2 | Merle Veres | 800 |
| 3 | Donte Emmons | 1000 |
| 4 | Demetrius Mccaster | 1200 |
| 5 | Tim Goudy | 1400 |
| 6 | Stephan Monfort | 1600 |
| 7 | Maximo Backstrom | 1800 |
| 8 | Dean Pickel | 200 |
+------------+---------------------+-----------+
```
First of all let's create a view.
```sql
create view [Failures] AS
select studentID, FullName , sat_score
from student
where sat_score <= 400;
```
Let's see what Failures view consists of
```sql
select * from [Failures]
```
Result :
```text
+------------+---------------------+-----------+
| studentID | FullName | sat_score |
+------------+---------------------+-----------+
| 1 | Vincent Uvalle | 400 |
| 8 | Dean Pickel | 200 |
+------------+---------------------+-----------+
```
### Basic Syntax
```sql
DROP VIEW [IF EXISTS]
drop view [IF EXISTS]
view_name [, view_name] ...
```
@ -32,16 +73,12 @@ DROP VIEW [IF EXISTS]
The if exists portion will "trap" errors, should the view not exist.
```sql
drop view if exists students_dropMe_v;
drop view if exists [Failures];
```
Result :
```text
Failures table dropped successfully.
```
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
@ -50,19 +87,7 @@ From the workbench:
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

@ -5,7 +5,10 @@ title: 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)`
```sql
CREATE TABLE example_table ( name varchar(255), age int)
```
**example_table**
@ -14,7 +17,10 @@ Insert queries are a way to insert data into a table. Let's say we have created
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)`
```sql
INSERT INTO example_table (column1,column2) VALUES ("Andrew",23)
```
**example_table**
@ -24,7 +30,10 @@ Now to add some data to this table , we'll use **INSERT** in the following way:
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)`
```sql
INSERT INTO table_name VALUES ("John", 28)
```
**example_table**

View File

@ -4,39 +4,105 @@ 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_)`
### Covered in this guide :
* Convert a decimal number to an integer
* Convert a string to date
* Convert a decimal number into string
* Convert an integer number to decimal
* convert a string to date in usa format 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
### Convert command Syntax
### Example: Convert a Decimal Number to An Integer
```sql
CONVERT (_New Data Type, Expression, Style_)
`SELECT CONVERT(INT, 23.456) as IntegerNumber`
```
**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\
* ### Convert a Decimal Number to An Integer :
```sql
SELECT CONVERT(INT, 23.456) as IntegerNumber
```
Result :
```text
+---+---------------+
| | IntegerNumber |
+---+---------------+
| 1 | 23 |
+---+---------------+
```
Note: The result is truncated.
* ### Convert a String to a Date :
```sql
SELECT CONVERT(DATE, '20161030') as Date
```
Result :
```text
+---+---------------+
| | Date |
+---+---------------+
| 1 | 2016-10-30 |
+---+---------------+
```
* ### Convert a Decimal to a String :
```sql
SELECT CONVERT(nvarchar, 20.123) as StringData
```
Result :
```text
+---+---------------+
| | StringData |
+---+---------------+
| 1 | 20.123 |
+---+---------------+
```
Note: The result is truncated.
* ### Convert an Integer Number to a Decimal Number :
```sql
SELECT CONVERT(DECIMAL (15,3), 13) as DecimalNumber
### Example: Convert a String to a Date
`SELECT CONVERT(DATE, '20161030') as Date`
```
Result :
```text
+---+---------------+
| | DecimalNumber |
+---+---------------+
| 1 | 13.000 |
+---+---------------+
```
* ### Convert a String to Date Format in USA Date Style :
```sql
SELECT CONVERT(DATE, '20171030' , 110) To_USA_DateFormat
```
Result :
```text
+---+-------------------+
| | To_USA_DateFormat |
+---+-------------------+
| 1 | 2017-10-30 |
+---+-------------------+
### Example: Convert a Decimal to a String
`SELECT CONVERT(nvarchar, 20.123) as StringData`
### Example: Convert an Integer Number to a Decimal Number
`SELECT CONVERT(DECIMAL (15,3), 13) as DecimalNumber`
### Example: Convert a String to Date Format in USA Date Style
`SELECT CONVERT(DATE, '20171030' , 110) To_USA_DateFormat`
```
### 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

@ -25,37 +25,71 @@ This is used to select the database containing the tables for your SQL statement
```sql
use fcc_sql_guides_database; -- select the guide sample database
```
### Select and From clauses
The Select clause 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.
In this tutorial we are using student table and it looks like this. To view table columns and its description we can use description or desc command.
```sql
select studentID, FullName, 3+2 as five, now() as currentDate
from student;
desc student;
```
Result :
```text
+--------------------+----------------------+--------------+---------------+------------+
| column_name | column_default | is_nullable | column_type | key |
+--------------------+----------------------+--------------+---------------+------------+
| studentID | NULL | NO | int(11) | PRI |
| FullName | NULL | YES | varchar(90) | |
| sat_score | NULL | YEs | int(4) | |
| recordUpdated | CURRENT TIMESTAMP | NO | timestamp | |
| recordCreated | 0000-00-00 00:00:00 | NO | timestamp | |
| programOfStudy | NULL | YES | varchar(200) | |
+--------------------+----------------------+--------------+---------------+------------+
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/syntax01.JPG)
* ### Select and From clauses :
The Select clause 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;
```
Result :
```text
+------------+---------------------+-----------+-----------------------+------+---------------------+
| studentID | FullName | sat_score | recordUpdated | five | currentDate |
+------------+---------------------+-----------+-----------------------+------+---------------------+
| 1 | Vincent Uvalle | 400 | 2017-08-07 15:38:12 | 5 | 2017-08-15 14:35:14 |
| 2 | Merle Veres   | 800 | 2017-08-07 15:26:19 | 5 | 2017-08-15 14:35:14 |
| 3 | Donte Emmons | 1000 | 2017-08-07 15:32:18 | 5 | 2017-08-15 14:35:14 |
| 4 | Demetrius Mccaster | 1200 | 2017-08-07 15:39:10 | 5 | 2017-08-15 14:35:14 |
| 5 | Tim Goudy | 1400 | 2017-08-07 15:45:19 | 5 | 2017-08-15 14:35:14 |
| 6 | Stephan Monfort | 1600 | 2017-08-07 15:03:12 | 5 | 2017-08-15 14:35:14 |
| 7 | Maximo Backstrom | 1800 | 2017-08-14 14:15:55 | 5 | 2017-08-15 14:35:14 |
| 8 | Dean Pickel   | 800 | 2017-08-14 14:25:32 | 5 | 2017-08-15 14:35:14 |
+------------+---------------------+-----------+-----------------------+------+---------------------+
```
### Where Clause (and / or, IN, Between and LIKE)
* ### Where Clause (and / or, IN, Between and LIKE) :
The WHERE clause is used to limit the number of rows returned.
The WHERE clause is used to limit the number of rows returned.
In this case all five of these will be used in a somewhat ridiculous Where clause.
In this case all five of these will be used in a somewhat ridiculous Where clause.
Compare this result to the above SQL statement to follow this logic.
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
Rows will be presented that:
* Have Student IDs between 1 and 5 (inclusive)
* or studentID = 8
* or have "Maximo" 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:
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
```sql
select studentID, FullName, sat_score, recordUpdated
from student
where (
@ -64,15 +98,26 @@ The following example is similar, but it further specifies that if any of the st
or FullName like '%Maximo%'
)
and sat_score NOT in (1000, 1400);
```
```
![image-1](https://github.com/SteveChevalier/guide-images/blob/master/syntax02.JPG)
Result :
```text
+------------+---------------------+-----------+-----------------------+
| studentID | FullName | sat_score | recordUpdated |
+------------+---------------------+-----------+-----------------------+
| 1 | Vincent Uvalle | 400 | 2017-08-07 15:38:12 |
| 2 | Merle Veres   | 800 | 2017-08-07 15:26:19 |
| 4 | Demetrius Mccaster | 1200 | 2017-08-07 15:39:10 |
| 7 | Maximo Backstrom | 1800 | 2017-08-14 14:15:55 |
| 8 | Dean Pickel   | 800 | 2017-08-14 14:25:32 |
+------------+---------------------+-----------+-----------------------+
```
### Order By (ASC, DESC)
* ### 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 student's 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:
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 student's 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
```sql
select studentID, FullName, sat_score
from student
where (studentID between 1 and 5 -- inclusive
@ -80,31 +125,53 @@ Order By gives us a way to sort the result set by one or more of the items in th
or FullName like '%Maximo%')
and sat_score NOT in (1000, 1400)
order by FullName DESC;
```
```
Result :
```text
+------------+---------------------+-----------+
| studentID | FullName | sat_score |
+------------+---------------------+-----------+
| 8 | Dean Pickel   | 800 |
| 4 | Demetrius Mccaster | 1200 |
| 2 | Merle Veres   | 800 |
| 7 | Maximo Backstrom | 1800 |
| 1 | Vincent Uvalle | 400 |
+------------+---------------------+-----------+
```
![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.
### Group By and Having
This data is from the campaign contributions dataset we've been using in some of these guides.
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 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?"
This data is from the campaign contributions dataset we've been using in some of these guides.
Ordering this data set in a descending (DESC) order places the candidates with the largest number of contributions at the top of the list.
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
```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)
```
Result :
```text
+--------------------------------------------+---------------+--------------------+----------+
| Candidate | Election_year | sum(Total_$) | count(*) |
+--------------------------------------------+---------------+--------------------+----------+
| CLINTON. HILLARY RODHAM & KAINE. TIMOTH... | 2016 | 568135094.4400003 | 126 |
| SANDERS. BERNARD (BERNIE) | 2016 | 258562022.17 | 122 |
| TRUMP. DONALD J & PENCE. MICHAEL R (MIKE) | 2016 | 366853142.7899999 | 114 |
| RUBIO. MARCO ANTONIO | 2016 | 44384313.9 | 106 |
| CRUZ. RAFAEL EDWARD (TED) | 2016 | 93430700.29000005 | 104 |
| KASICH. JOHN R | 2016 | 18842368.889999997 | 97 |
| BUSH. JOHN ELLIS (JEB) | 2016 | 34606731.78 | 97 |
| CARSON. BENJAMIN S (BEN) | 2016 | 62202411.12999996 | 93 |
+--------------------------------------------+---------------+--------------------+----------+
```
*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.*