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

SQL Basics: Introduction To Standard Query Language

SQL is a language for interacting with relational databases. It has two main types: DML for manipulating data and DDL for defining database structure. A database contains tables which are made up of rows and columns. Tables are organized using a schema which defines the structure. SQL can be used to retrieve, insert, update, and delete data from databases using commands like SELECT, INSERT, UPDATE, and DELETE. Joins allow combining data from multiple tables.

Uploaded by

kush4171
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
123 views

SQL Basics: Introduction To Standard Query Language

SQL is a language for interacting with relational databases. It has two main types: DML for manipulating data and DDL for defining database structure. A database contains tables which are made up of rows and columns. Tables are organized using a schema which defines the structure. SQL can be used to retrieve, insert, update, and delete data from databases using commands like SELECT, INSERT, UPDATE, and DELETE. Joins allow combining data from multiple tables.

Uploaded by

kush4171
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

SQL Basics

Introduction to
Standard Query Language
SQL What Is It?

• Structured Query Language


• Common Language For Variety of Databases
• Two Types of SQL
1. DML ––Data Manipulation Language (SELECT)
2. DDL ––Data Definition Language (CREATE TABLE)
What is a Database?

Databases are designed to offer an organized mechanism for


storing, managing and retrieving information. They do so through
the use of tables. If you’re familiar with spreadsheets like
Microsoft Excel, you’re probably already accustomed to storing
data in tabular form. It’s not much of a stretch to make the leap
from spreadsheets to databases.
What is a Tables?

Just like Excel tables, database tables consist of columns and rows.
Each column contains a different type of attribute and each row
corresponds to a single record. For example, imagine that we were
building a database table that contained names and telephone
numbers. We’d probably set up columns named “FirstName”,
“LastName” and “TelephoneNumber.” Then we’d simply start
adding rows underneath those columns that contained the data
we’re planning to store.

If we were building a table of contact information for our business


that has 50 employees, we’d wind up with a table that contains 50
rows.
What is a Schema?

A database schema is described in a formal language supported by


the database management system (DBMS). In a relational
database, the schema defines the tables, the fields in each table,
and the relationships between fields and tables.
Schemas are generally stored in a data dictionary. Although a schema
is defined in text database language, the term is often used to
refer to a graphical depiction of the database structure Levels of
database schema
Data Types:
CHAR(size) : Character string of fixed string length n.
DATE(): A date. Format: YYYY-MM-DD
DATETIME(): A date and time combination. Format: YYYY-MM-DD
HH:MM:SS
VARCHAR(size): can contain letters, numbers, and special characters
Data Definition Language (DDL)
statements are used to define the database structure or schema.
Some examples:

• CREATE - to create objects in the database


• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces
allocated for the records are removed
• COMMENT - add comments to the data dictionary
• RENAME - rename an object
Sample Table
Data Manipulation Language (DML)
statements are used for managing data within schema objects.
Some examples:
• SELECT - retrieve data from the a database
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - deletes all records from a table, the space for the records
remain
• MERGE - UPSERT operation (insert or update)
• CALL - call a PL/SQL or Java subprogram
• EXPLAIN PLAN - explain access path to data
• LOCK TABLE - control concurrency
Data Control Language (DCL)
Some examples:
• GRANT - gives user's access privileges to database
• REVOKE - withdraw access privileges given with the GRANT
command
Transaction Control (TCL)
statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into
logical transactions.

• COMMIT - save work done


• SAVEPOINT - identify a point in a transaction to which you can
later roll back
• ROLLBACK - restore database to original since the last COMMIT
• SET TRANSACTION - Change transaction options like isolation level
and what rollback segment to use
Where To Use?

• SQL*Plus
• TOAD
• SQL Navigator
• Excel
• Access
• Lotus 1Lotus 1
• Heart of PL/SQL
Pros & Cons of SQL

Pros:
• Very flexible
• Universel (Oracle, Access, Paradox, etc)
• Relatively Few Commands to Learn
Cons:
• Requires Detailed Knowledge of the Structure of the Database
• Can Provide Misleading Results
Basic SQL Components

• SELECT schema.table.column
• FROM table alias
• WHERE [conditions]
• ORDER BY [columns];
 Defines the end of an SQL statement
 Some programs require it, some do not (TOAD Does Not)
 Needed only if multiple SQL statements run in a script

Optional Elements
SELECT Statement
• SELECT Statement Defines WHAT is to be returned (separated by
commas)
 Database Columns (From Tables or Views)
 Constant Text Values
 Formulas
 Group Functions (COUNT, SUM, MAX, MIN, AVG)
• ““*” Mean All Columns From All Tables In the
• FROM Statement
• Example: SELECT roll_number, student_name
FROM Statement

• Defines the Table(s) or View(s) Used by the SELECT or WHERE


Statements
• You MUST Have a FROM statement
• Multiple Tables/Views are separated by Commas

Example: SELECT roll_number, student_name


FROM class

SELECT *
FROM class
WHERE Clause
• Optional
• Defines what records are to be included in the query
• Uses Conditional Operators
– =, >, >=, <, <=, != (<>)=, (<>)
– BETWEEN x AND y
– IN (listlist)
– LIKE ‘‘%string%’’(“%” is a wild-card)
– IS NULLIS NULL
– NOT {BETWEEN / IN / LIKE / NULL}
• Multiple Conditions Linked with AND & OR Statements
• Strings Contained Within SINGLE QUOTES!!
AND & OR

• Multiple WHERE conditions are Linked by AND / OR Statements


• “AND” Means All Conditions are TRUE for the Record
• “OR” Means at least 1 of the Conditions is TRUE
• You May Group Statements with ( )
• BE CAREFUL MIXING “AND”& “OR” Conditions
Examples with WHERE
SELECT roll_number, student_name
FROM class
WHERE Roll_number = ’20’

SELECT roll_number, student_name


FROM class
WHERE Roll_number > ‘10’

SELECT roll_number, student_name


FROM class
WHERE student_name like ‘%ABC%’

SELECT roll_number, student_name


FROM class
WHERE Roll_number in (‘10’, ’20’, ‘21’) and student_name like ‘%ABC%’
ORDER BY Statement
• Defines How the Records are to be Sorted
• Must be in the SELECT statement to be ORDER BYORDER BY
• Default is to order in ASC (Ascending) order
• Can Sort in Reverse (Descending) Order with ““DESCDESC””After
the Column Name

Examples:
SELECT *
FROM class
ORDER BY roll_number DESC
Group Functions
• Performs Common Mathematical Operations on a Group of
Records
• Must define what Constitutes a Group by Using the GROUP BY
Clause
• All non-Group elements in the SELECT Statement Must be in the
GROUP BY Clause (Additional Columns are Optional) -

Examples:
SELECT *
FROM class
GROUP BU grade
OK, I understand How to Get Data
From 1 Table What about Multiple
Tables? Table…
Primary & Foreign Keys

Primary Keys
• 1 or More Columns Used to Uniquely Identify a record.
• All Columns Defined as PK’s MUST be populated

Foreign Keys
• Value on a table that references a Primary Key from a different
table
What are Joins?
A JOIN is a means for combining fields from two tables by using
values common to each.

types of JOINs:

• INNER
• OUTER
• LEFT
• RIGHT.

• Joins Between Tables are Usually Based on Primary / Foreign Keys


• Make Sure Joins Between All Tables in the FROM Clause Exist
• List Joins Between Tables Before Other Selection Elements
SAMPLE TABLES
Aliases

• “Shorthand”for Table or Column References


• SELECT Aliases Appear as Column Headers in the Output
• Aliases Cannot be Keywords

SELECT roll_number as ROLL, student_name as NMAE


FROM class

Why Use an Alias?

• Saves Typing
• Good Internal Documentation
• Better Headers
• If the same column name exists on multiple tables, SQL needs a way to
know which element you are referencing
Inner Join
Inner joins return all rows from multiple tables where the join
condition is met.
SELECT *
FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID

SELECT *
FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID
Outer joins

An outer join does not require each record in the two joined tables to have
a matching record. The joined table retains each record—even if no
other matching record exists.

Outer joins subdivide further into left outer joins, right outer joins, and full
outer joins
Left outer join
The result of a left outer join (or simply left join) for table A and B always
contains all records of the "left" table (A), even if the join-condition does
not find any matching record in the "right" table (B).

This means that if the ON clause matches 0 (zero) records in B, the join will
still return a row in the result—but with NULL in each column from B.

This means that a left outer join returns all the values from the left table,
plus matched values from the right table (or NULL in case of no
matching join predicate). If the right table returns one row and the left
table returns more than one matching row for it, the values in the right
table will be repeated for each distinct row on the left table.
Left outer join
SELECT *
FROM employee LEFT OUTER JOIN department ON employee.DepartmentID =
department.DepartmentID

SELECT *
FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID(+)
Right outer join
A right outer join (or right join) closely resembles a left outer join,
except with the treatment of the tables reversed. Every row from
the "right" table (B) will appear in the joined table at least once.

If no matching row from the "left" table (A) exists, NULL will appear
in columns from A for those records that have no match in B. A
right outer join returns all the values from the right table and
matched values from the left table (NULL in case of no matching
join predicate).

For example, this allows us to find each employee and his or her
department, but still show departments that have no employees.
Right outer join
SELECT *
FROM employee RIGHT OUTER JOIN department ON employee.DepartmentID =
department.DepartmentID
You do the research on:
What is:

Union, union all.


Minus.
How to find duplicate records in a table.
How does count(), sum() works.
What is a sub query. How to write a query with sub queries.

You might also like