Download presentation
Presentation is loading. Please wait.
1
Advanced MySQL Queries
CS4750
2
Introduction to Advanced Queries
High-level overview – managing the business logic – on the data layer
3
High-end SQL queries They are so different for every database system Vastly different from MySQL vs. MS-SQL vs. Oracle… Understanding the idea behind them is important Syntax can come later Depending on what DB system you’re going to use, you’ll have to look up these queries These advanced SQL queries are going to manage the business logic
4
We’ve talked about… The SQL queries used for Data Manipulation and Data Definition Selects Joins Grouping Searching Inserts Deletes Updates ...
5
Remember, why we wanted DBMS?
Query processing Transactions Physical Data Independence Dealing with a “model” instead of the data Security Concurrent access Managing redundancy …other things
6
Business Logic Layers: [PRESENTATION ] [LOGIC] [DATA] In upper layer
ASP.net php Java … All making queries to the database and reporting back to the user How much of our business logic should reside at the Data layer or Logic layer? Layers: [PRESENTATION ] [LOGIC] [DATA]
7
Advanced SQL Commands More Complex Less Complex Stored Procedures
Triggers Assertions Checks Integrity Constraints Data Types All six of these are types of SQL commands that we can execute Going to shift some logic from the logic layer to the data layer
8
Why this shift? We shift core logic to the data layer and let the database handle it Don’t want teams that use ASP, php, Java, … developing for mobile app, or web app, or something else to duplicate or come up with their own SQL queries E.g. Query: “Move $50 from checking to savings” Don’t want a different query for the Mobil bank, Web client, ATM, Tellers… Different queries would make testing harder
9
Advanced SQL Commands Starting from the least complex
10
Data Types The simplest way to control what kind of data is in your database Forces all data populating a particular attribute to look a certain way A very low level, easy way, of ensuring the data is one type Types: Integers, varchar, text, date (timestamp), decimals, boolean, enum, blobs(!), spatial stuff…
11
On phpMyAdmin… Look at section table (Lou’s List)
Click on Structure tab There are some basic data types in SQL you should know You can have different sizes of types E.g. int (11) Important to judge correct size! Else the DB will truncate!
12
On phpMyAdmin… (more types)
Operations > In Create Table > make “testtest” 2 columns Text: Tiny/medium/long Paragraph text not intended to be searched Text is not indexed (you can index varchars) Date: Timestamp – most useful Decimals Bit/boolean
13
On phpMyAdmin… (more types)
String – blobs! “Binary Large Object” – Do NOT use! DB good at managing text/numbers Bad at managing images can’t index increases overhead makes joins with tables really hard… If you’re going to store images or thumbnails Store the URL in the DB of the image and put the images in some image directory Don’t use Blobs!! Enum – quite useful, must be in a set of values (e.g. Rating – “G, PG, PG-13, R”)
14
When transmitting data to the DB…
It’s always going to be a string (even if its an integer) The database does the conversion!
15
Integrity Constraints
Making sure data in your DB is valid (data integrity) Examples: Foreign keys (“foreign constraint”) Click on a table, go to the structure tab, then click on “Relation View” NULL or not Will you allow computingID to be NULL? Or refuse to let someone do an insert into your database unless they provide a computing ID? Default values Primary keys Unique - while not your primary key, that column must be unique
16
Checks A truth statement that you make about a single field in one table that is “checked” any time there is an insert or an update on that table Example: “Check balance > 0” For instance, in Bank database, add a check constraint “Balance of someone’s account cannot go below zero” If you do an insert, update, or delete that will change that value which will result in that check not passing that update is not allowed Most checks going to be numeric E.g. CONSTRAINT ‘CK_NotZero’ CHECK(‘balance’>0);
17
Example of Check CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(50) NOT NULL, FirstName varchar(40), Address varchar(255), City varchar(255), CONSTRAINT chk_PersonId CHECK (P_Id>0) )
18
Assertion Check: one-table, one-attribute
Assertion: one-table, multi-attribute, it could involve a second table Usually more complex and more powerful than Checks Example: “The sum in another table must be greater than the min in this table” Example: “You are only allowed to withdraw up to $200/day from an ATM” Referencing sum on ‘withdraw’ table (which sums up total withdrawals) and may check it against some limit
19
Triggers They are event-driven, reacting to updates, deletes, or insertions. Once this event is detected, they “do something” usually performing a particular query Triggers are really where you start building in business logic The query could be another insert, update, … Example: Warehouse Every time a shipment goes out, database updates inventory If inventory level drops below a certain threshold A trigger is activated Might insert a line into an ‘orders’ table to place order for X amount of that item
20
Example of Trigger (1) If you had a table created as follows:
CREATE TABLE contacts ( contact_id INT(11) NOT NULL AUTO_INCREMENT, last_name VARCHAR(30) NOT NULL, first_name VARCHAR(25), birthday DATE, created_date DATE, created_by VARCHAR(30), CONSTRAINT contacts_pk PRIMARY KEY (contact_id) );
21
Example of Trigger (2) DELIMITER // CREATE TRIGGER contacts_after_update AFTER UPDATE ON contacts FOR EACH ROW BEGIN DECLARE vUser varchar(50); -- Find username of person performing the INSERT into table SELECT USER() INTO vUser; -- Insert record into audit table INSERT INTO contacts_audit ( contact_id, updated_date, updated_by) VALUES ( NEW.contact_id, SYSDATE(), vUser ); END; // DELIMITER ;
22
Note about overhead… As we move up, we’re incurring more overhead
Do these things only if really needed You should always use data types and do integrity checks Minimum requirement! Checks are good, too… used less often Assertions/Triggers can be quite complicated although very powerful in certain situations Make your choices wisely!
23
Triggers What’s the problem with triggers?
EVERY time something updates that table, that trigger gets checked Therefore, all your data-changing queries – insert/update/ delete – have a higher overhead How to decide when to use triggers? Is your database read-heavy? Is your database write-heavy?
24
Triggers Read-heavy databases You will optimize a lot (using indexes)
Will have assertions and triggers, etc. Because the data won’t change that much Write-heavy databases “log-file” type databases where you’re constantly writing to If you have triggers it will negatively impact your performance
25
Stored Procedures It’s implementation is the most different from one database to another It is simply a function call If a view is a stored select query A stored procedure is a stored select or insert where you can pass parameters to it If you want to use a stored procedure I may need to grant you permission to do that on your database
26
Stored Procedures Example: “GiveEveryoneARaise” stored procedure
Find all employees at some company Apply some formula to give everyone a raise according to some pre-set logic You can pass in parameters like 0.2 or only managers, etc It’s as if you wrote a method that will do this Why is this good? Again, so that everyone doesn’t write their own queries The DB administrator – who knows how to write optimized queries – will tell them to just call the method Can call that stored procedure from any language (ASP, php, Java, etc…)
27
For your DB Project… -- See “Database (40%) under “Grading Rubric” –
One of the requirements is that you implement at least two different complex specialty commands / features
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.