Você está na página 1de 64

Beginning SQL Tutorial

Wednesday, 08 May 2013

What is SQL?
Structured Query Language Lets you access and manipulate databases ANSI standard.

Also used to create queries, forms, and reports

What is RDBMS?
Stands for Relational Database Management

System RDBMS data is structured in tables, fields and records RDBMS store the data into collection of tables RDBMS provide tools to manipulate database, mostly using SQL Popular RDBMS : MSSQL, Oracle, MySQL, Postgre SQL, DB2, SQL Lite, Firebird, etc ..

Table Basics
A Table is an object

Database data is stored in Tables


Each table has a unique name Columns have various attributes, such as

column name and data type Rows contain records or data for the columns

Weather Sample Table


City
Phoenix Tuscon Flagstaff San Diego Albuquerque

State
Arizona Arizona Arizona California New Mexico

High
105 101 88 77 80

Low
90 92 69 60 60

Selecting Data
The Select statement is used to get data which matches the specified criteria. Here is the basic syntax: ex)
select columnname1, columnname2 from tablename where condition

Conditions Used In Where Clause


= > < >= <= <> equals greater than less than greater than or equal to less than or equal to not equal to

Like
Used to make complex searching easy. If you are trying to find all peoples names which begin with E for example:

ex) select firstname from employee


where firstname LIKE 'E%';

Selecting Exercise
Go to http://sqlcourse.com/select.html Scroll to the bottom of the page. Do exercises 2, 4, and 6. The tables you need are in your handout packet

Creating Tables
The statement to use is create table Here is the syntax:
create table tablename (columnname, datatype, columnname2, datatype, columnname3, datatype);

Creating Tables - Steps


1.

2.
3. 4. 5. 6.

Use the command create table Follow it with the correct table name Put a parenthesis and type in the first column name Follow it with the variable type (we will list them in a minute) then a comma Continue the previous two steps until you have all your columns accounted for Then put a parenthesis to close the columnname section and add a ; after it

Creating Tables - Rules


Table and column names must start with a letter

They can not exceed 30 characters


They can not be key words such as create,

insert, select, etc.

Creating Tables Variables


If you took algebra then y=2x might be familiar.

y and x are unknown information, which is a variable. Now a string is a bunch of letters and numbers A number is a bunch of numbers A data type determines what a variable can hold, i.e. strings or numbers

Creating Tables Data Types


char(size) - all column entries must be = size,

which you specify at the beginning, if size = 10 then you must have ten characters varchar(size) - all column entries must be less than or equal to whatever size is, if size is 10, then the string must be between 1-10 charcters

Creating Tables Data Types contd


number(size) - a number value that can not

exceed, size columns, for example if you have size = 10, then you can only have 10 different digit places, like 1,000,000,000 date - date value number(size,d) - This works the same as the regular number except d represents # of columns after the decimal.

Creating Tables - Constraints


A constraint is a rule.
Some examples constraints are: unique - no two entries will be the same not null - no entry can be blank **primary key - unique identification of each row** primary keys will be very important to you as your knowledge of databases progresses

Creating Tables contd


Here is a real example: create table employee (first varchar(15), last varchar(20), age number(3), address varchar(30), city varchar(20), state varchar(20));

Creating Table Exercise


Go to http://sqlcourse.com/create.html Do the exercise listed under the heading Create Table Exercise

Inserting Information into Tables


To insert into tables you need only use the keyword insert. Here is the syntax:
insert into "tablename" (first_column, ..., last_column) values (first_value, ...,last value);

Inserting Information into Tables


Here is a practical example:
insert into employees (first, last, age, address, city, state) values ( 'Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia');

Inserting Information into Tables Steps


**All strings should be enclosed by single quotes: 'string'** 1. Use the keyword "insert into" followed by the tablename 2. Then on the next line, in parenthesis, list all the columns you are inserting values for. 3. Then on the line after, type values, then in parenthesis, put the values in the same order as the columns they belong to

Inserting Information Exercise


Go to http://sqlcourse.com/insert.html All the employees you need to insert are listed in your handout Do exercises 3, 4, 5, and 8 under the heading: Insert statement exercises

Updating Records
To update records use the "update" statement. Here is the syntax:
update tablename set columnname = newvalue, nextcolumn = newvalue2, ... where columnname OPERATOR value and|or columnname2 OPERATOR value

Updating Records contd


Here are some practical examples: ex)
update phone_book set area_code = 623 where prefix = 979;

This changes the area code all numbers beginning with 979 to 623

Updating Records contd


update phone_book set last_name = 'Smith', prefix=555, sufix=9292 where last_name = 'Jones';

This changes everyone whose last name is Jones to Smith and their number to 555-9292

Updating Records Exercise


Go to http://sqlcourse.com/update.html Do Exercises 1, 2, 3, 5 under the heading: Update statement exercises

Deleting Records
Here is the syntax:
delete from tablename where columnname OPERATOR value and|or columnname2 OPERATOR value

Deleting Records Examples


ex) delete from employees; deletes all records from that table ex) delete from employee
where lastname='May';

deletes all records for people whose last name is May ex) delete from employee
where firstname='Mike' or firstname='Eric';

deletes all records for anyone whose first name is Mike or Eric

Deleting Records Exercise


Go to http://sqlcourse.com/delete.html Do all the exercises under the heading: Delete statement exercises

Deleting Tables
Use the drop command drop table "tablename"; drop table employees; Bye Bye Table, Hello Corporate Espoinage =)

Aggregate Functions
Aggregate functions are used to compute/summarize against a "returned column of numeric data" from your SELECT statement.
MIN
MAX SUM AVG COUNT COUNT(*)

returns the smallest value in a given column


returns the largest value in a given column returns the sum of the numeric values in a given column returns the average value of a given column returns the total number of values in a given column returns the number of rows in a table

Aggregate Functions
Here is the basic syntax:
select avg/max/min/sum(columnname1), avg/max/min/sum(columnname2), columnname3 from tablename where condition group by columnname3

Aggregate Functions
Example:
select avg(price), . from orders where product = MODEM

select count(*), . from employess

Aggregate Functions - Exercise


Go to http://www.sqlcourse2.com/agg_functions.html Do the Exercise 1 - 3

Group By Clause
The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and will allow aggregate functions to be performed on the one or more columns:
select column1, sum(column2) from list of tables group by column list, ..

Group By Clause
The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and will allow aggregate functions to be performed on the one or more columns:
select column1, sum(column2) from list of tables group by column list, ..

Group By Clause
Example:
select quantity, max(price) from items_ordered group by quantity

What data displayed by above query ????

Group By Clause - Exercise


Go to http://www.sqlcourse2.com/groupby.html Do the Exercise 1 - 3

Having Clause
The HAVING clause allows you to specify conditions on the rows for each group. The HAVING clause should follow the GROUP BY clause :
select column1, sum(column2) from list of tables group by column list having condition

Having Clause
Example :
select dept, avg(salary) from employee group by dept having avg(salary) > 20000

What data displayed by above query ????

HAVING Clause - Exercise


Go to http://www.sqlcourse2.com/having.html Do the Exercise 1 - 3

Order By Clause
The ORDER BY clause is an optional clause which will allow you to display the results of your query in a sorted order (either ascending order or descending order) based on the columns that you specify to order by:
select * from list of tables order by column list [ASC | DESC]

Order By Clause
Example :
SELECT employee_id, dept, name, age, salary FROM employee_info WHERE dept = 'Sales' ORDER BY salary, age DESC;

What data displayed by above query ????

Order By Clause - Exercise


Go to http://www.sqlcourse2.com/orderby.html Do the Exercise 1 - 3

Boolean Operators
The AND operator can be used to join two or more conditions in the WHERE clause. Both sides of the AND condition must be true in order for the condition to be met and for those rows to be displayed:
select col1, col2 from tables where condition1 and condition2

Boolean Operators
Example :
SELECT employee_id, dept, name, age, salary FROM employee_info WHERE salary > 50000 AND title = Sales

What data displayed by above query ????

Boolean Operators
The OR operator can be used to join two or more conditions in the WHERE clause. Either sides of the OR condition must be true in order for the condition to be met and for those rows to be displayed:
select col1, col2 from tables where condition1 or condition2

Boolean Operators
Example :
SELECT employee_id, dept, name, age, salary FROM employee_info WHERE salary > 50000 OR title = Sales

What data displayed by above query ????

Boolean Operators- Exercise


Go to http://www.sqlcourse2.com/boolean.html Do the Exercise 1 - 2

IN & BETWEEN
The IN is used to test whether or not a value (stated before the keyword IN) is "in" the list of values provided after the keyword IN:
select col1, col2 from tables where col3 IN (list of values) select col1, col2 from tables where col3 between value1 AND value2

IN & BETWEEN
Example :
SELECT employeeid, lastnameFROM employee_info WHERE lastname IN (Gita', Azis', Hanra', Fuad');

What data displayed by above query ????

Use NOT IN clause to exclude rows in the list

IN & BETWEEN
The BETWEEN is used to test to see whether or not a value (stated before the keyword BETWEEN) is "between" the two values stated after the keyword BETWEEN:
select col1, col2 from tables where col3 between value1 AND value2

IN & BETWEEN
Example :
SELECT employeeid, lastnameFROM employee_info WHERE age BETWEEN 25 AND 40;

What data displayed by above query ????


Use NOT BETWEEN clause to exclude rows in the list

IN & BETWEEN - Exercise


Go to http://www.sqlcourse2.com/setoper.html Do the Exercise 1 - 2

Mathematical Functions
The ANSI SQL-92 support mathematical operations +, -, /, * . Most RDBMS support % modulo operator.

List of supported mathematical functions by SQL : ABS(x), SIGN(x), MOD(x,y), FLOOR(x), CEILING(x)/CEIL(x), POWER(x,y), ROUND(x), ROUND(x,d), SQRT(x), etc..

Mathematical Functions
Example :
SELECT round(salary), firstname FROM employee_info;

What data displayed by above query ????

Mathematical FunctionsExercise
Go to http://www.sqlcourse2.com/math.html
Do the Exercise

Table Join
Joins allow you to link data from two or more tables together into a single query result--from one single SELECT statement. A "Join" can be recognized in a SQL SELECT statement if it has more than one table after the FROM keyword.
select col1, col2 from table1, table2 where search-conditions

Table Join
Example :
SELECT customer_info.firstname, customer_info.lastname, purchases.item FROM customer_info, purchases WHERE customer_info.customer_number = purchases.customer_number;

What data displayed by above query ???? The particular Join is known as an Inner Join or Equijoin.

Mathematical FunctionsExercise
Go to http://www.sqlcourse2.com/joins.html
Do the Exercise

SQL Extension

Oracle PL/SQL Microsoft SQL Server T-SQL

Other kind DBMS


NoSQL (Not Only SQL) database (MongoDB) Object Relational Database (ORD) or Object Relational Database Management System (ORDBMS) : Support Object on the database schema Query Object using SQL

DBMS Tools

Object Relational Mapping Tools : NHibernate Hibernate Entity Framework .NET TOAD for Oracle TOAD for Microsoft SQL Server NavicateSQL etc

Cukup dulu sampai disini

Você também pode gostar