Вы находитесь на странице: 1из 5

DML Data Manipulation Language

- working with the tables themselves


- there are a lot of clauses

DDL Data Definition Language


- using SQL to create and make changes to tables
Basic SELECT statements: SELECT (column) FROM (table)
To SELECT all from the table = SELECT * FROM table
* = all
CONSTRAINTS = rule or restrictions
Projection (specified columns) = SELCT
firstname FROM orders
To select all table, but different view = SELECT column, column FROM table
o SELECT RegionDescription, RegionID FROM Region
ORDER BY CLAUSE = optional clause that allows you to reorder the columns
o SELECT * FROM employees ORDER BY LastName
ASC = order by A-Z or 1 - 100
DES = order by Z-A or 100 1

WHERE CLAUSE = effects existing records, OPTIONAL CLAUSE, but if used with ORDER BY
must be in the right order;
WHERE CLAUSE comes 1st
o Where Clause can have multiple expressions joined by AND, OR

Logical Operator = AND, OR, EXOR, NOT

AND and OR combine


o SELECT * FROM Employees WHERE LastName = King and
lastname = Adams
o Dates are in # #

SELECT *FROM employees WHERE titleofcourtesy = Dr. and birthdate


<#1/1/1940# ORDER BY titleofcourtesy, lastname desc

Text based value, string, must be in quotes


o Shows all columns from the Employee Table that secludes last name, King

SELECT * FROM Employees WHERE LastName = King


Where Clause can have multiple expressions joined by AND or OR
Primary Key is by far the most common in tables
MOD = modules, when you divide and return the remainder
o SELECT * FROM employees WHERE employeeid MOD 2=0

This will bring up all employee IDs in the increments of 2 (2, 4, 6, 8)


When a function results are ran, it will change the column name. Example: LastName= Expr1000
ALIAS = renames the column in the output MUST use the word AS after the column
o AP = Alias Product (see CORRELATED SUBQUERIES)
o In order to add a space within the name of the category use [ ] around the Alias
name

Example: AS [Average Price]


o SELECT left(firstname, 1) + . AS FirstInitial, ucase (lastname) AS UpperLastName,
TitleOfCourtesy as Prefix FROM employees
o SELECT productname, unitprice as cost FROM products ORDER BY productname

INSERT

Statement = adds to the tables/records. (Generally speaking)


o Inserting one record at a time THERE IS NO UNDO!!!
o INSERT TO will allow for multiple records

INSERT INTO TABLE (column, column) values (column, column)

Must provide a value required for every column


Must provide a value for a Primary Key
EXCEPT when it is AutoNumber
Must have the same numbers of values as columns
INSERT INTO territories (regionid, regiondescription, territoryid) values (2,
PhilsHouse, 2345)
UPDATE = changes existing record, needs WHERE CLAUSE (usually Primary Key)
o UPDATE Table Set column = value, column WHERE column=value

YOU WILL UPDATE EVERYTHING!!!

THERE IS NO UNDO!!!
o UPDATE region SET regiondescription = Alaska WHERE regionid = 5
DELETE = removes records THERE IS NO UNDO!!!
o CHANT = I WILL NEVER RUN AN UPDATE OR DELETE WITHOUT A WHERE
CLAUSE
o DELETE FROM table WHERE column = value
o DELETE FROM products WHERE productid = 53
DISTINCT = eliminates duplicates
o SELECT DISTINCT column FROM table

Almost always done in a single column


o SELECT DISTINCT titles FROM employees
NULL = cannot use = , to test for NULL use IS (absent values)
o SELECT column FROM table WHERE column IS NULL
o SELECT column FROM table WHERE column IS NOT NULL
AGGREGATES = a summary; these summaries typically do not have specific set of data
will look at all data
o DO NOT SELECT second column targets multiple rows

Most databases will support 5 aggregates all data

( ) = aggregate function argument

Function = a process
o SELECT Aggregate Function (column) FROM table
o SUM summation (summarizes)
o COUNT how many records match (does not work on specific rows, must

o
o
o
o
o

use (*)
MAX maximum
MIN minimum
AVG average (takes the average between multiple items)
SELECT SUM (unitsinstock) FROM products

Adds up each item in the Units In Stock row


SELECT MAX (unitsinstock) FROM products

Selects the highest value in the row

Use an ALIAS (AS) to change the column name

SELECT MAX (unitsinstock) AS NumberOfBoxes FROM products


SELECT COUNT (*) FROM products
SELECT AVG(unitprice) FROM products
SELECT AVG(unitprice * unitsinstock) FROM products WHERE productid=21 or
prodcutid=74

PER = how many students? versus How many students PER program?
GROUP BY Clause= lets us do PER activity
the only time you select a second column in an Aggregate Query is by using

GROUP BY
o Group By Foreign Key NEVER by Primary Key
o SELECT Aggregate Function (column) FROM table GROUP BY column
o SELECT AVG(column), Foreign Key FROM table GROUP BY Foreign Key

SELECT AVG(unitprice), supplierid FROM products GROUP BY supplierid ORDER


BY AVG(unitprice)
o SELECT COUNT (*), supplierid FROM products GROUP BY supplierid
o How many products at each price point?
SELECT COUNT (*), unitprice FROM products GROUP BY unitprice
SELCT COUNT (*), country FROM customers WHERE country <> Poland
GROUP BY country ORDER BY COUNT (*)
o ALWAYS USE in this order: WHERE, GROUP, ORDER BY
FormatCurrency
o This will allow you to put the query in a currency format

SELECT productname, unitprice AS [The Cost], formatcurrency(unitprice+


(unitprice*.1)) AS [New Price] FROM products ORDER BY productname
o What would happen if ALL products were raised by a dollar?
SELECT prodcutname, unitprice AS [The Cost], unitprice+(unitprice+1) AS
[New Price] FROM products
o What would happen if ALL products were raised by 10%?
SELECT productname, unitprice AS [The Cost], unitprice+(unitprice*.1) AS
[New Price] FROM products ORDER BY productname
HAVING = only ever used with an Aggregates Queries
o < > means not equal, able to eliminate a value/Foreign Key
o SELECT AVG(unitprice), categoryid FROM products GROUP BY AVG(unitprice)

SELECT AVG(unitprice), categoryid FROM products WHERE categoryid <>7


GROUP BY categoryid HAVING AVG(unitprice) >30 ORDER BY AVG(unitprice)
LIKE = must use * * in order to search anything that has that exact word
* in order to search anything that has that letter
o example = S* will search all values that begin with the
letter S
Scaler = must equal 1 value
o SELECT productname, unitsinstock FROM products WHERE unitstock =
(select max (unitsinstock) from products)
SUBQUERY = queries nested within each other, must return 1
o Subqueries must return 1 scaler value
CORRELATED SUBQUERIES = one query within another
o Average per its category = SELECT productname, unitprice, categoryid (Select
AVG(unitprice) FROM products WHERE categoryid=1) as [Average Price] FROM
product
o SELECT productname, unitsinstock FROM products WHERE unitstock =
(select max (unitsinstock) from products)
o SELECT productname, unitprice, categoryid (SELECT AVG(unitprice) FROM products
WHERE products.categoryid=ap.categoryid) AS [Average Price] FROM products as
ap
AP = Alias Product
IIF statement =
Datepart = will select portions of the date
TRIM =
o ltrim (L Trim) = spaces from the left side
o rtrim (R Trim) = spaces from the right
o
MID = takes 3 arguments
1. The value extracting from
2. At what character position you are abstracting from
3. How many characters do you want to take
o SELECT firstname, MID(firstname,1,2) AS [Last Initial] FROM employees

LEN

= will tell you how many characters are in a column


o SELECT len(firstname) AS [Name Length] FROM employees
In String (instr) =
o SELECT prouctname, INSTR(productname, @) FROM products WHERE
INSTR(prodcutname, @) >0
o SELECT prodcutname, INSTR(productname, @), MID(productname,
INSTR(productname, @) +1) FROM products WHERE INSTR(productname, @)>0

This one will add a new column that wills how the word after the @
Projection = selecting a subset of columns describing the idea that we can retrieve
only desired columns from the base table and rearrange or rename the columns in
the output view
o Choosing or eliminating a particular column

SELECT firstname, lastname FROM t


Selection = retrieves a sub set of rows
o SELECT *t WHERE tid=1
PRODUCT (CARTESIAN)= every record in A put next to every record in B
JOINS = virtually reassembles the database and makes it user friendly puts all the
pieces together
o SELECT column FROM table JOIN TYPE table ON key=key
o INNER JOINS = pairs records in 2 different columns where there is equality
Only show records that have a match in their apposing records from both
sides
only matches records that have matching parent and child table
removes unmatched records
o OUTER JOINS = will show records that are unmatched
LEFT JOIN = pulls all records from the table on the left side of
the join with only matching records on the right side
o If they match more than 1 record, they will show up twice
o If they have no matches, they will show up once, but with a
NULL (or blank) in the column
RIGHT= pulls all records from the table on the right side of the
join with only matching records on the left side
Would want all parent records to match their child
o FULL = all records from both tables that includes both matched and
unmatched records
o SEMI = Finds only matches and shows them
o ANTI = Finds record in 1 table that doesnt have a match and only shows
those
o EQUI = the joining of 2 or more tables based on the equality of one (or
more) columns
Pairs columns from the 2 tables based on the equality of 1 or more column
SELECT t.lastname, t.firstname, t.tid, s.tid, s.lastname,
s.firstname, s.sid FROM t,s
o This shows everything from the T table and puts it next
to the S table
o

NATURAL = eliminates the redundant columns and tests on all


correspondingly name columns
Only joins on identically named columns
Makes a distinguished between Equi and Natural

These are done in INNER JOINS (in SQL). INNER JOINS performs
either Equi or Natural depending on how the columns are named
o UNION = Merging of 2 or more tables or queries with similar column
structures

Having at least 1 column with the same name in 2 different tables


o INTERSECTION = describes records that occur in both tables

Must be compatible
MULTIPLE JOINS
SELECT columns FROM (table JOIN TYPE table ON key=key) JOIN TYPE
new table ON key FROM one of the first two original tables=new key

SELECT categories.categoryname, productsnew.productname,


suppliers.companyname, productsname.supplierid,
categories.categoryid AS CatIDFromCategories,
productsnew.categoryid AS CatIDFromProducts FROM (categories
INNER JOIN productsnew ON
productsnew.categoryid=categories.categoryid) INNER JOIN suppliers
on productsnew.supplierid=suppliers.supplierid
o

SQL SERVER
VARCHAR
o

= variable within character field


varchar(#) = how many characters you need

varchar(5) = _ _ _ _ _
IDENTITY = auto number or auto increment
o Will make up a unique number
o Identity Increment = where it (auto number) counts by
o Identity Seed = where it (auto number) starts
o Numberic(#,#) = number of characters needed, number of characters after the
decimal

Numeric(6,2) = _ _ _ _ _ _ . _ _
Colors within SQL
o RED = string (text values)
o GREEN = comments (going to be ignored)
o Blue = key words
o Black = tables
How to add spaces
o [ ] = brackets around words in SQL Server

[Movie Titles]
o ` ` = back ticks around words - phpMyAdmin

`Move Titles`

Вам также может понравиться