Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Some "rules"
Download MySQL http://dev.mysql.com/downloads/mysql
Download the latest general availability release
Accept all the default settings (ex: port 3306; password: admin)
If you change the password from admin, please remember it (for this class, you are advised to leave it as admin)
Can do this via the command line client or using the GUI
For this class, we will use the GUI
Download the MySQL GUI http://dev.mysql.com/downloads/workbench/
Accept all the defaults
Open MySQL Workbench
Click on + sign to connect to an instance of MySQL
Download MySQL and MySQL workbench
Create a new connection to MySQL
Create a new connection to MySQL
A relational database consists of many different elements, some of which include:
Is a way to logically group database objects
Acts as a blueprint for how the database is constructed
In a relational database, the schema defines relationships, tables, fields in tables etc.
Default schema for many RDBMS is dbo
In a relational database, a table is an organized set of data using columns and rows.
You may sometimes hear a table referred to as a "relation".
Spend a few minutes exploring SSMS
Used for manipulating data
Used for defining data
Used for defining data
Used for defining data
SELECT columns FROM database
SELECT * FROM adventureworks.contact;
This will return all of the results from the table, which could be expensive. Don't use this in production!
DISTINCT keyword is used to return only distinct values, if there are duplicate values
Note:
Returns a subset of rows filtered on the set criteria in the WHERE clause
SELECT .. WHERE statement can be made on one line:
SELECT * FROM adventureworks.contact where FirstName = "Catherine";
Operator | Description |
= | Equal |
<> | Not equal. Note: In some versions of SQL, this may be written as != |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
BETWEEN | Between an inclusive range |
LIKE | Search for a pattern (can use a wildcard character) |
IN | To specify multiple possible values for a column |
SELECT * FROM adventureworks.contact WHERE FirstName <> "Catherine";
SELECT * FROM adventureworks.Employee WHERE BirthDate > "1970-01-01";
SELECT * FROM adventureworks.Employee WHERE BirthDate < "1970-01-01";
SELECT * FROM adventureworks.Employee WHERE BirthDate BETWEEN "1965-01-01" AND "1971-01-01";
Uses the wildcard character
SELECT * FROM adventureworks.Track WHERE Name LIKE "%Love%";
Can use the character at the beginning or end of the word/phrase
SELECT * FROM adventureworks.Track WHERE Name LIKE "%Lo";
SELECT * FROM adventureworks.currency WHERE CurrencyCode IN ('AFA', 'ZAR');
We will now learn to insert, update, and delete objects in a database!
INSERT INTO dbo.table1 VALUES x, y, z
INSERT INTO dbo.table1 SELECT col from dbo.table2
Note: If there is an identity or primary key column on a table, you should omit that column from your insert statement
INSERT INTO adventureworks.currency
VALUES ('PIP', 'Pippa', '2014-06-01 00:00:00');
Is used to update or change the value of columns in selected row(s) of data
Use WHERE Clause to define your set or row to update
UPDATE adventureworks.currency
SET Name = 'PippaNew'
WHERE CurrencyCode = 'PIP';
Is used to DELETE data from tables
Unlike TRUNCATE, DELETE is used when removing data based on a set of criteria
If all data should be removed from a table, TRUNCATE is a less expensive operation than DELETE
DELETE FROM adventureworks.currency
WHERE CurrencyCode = 'PIP';
Using the database you have created, practice inserting, updating and deleting records
Practice Problems
**Note: be aware of the data types you are inserting into the table!!
We will now learn to create, drop, truncate, and alter objects in a database!
Can use CREATE to create a database, tables, views, stored procedures, indexes etc. (objects of a db)
To create a table, we need to give the table a name and define the columns with a name and datatype
Defining primary and foriegn keys as well as constraints and default values is an option here
CREATE TABLE IF NOT EXISTS dbo.Students
(int ID,
varchar(20) FirstName,
varchar(20) LastName,
int BirthDate,
datetime ModifiedDate);
Used to delete an object from a database
Be very cuatious when using this command!
Cannot drop a table that does not exist, you will get an error
Can use IF EXISTS at the beginning of the statement
DROP TABLE dbo.Customers
Used to delete all the contents of object from a database
Again, be very cuatious when using this command!
TRUNCATE TABLE dbo.Customers
Used to alter an object in database
Not all objects can be altered, this can be vendor specific
If an object cannot be altered, you can drop and recreate the object with the changes needed
ALTER TABLE dbo.Students
ADD Age int
Types:
Limit the type of data that can be inserted into a table
Used as a unique indentifier for a row in a table
There is only one PK contraint allowed on a table
Can have more than one unique contraints
PK's become FK's when creating relations among tables
When creating a table:
When altering a table:
Points to a PK in another table
Enforces referential integrity
When creating a table:
When altering a table:
Ensures that all data in a column is unique
Primary key constraints automatically have unique constraints defined
When creating a table:
When altering a table:
A column with this type of constraint cannot containt NULL values
When creating a table:
Imposes a validation on the value being added or updated in a column
When creating a table
When altering a table
Inserts the specified default value when no column value is provided
Inserts the specified default value when the inserted or updated value meets a certain criteria
For example: If the value inserted is 0, default the column value to 1
When creating a table
When altering a table
Create a table of your choice
Be cognizant of the datatypes you give you columns
Bonus: Add a primary key constraint to your table during creation!
The SQL JOIN clause combines records from two or more tables in a database. You will primarly use two types of joins, with some variations on these.
Inner Joins
Outer Joins
Left and Right Joins
Cross Joins
Selects records that match Table A and Table B
Is the default join type in many RDBMS systems
SELECT p.ProductID, p.Name, p.ListPrice, sd.UnitPrice
FROM adventureworks.Product p
JOIN adventureworks.SalesOrderDetail sd ON p.ProductID = sd.ProductID
WHERE p.ProductID = 718;
Write a query, using an inner join, that returns the employee loginID, and addressID (Hint: you will use the employees and employeeaddress tables!)
Returns all sets of records in Table A and Table B
Records from both sides are included, where available.
If there is no matching record, the missing side will have a null value.
Produces all records from TableA, with matching records from TableB if they are available.
If there is no matching record in TableB, the right side will have a null value.
Data from a SELECT statement can be ordered with the ORDER BY clause.
Default ordering is ascending
Can explicitly add asc or desc
SELECT *
FROM adventureworks.Employee
ORDER BY BirthDate DESC
Data from a SELECT statement can be ordered with the ORDER BY clause.
Default ordering is ascending
Can explicitly add asc or desc
SELECT count(*), Title
FROM adventureworks.Employee
GROUP BY Title
Will vary by vendor
Aggregate, Datetime, User defined etc.
count(*)
count(x)
sum(x)
avg(x)
FILL INZ!!!
count(x)
sum(x)
avg(x)
abs()
max()
min()
length()
ltrim()
rtrim()
Are a sequence of instructions (SQL Statements) that perform a task and are stored in a single execution plan
Available to pplications that access relational database systems
Used for extensive and/or complex operations that involve multiple SQL statements
Indexes reduces the number of database pages that have to be visited/scanned
Used to enhance query performance
Can be thought of as a pointer to data in a table (much like an index of a book)
Can only have one clustered index per table (determines the physical order of a table)
The clustered index is the table
Can have many non clustered indexes per table
Triggers are database operations that are automatically performed when a specific event occurs in your database.
Among other things, triggers often used to insert records into log tables when changes are made to data.
Creating triggers is beyond the scope of this class, but know they exist.
A transaction is an atomic unit of database operations.
The effect of a transaction is that either all of the SQL statements in a transaction are committed to the database, or all of them are rolled back (no changes).
A transaction begins with the BEGIN TRANSACTION statement, followed by COMMIT or ROLLBACK.
Transactions are beyond the scope of this class, but good to learn if you are dealing with a group of changes that are "all or nothing".