Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
60 views

Database Cheat Sheet

Structured Query Language (SQL) is a data sublanguage used to manage data in relational database management systems. It is used to define tables, insert, query, update and modify data. SQL includes data definition language for defining tables, data manipulation language for inserting, querying and modifying data, and transaction control language for managing transactions. SQL allows joining data from multiple tables and uses comparison operators, aggregate functions and grouping to retrieve desired data.

Uploaded by

Joseph Craig
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Database Cheat Sheet

Structured Query Language (SQL) is a data sublanguage used to manage data in relational database management systems. It is used to define tables, insert, query, update and modify data. SQL includes data definition language for defining tables, data manipulation language for inserting, querying and modifying data, and transaction control language for managing transactions. SQL allows joining data from multiple tables and uses comparison operators, aggregate functions and grouping to retrieve desired data.

Uploaded by

Joseph Craig
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

• Structured Query Language (SQL) is not a complete programming language; rather, it is a data sublanguage

Developed by IBM in the late 1970’s, Endorsed and adopted by ANSI in 1992, Endorsed as a standard by
the International Organization for Standardization (ISO), It is text oriented, Can be used by
• SQL is not a full programming language, but rather a data sublanguage.
• SQL is comprised of:
data definition language (DDL) - used to define database structures
data manipulation language (DML) - data definition and updating, data retrieval (Queries)
SQL/Persistent Stored Modules (SQL/PSM) - procedural programming capabilities
transaction control language (TCL) - control transaction behavior [See Chapter 6]
Data control language (DLC) - grant and revoke database permissions [See Chapter 6]
• The SQL data definition statements include:
CREATE - to create database objects
ALTER - to modify the structure and/or characteristics of database objects
DROP - to delete database objects
TRUNCATE - to delete table data while keeping the structure SQL for DDL CREATE Statement
• Two of the most useful data definition SQL statements are:
the SQL DROP TABLE statement
the SQL ALTER TABLE statement
• SQL DML is used to query databases and to modify data in the tables.
• There are three possible data modification operations:
INSERT - adding data to a relation
UPDATE - modifying data in a relation
DELETE - deleting data in a relation
• The order of the columns on the INSERT command does not matter as long as the values match the order of the
columns as seen below.
• The SQL DML contains commands for the three possible data modifications operations:
Insert, Modify, Delete
• The example above is a valid statement, but note that if you fail to include the WHERE clause then you will have
just deleted all records in the table.
• The basic framework for the SQL Query statement has three statements as follows:
the SQL SELECT clause - specifies which columns are to be listed in the query results
the SQL FROM clause - specifies which tables are to be used in the query
the SQL WHERE clause - specifies which rows are to be listed in the query results
Operator Meaning
= Is equal to
<> Is NOT Equal to
< Is less than
> Is greater than
<= Is less than OR equal to
>= Is greater than OR equal to
IN Is equal to one of a set of values
NOT IN Is NOT Equal to any of a set of values
BETWEEN Is within a range of numbers (includes the end points)
SQL Comparison Operators 2
Operator Meaning
NOT BETWEEN Is NOT within a range of numbers (includes the end points)
LIKE Matches a set of characters
NOT LIKE Does NOT match a set of characters
IS NULL Is equal to NULL
IS NOT NULL Is NOT equal to NULL
• By default, SQL Server sorts in ascending order. If you need the sort in descending order it would be: ORDER BY
Department DESC;
SQL WHERE Clause Options
• Three options for the SQL WHERE clauses are compound clauses, ranges, wildcards
SQL Logical Operators
Operator Meaning
AND Both arguments are TRUE
OR One of the other or both of the arguments are TRUE
NOT Negates the associated operator
• It is possible to involve the use of SQL built-in functions.
SQL Built-in Aggregate Functions
Functions Meaning
COUNT(*) Count the number of rows in the table
COUNT Count the number of rows in the table where column (Name) IS
({Name}) NOT NULL
SUM Calculate the sum of all values (numeric columns only)
AVG Calculate the average of all values (numeric columns only)
MIN Calculate the minimum value of all values
MAX Calculate the maximum value of all values
• In SQL, you can use the SQL GROUP BY clause to group rows by common values. Because there are 9
departments, we have the employees divided into 9 groups.
• The queries considered so far have involved data from a single table. However, at times, more than one table must
be processed to obtain the desired information. SQL provides two different techniques for querying data from multiple
tables:
the SQL Subquery
the SQL Join
• When selection an employee from the joined table:
SELECT firstName, LastName, ProjectID
FROM EMPLOYEE, ASSIGNMENT
WHERE EMPLOYEE.EmployeeNumber = ASSIGNMENT.Employee number
AND EMPLOYEE.EmployeeNumber = 1
or
SELECT firstName, LastName, ProjectID
FROM EMPLOYEE as e, ASSIGNMENT as a
WHERE e.EmployeeNumber = a.Employee number
AND e.EmployeeNumber = 1
• The JOIN ON syntax still requires a statement of primary key to foreign key as shown below:
• Subqueries and joins both process multiple tables, but they differ slightly. A subquery can only be used to retrieve
data from the top table, whereas a join can be used to obtain data from any number of tables.
• SQL Inner Join is also referred to as an SQL equijoin (or simply join).
• An Inner Join only displays data from the rows that match based on join conditions:
if a row has a value that does not match the WHERE clause condition, that row will not be included in the
join result
• LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
• RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
• FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
/* LEFT JOIN */
SELECT *
FROM Student AS s LEFT JOIN Locker AS c
ON s.LockerFK = c.LockerPK;
/* RIGHT JOIN */
SELECT *
FROM Student AS s RIGHT JOIN Locker AS c
ON s.LockerFK = c.LockerPK;
/* FULL OUTER JOIN */
SELECT *
FROM Student AS s FULL OUTER JOIN Locker AS c
ON s.LockerFK = c.LockerPK;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Data Administration Terms


• Data administration refers to a function that applies to an entire organization concerning corporate data privacy and
security issues.
• Database administration refers to a more technical function that is specific to a particular database, including
applications associated with it.
• Database administrator (DBA) refers to the person in charge of a database and facilitates the development of use of
it.
Concurrency Control
• Concurrency control ensures that one user’s work does not inappropriately influence another user’s work.
• Users should be able to enter an order and get the same result whether there are no other users, or hundreds of
other users.
• No concurrency control technique is ideal for all circumstances, they all involve trade-offs.
The Need for Atomic Transactions
• Users submit work in the form of transactions, also know as logical units of work (LUWs).
• An atomic transaction is one where a series of actions are taken on a database such that all of them are performed
successfully or none of them are performed at all.
Lost Update Problem
• If two users are attempting to update the same piece of data at the same time, it is possible that one update may
overwrite the other update.
• If one user’s update overwrites the other’s, this is called a lost update problem (concurrent problem).
Concurrency Issues
• Dirty reads
the transaction needs a changed record that has not been committed to the database
• Inconsistent reads
the transaction rereads a data set and finds that the data has changed
• Phantom reads
the transaction rereads a data set and finds that a record has been added
Resource Locking
• Resource locking prevents concurrent processing problems by disallowing sharing by locking data that are retrieved
for update.
• Locks placed by the DBMS are called implicit locks, while those placed by command are called explicit locks.
Serializable Transactions
• When two or more transactions are processed concurrently, the results in the database should be logically
consistent with the results that would have been achieved had the transactions been processed in an arbitrary serial
fashion.
• A scheme for processing concurrent transactions in this way is said to be serializable.
Two-Phased Locking
• One way to achieve serializable transactions is by using two-phased locking.
• Two-phased locking lets locks be obtained and released as they are needed:
a growing phase, when the transaction continues to request additional locks
a shrinking phase, when the transaction begins to release the locks
Deadlock
• As a transaction begins to lock resources, it may have to wait for a particular resource to be released by another
transaction.
• Sometimes two transactions may indefinitely wait on each other to release resources. This condition is known as a
deadlock or the deadly embrace.
• This condition can lock up a computer preventing use by any user until it is fixed.
Optimistic Locking versus Pessimistic Locking
• Optimistic locking assumes that no conflict will occur. Data are read, the transaction processed, updates are issued,
and then a check is made to see if conflict occurred. If a conflict occurred it is rolled back and repeated until
successful.
• Pessimist locking assumes that conflict will occur, thus locks are issued, the transaction completed, and then the
locks are released.
SQL Transaction Control Language (TLC)
• The SQL BEGIN TRANSACTION statement
• The SQL COMMIT TRANSACTION statement
• The SQL ROLLBACK TRANSACTION statement
ACID Transaction (1 of 2)
• Sometimes the acronym ACID is applied to transactions.
• An ACID transaction is one that is atomic, consistent, isolated, and durable.
Atomic:
▪ an atomic transaction is one in which all of the database actions occur, or none of them do
▪ a transaction consists of a series of steps, each of which must be successful to be saved
Consistent
▪ a consistent transaction means that no other transactions are permitted on the records until the
current transaction finishes; referred to as statement level consistency among all records
ACID Transaction (2 of 2)
Know the meaning of ACID transaction
Isolation
▪ because of multiuser environments, different transactions may be operating on the same data
which can result in continuously changing data content
▪ 1992 ANSI SQL standard defines four isolation levels that specify which of the concurrency
control problems are allowed
Durable
▪ a durable transaction is one in which all committed changes are permanent
Cursors
• A cursor is a pointer into a set of rows that is the result set from an SQL SELECT statement.
• Cursors are usually defined using SELECT statements.
Cursor Types
• Cursors can be forward only or scrollable.
• In SQL Server, these cursors can be one of three different types:
static cursor, keyset cursor, dynamic cursor
• Other DBMS products may define a different set of cursors.
Database Security
• Database security strives to ensure that:
only authenticated users
perform authorized activities
• Processing rights define who is permitted to do what, and when they can do it.
• Individuals are identified by a username and a password.
Figure 6-21 Database Security Guidelines
• Run the DBMS behind a firewall, Apply the latest operating system and DBMS service packs and fixes, Limit DBMS
functionality to needed features, Protect the computer that runs the DBMS, Manage accounts and passwords,
Encryption of sensitive data transmitted across the network, Encryption of sensitive data stored in databases
Application Level Security
• Application level security is often provided on the Web server computer.
• When application security is executed on this server, sensitive security data do not need to be transmitted over the
network.
• For example, when users (who are logged in) click a particular button on a browser page, the following query is sent
to the Web server and then to the DBMS:
Database Backup and Recovery
• Common causes of database failures:
hardware failures, programming bugs, human errors/mistakes, malicious actions
• As these issues are impossible to completely avoid, recovery procedures are essential.
Recovery via Reprocessing
• In reprocessing, all activities since the backup was performed are redone.
• The time it takes to do this is the same amount of time it took when first entered.
• One downside is that if the system is heavily scheduled, it might never catch up.
Recovery via Rollback and Rollforward
• Most database management systems provide a mechanism to record activities into a log file.
to undo a transaction the log must contain a copy of every data- base record before it was changed
▪ such records are called before-images
▪ a transaction is undone by applying before-images of all its changes to the database
to redo a transaction the log must contain a copy of every database record (or page) after it was changed
▪ these records are called after-images
▪ a transaction is redone by applying after-images of all its changes to the database
• The log file is then used for recovery via rollback or rollforward.
Rollback
• Log files save activities in sequence order.
• It is possible to undo activities in reverse order that they were originally executed.
• This is performed to correct or undo erroneous or malicious transaction(s) after a database is recovered from a full
backup.
Rollforward
• Activities recorded in the log files may be replayed.
• In doing so, all activities are reapplied to the database.
• This procedure is used to resynchronize restored database data by adding transactions to the last full backup.
Additional DBA Responsibilities
• The DBA needs to ensure that a system exists to gather and record user- reported errors and other problems:
a method must be devised to prioritize those errors and problems and to ensure that they are corrected
accordingly
• The DBA needs to create and manage a process for controlling the database configuration:
procedures for recording change requests, conducting user and developer reviews of such requests,
creating projects and tasks
• The DBA is responsible for ensuring that appropriate documentation is maintained:
database structure, concurrency control, security and backup and recovery, applications used

You might also like