You are on page 1of 12

SQL

06 February 2023 10:20

Once you drop a table - IT'S PERMANENT. WON'T COME BACK. THAT'S ITTTTT.

FOREIGN KEY (field) --> variable within table we're calling from elsewhere
REFERENCES table(KEY) --> collects the reference data from the other table

TRUNCATE TABLE table_name; Removes all records from a table but won't destroy the table structure
ALTER TABLE table ADD(key Add new field to a table (e.g., ALTER TABLE customer ADD(email
DATATYPE) Varchar(100));
ALTER TABLE table MODIFY key
datatype
RENAME TABLE table TO rename table
new_name

Bootcamp Page 1
If you had an employee who was in multiple departments then you'd need a:
- department table
- employee table
- department/employee table (aka junction table)

Referencial Integrity = the accuracy and consistency of data in a data relationship


- data linked between 2 or more tables
- Primary Keys and Foreign Keys

Database Entity-Relationship Diagram - also known as Schema

Bootcamp Page 2
Bootcamp Page 3
getdate gets the current datetime

Viewing data:

Note: no comma at the end of first-line

Bootcamp Page 4
Functions:

Bootcamp Page 5
CaseSensitivity is dependent on the program you're using.

Specifying range:

Discluding certain values:

the LIKE operator:

Bootcamp Page 6
Narrowing down search terms:

Can have AND/OR so either statement is true.

AND has precedence over OR:

By adding brackets you group arguments together


to get exactly the search you want. Without them there
is a tug of war between OR and AND - AND will win.

Counting all the cities in the USA!

Bootcamp Page 7
Counting all unique countries in the database!

SELECT DISTINCT value FROM table; display values without duplicates

SQL REVISION!

SHOW tables; Shows all tables in database


SELECT * FROM table; see the whole table
SELECT field1, field2 FROM table; see only selected columns from table
SELECT Using arithmetic to manipulate data and display as an alias.
field1,
field 2 * 1.5 as field_150
FROM table;
SELECT DISTINCT field FROM table; Displays all unique occurences in a field / no duplicates.
SELECT The 'datepart' function takes argument (interval, datefield) to
DATEPART (MM, date_field) as month format date values (incl., datetime, date, smalldatetime) as an
FROM table; interval (e.g., YYYY = year, dw = Weekday, hh = hour).
[see here for more]
^ as above, add after 'table',

ORDER BY month This will order the rows by ascending month.


LIMIT n; This will only show n amount of rows.
SELECT field, This would create a column counting the number of instances the
COUNT(name) as alias selected
FROM table;

SubQueries:

SELECT Name, Population Shows the city and population of the MAX populated

Bootcamp Page 8
SELECT Name, Population Shows the city and population of the MAX populated
FROM Country city in the table.
WHERE Population =
(SELECT max(population) FROM country);

Constraints:

NOT NULL = can't be empty

Hierarchy and names:

Introduced to JOIN - there are multiple types of JOIN

SELECT * FROM sale Restricting the range of rows.


WHERE order_value BETWEEN
10 AND 30;
^ as above, plus We only want to see the results from employees 10 and 50.

Bootcamp Page 9
^ as above, plus We only want to see the results from employees 10 and 50.
The values we want to see are IN the brackets.
AND emp_no IN (10, 50);
SELECT * This shows only rows with departments containing 'sys' in their names (i.e., systems).
FROM dept This can be capitalised or lowercase, denoted by the enclosing %.
WHERE dept_name LIKE '%SYS%' ;
WHERE field IS NOT NULL; Doesn't show rows where the specified field is empty.
SELECT Coalesce replaces any NULL value in field with the 2nd argument.
COALESCE (field, 'field unknown') as New Field
FROM table;
SELECT order_no, order_value, name Joining a field from one table to another. Table Aliases are used to denote which table
FROM sale S the field belongs in (and aids with readability).
INNER JOIN company C ON S.company_no =
C.company_no
SEE EXAMPLE BELOW!

Sale: Company:

order_no order_value company_no company_no name


1 100 4 1000 1 1000 Supermarket
2 200 6 6000 2 6000 Retailer
3 300 17 8000 3 8000 Tech

These fields link these two different tables, so we script this with:

INNER JOIN company C ON S.company_no = C.company_no

It knows we want to use the 'name' field from company because that's what we
specified after SELECT, so this is our output:

Joined table:
order_no order_value name
1 100 4 Supermarket
2 200 6 Retailer
3 300 17 Tech

Outer joins:

--p2) Copy in the 3rd query from p1) and change the word INNER to the word RIGHT

-- This is called an outer JOIN, inserting the word RIGHT means literally
-- "include every row from the table on the RIGHT of the word JOIN",
-- (even if there is no matching row in the table on the LEFT).

SELECT D.dept_no, manager, lname


FROM salesperson SP
RIGHT JOIN dept D ON SP.dept_no = D.dept_no

dept_no manager lname


----------- -------------------- ---------------
1 Adam Apricot Brick
2 Barbara Banana Custard
2 Barbara Banana Digger
3 Paul Peach Ernst
3 Paul Peach Flipper
3 Paul Peach Goalie
4 Diver Dan NULL
5 Xavier Xylophone NULL

-- p4) ‘Can I do a LEFT & a RIGHT JOIN at the same time?’ is a question often asked.
-- Yes, it’s called a FULL JOIN.

SELECT COALESCE(manager, '** Has no manager **') AS Manager,


COALESCE(lname, '** Nobody in this dept **') AS Surname
FROM dept D FULL JOIN salesperson SP
ON SP.dept_no = D.dept_no

Bootcamp Page 10
Manager Surname
-------------------- -------------------------
Adam Apricot Brick
Barbara Banana Custard
Barbara Banana Digger
Paul Peach Ernst
Paul Peach Flipper
Paul Peach Goalie
Diver Dan ** Nobody in this dept **
Xavier Xylophone ** Nobody in this dept **
** Has no manager ** Ell

-- But if you were now to include 'dept_no' in this query, should you choose
-- SP.dept_no or D.dept_no, because one of the rows is surely going to have a NULL dept_no?
-- Well you could include either and COALESCE it to remove the NULL, but there is one problem.
-- Namely, the 'COALESCE' function requires that both parameters are of the same data type,
-- so

○ COALESCE(D.dept_no, 0 ) -- would be valid syntax but produce a misleading '0' in results.


○ COALESCE(D.dept_no, 'n/a') -- would fail as 1st arg is numeric, but 2nd arg is not.

-- So the solution would be to convert the 'dept_no' into a character string.


-- In SQL Server it would be

COALESCE(STR(D.dept_no, 2), 'n/a') -- meaning convert D.dept_no into a 2 character string.

Insert, Udate and Delete:

INSERT INTO table Add a new line of data and type values in order
VALUES (x, y, z, NULL) of columns.
SELECT * from table Update the values of a column.
UPDATE table
SET column = column + n
DELETE FROM table Say, you want to delete something where the
WHERE column LIKE '% ? %' word contains the specified letter.
UPDATE contact
SET job_title = 'VP of Development', tel = '01242-112233 Ext 444'
WHERE name = 'Ricky Rambo'

Creating tables

CREATE TABLE review NULL / NOT NULL specifies whether the column allows null values
( to exist. If NOT NULL then there must be a given value.
emp_no INT NOT NULL,
review_date DATETIME NOT NULL,
grade CHAR(1) NULL
)

ALTER TABLE review Adding a character column of varying length, not to exceed 40
ADD notes VARCHAR(40) NULL characters.

'Referential integrity' is about a datapoint existing in all necessary tables, so Jack Mason can be found in
'department' AND 'salesperson'. To be missing from one would mean the database is lacking in referential
integrity.

Bootcamp Page 11
----------------------------------------------------------------------------------------------------------------------

-- There is a composite Primary Key constraint defined on the 'emp_no' and 'review_date'
-- columns. The constraint is a separate object in the database which can be 'dropped'
-- independently of the table itself, so it is a good idea to give it a meaningful name
-- like 'pk_review'.

CONSTRAINT pk_review PRIMARY KEY(emp_no, review_date)

-- There is a Foreign Key constraint defined on 'emp_no' which basically says


-- "values in the 'emp_no' column of 'review' should exist in the primary key column
-- of 'salesperson' which just happens to also be called 'emp_no' but doesn’t have to be".

CONSTRAINT fk_salesperson_link FOREIGN KEY(emp_no) REFERENCES salesperson

-- Now run this CREATE table syntax and then observe the changed behaviour you get when you
-- either INSERT/UPDATE 'reviews' or DELETE/UPDATE 'salespersons'.

-- Run this code:

CREATE TABLE review


(
emp_no INT NOT NULL,
review_date DATETIME NOT NULL,
grade CHAR(1) NULL,
CONSTRAINT pk_review PRIMARY KEY(emp_no, review_date),
CONSTRAINT fk_salesperson_link FOREIGN KEY(emp_no) REFERENCES salesperson
)

CONSTRAINT followed by name_of_constraint followed by where the constraints apply

-----------------------------------------------------------------------------------------------------------------------------=

------------------------------------------------------------------------------------------------------------------------

INSERT INTO review


VALUES (90, '05-12-2006', 'A')

-- What happened and why?

INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'fk_salesperson_link'.


The conflict occurred in database 'xxxxxxxxxx', table 'salesperson', column 'emp_no'.
The statement has been terminated.

Inserting employee no_90 into the review table didn't work because in the previous CREATE TABLE block we
created a CONSTRAINT. Employee 90 doesn't exist in the salesperson table, so we are prevented from adding
them to review and damaging the referential integrity of the database. This is why we created the
CONSTRAINTs.

---------------------------------------------------------------------------------------------------------------------------

Bootcamp Page 12

You might also like