basic sql introduction presented by: madhuri bhogadi

28
Basic SQL Introduction Presented by: Madhuri Bhogadi

Upload: ciara-ingold

Post on 14-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Basic SQL Introduction Presented by: Madhuri Bhogadi

Basic SQL Introduction

Presented by: Madhuri Bhogadi

Page 2: Basic SQL Introduction Presented by: Madhuri Bhogadi

Overview

• Introduction1• Data Query Language

( SELECT)2• Operators3• Functions4• Joins5

Page 3: Basic SQL Introduction Presented by: Madhuri Bhogadi

What is SQL?

SQL is Structured Query Language, is a computer language for storing, manipulating and retrieving data stored in relational database.

Page 4: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL CommandsThe SQL commands to interact with databases are classified into 4 groups:

• DDL - Data Definition LanguageCREATE, ALTER, DROP

• DML - Data Manipulation LanguageINSERT, UPDATE, DELETE

• DCL - Data Control Language GRANT, REVOKE

• DQL - Data Query LanguageSELECT

Page 5: Basic SQL Introduction Presented by: Madhuri Bhogadi

DQL - Data Query Language

SELECTSyntax:

SELECT column1, column2,………, columnN FROM table_name WHERE [ CONDITION | EXPRESSION ];

Example: SELECT * from CustomerSELECT [cust-no],[name],[address],[city],

[st],telephone from customer where

active='a'

Page 6: Basic SQL Introduction Presented by: Madhuri Bhogadi

WHERE ClauseThe SQL WHERE clause is used to specify a condition

while fetching the data from single table or joining with multiple tables.

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc. We can specify condition using >, <, =,LIKE , ODER BY,GROUP BY,HAVING Etc.

Syntax : SELECT column1, column2, columnN FROM table_name WHERE [condition]

Example : Select * from customer WHERE [cust-no]='davis'

Page 7: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL OperatorsAn operator is a reserved word or

character used in SQL statement's WHERE clause to perform operation(s).

SELECT column1, column2,………. columnN FROM table_name WHERE [condition]

They are :• Arithmetic operators• Comparison operators• Logical operators

Page 8: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL Arithmetic OperatorsOperators : + , - , * , / , %

Examples:

select * from [invoice] where [gross-amt]+[add-charges]

>1000

select * from [invoice] where [gross-amt]-[add-charges]>0

select * from [invoice] where [tax-

amt__1]*0.5>0

Page 9: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL Comparison OperatorsOperators : = , != , <> , > , < ,>= ,<= ,!< ,!>

Examples:

Select * from customer where [cust-no]='davis'

Select * from customer where [cust-no]!='davis'

select * from [invoice] where [gross-amt]>100

select * from [invoice] where [gross-amt]<0

Page 10: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL Logical Operators

Operators : AND , BETWEEN ,EXISTS,IN,LIKE,NOT, OR,IS NULL

Examples:

select * from [invoice] where [gross-amt]>0 and [add-charges]>0

select * from [invoice] where [gross-amt] between 0 and 10000

select * from [sa] where [cancel-date] is null

Page 11: Basic SQL Introduction Presented by: Madhuri Bhogadi

Sorting the DataThe SQL ORDER BY clause is used to sort the

data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default. We can use more than one column in the ORDER BY clause. Syntax:SELECT column(s) FROM table_name [WHERE condition] [ORDER BY column1, .. columnN] [ASC | DESC]

Examples:

Select * from customer order by [cust-no] descSelect * from invoice order by [cust-no],

[document] ASC

Page 12: Basic SQL Introduction Presented by: Madhuri Bhogadi

Group By ClauseThe SQL GROUP BY clause is used in collaboration

with the SELECT statement to arrange identical data into groups . Group by can be used with WHERE ,ORDER BY clause as an optional.

Syntax:SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 ORDER BY column1, column2

SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name HAVING (arithematic function condition)

Examples:Select [cust-no] from [invoice] group by [cust-no]Select [cust-no] from invoice group by [cust-no]

having count(*)>1

Page 13: Basic SQL Introduction Presented by: Madhuri Bhogadi

Like ClauseThe SQL LIKE clause is used to compare a value to

similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator:The percent sign (%) : The percent sign represents zero, one, or multiple characters. The underscore (_) : The underscore represents a single number or character.

Examples:Select * from [invoice] WHERE document like '111%'Select * from [invoice] WHERE document like '%111%'Select * from [invoice] WHERE document like '%111%'Select * from [invoice] WHERE document like '5__6%'Select * from [invoice] WHERE document like '5__000'

Page 14: Basic SQL Introduction Presented by: Madhuri Bhogadi

FunctionsSQL has many built-in functions for performing processing on string or numeric data.

Following is the list of all useful built-in functions:• Aggregate• Date• String • Numeric

Page 15: Basic SQL Introduction Presented by: Madhuri Bhogadi

Aggregate FunctionsThey summarize the results of a particular column of selected numeric data. They are COUNT ,MAX,MIN,AVG and SUM. These can be used with Group By as well.

Examples:

select count(*) from customerselect max([ar-balance]) from [customer-d]select min([ar-balance]) from [customer-d]select avg([ar-balance]) from [customer-d]select sum([ar-balance]) from [customer-d]select [cust-no],sum([ar-balance]) from [customer-d]

group by [cust-no]

Page 16: Basic SQL Introduction Presented by: Madhuri Bhogadi

Date FunctionsThey are quite a few in-built date functions like GETDATE, DAY , MONTH, YEAR ,DATENAME, DATEADD , DATEDIFF etc.GETDATE - Gives current date time stampDAY - Returns an integer representing the day (day of the month) of the specified dateMONTH - Returns an integer that represents the month of the specified dateYEAR - Returns an integer that represents the year of the specified dateDATENAME - Syntax: DATENAME ( datepart , date ) where the datepart is DAY,MONTH,YEAR, WEEK, WEEKDAY Etc.DATEADD - Returns a specified date with the integer added to a specified datepart of that date.

Syntax: DATEADD (datepart , number , date ) DATEDIFF- Returns the count of the specified datepart between the specified start date and end date.

Syntax: DATEDIFF (datepart,startdate,enddate) Examples:

select GETDATE ()select * from invoice where DAY([invoice-date])=1select * from invoice where DAY([invoice-date])=1 and MONTH([invoice-date])=10select * from invoice where DAY([invoice-date])=1 and MONTH([invoice-date])=10

and YEAR([invoice-date])=2013

select * from invoice where DATENAME(week,[invoice-date])=4 and MONTH([invoice-date])=1

select * from invoice where DATENAME(weekday,[invoice-date])='sunday' and MONTH([invoice-date])=1

select * from invoice where DATEADD(YEAR,1,[invoice-date])=2014select * from invoice where DATEDIFF(day,[invoice-date],[due-date])>10

Page 17: Basic SQL Introduction Presented by: Madhuri Bhogadi

String Functions SQL string functions are used primarily for string manipulation. The following are the important string functions:CHARINDEX Returns the starting position of a character string.LEFT Returns the leftmost number of characters as specifiedRIGHT Returns the specified rightmost number of characters SUBSTRING Returns the substring as specifiedLTRIM/RTRIM Removes leading and trailing spaces LOWER Returns the argument in lowercase UPPER Converts to uppercaseLEN Returns the length of a string in bytesREVERSE Returns reverse a string. REPLACE Replaces occurrences of a specified string Examples:

Select * from customer where CHARINDEX('Davis', Name)>0Select * from customer where SUBSTRING( Name , 1,4)='david'Select * from customer where LEN( City )=15Select UPPER(name) from customerSelect LOWER(name) from customerSelect LTRIM(name) from customerSelect LEFT(name,5),* from customerSelect RIGHT(name,10),* from customerSelect REVERSE(name) from customer

Page 18: Basic SQL Introduction Presented by: Madhuri Bhogadi

Numeric FunctionsSQL numeric functions are used for numeric manipulation or mathematical calculation.

CEILING Returns the smallest integer value that is not less than passed numeric expression. FLOOR Returns the largest integer value that is not greater than passed numeric expression.ROUND Returns numeric expression rounded to an integer. Can be used to round an expression to a number of decimal points Examples:

select CEILING([gross-amt]) 'Gross Amt',* from [sa-inv]

select FLOOR([gross-amt]) 'Gross Amt',* from [sa-inv] select ROUND([gross-amt],3) 'Gross Amt',* from [sa-

inv]

Page 19: Basic SQL Introduction Presented by: Madhuri Bhogadi

Joins The SQL Join clause is used to combine records from multiple tables in a database. We can join with join two, three or n number tables.

There are different types of joins available in SQL:

INNER JOIN : Returns rows when there is a match in both tables.

LEFT JOIN : Returns all rows from the left table, even if there are no matches in the right table.

RIGHT JOIN : Returns all rows from the right table, even if there are no matches in the left table.

Page 20: Basic SQL Introduction Presented by: Madhuri Bhogadi

Inner JoinThe most frequently used and important of the joins is the INNER JOIN. They are also referred to as an EQUIJOIN.The INNER JOIN creates a new result table by combining column values of two tables.

Syntax:SELECT table1.column1, table2.column2... FROM table1 INNER JOIN table2 ON table1.common_filed = table2.common_field

Example:SELECT customer.[cust-no],[customer-d].[ar-balance] from customer INNER JOIN [customer-d] on customer.[cust-no]=[customer-d].[cust-no]WHERE active='a' and [customer-d].[ar-balance]>1000

SELECT c.[cust-no],d.[ar-balance] from customer c with(nolock)INNER JOIN [customer-d] d with(nolock) on c.[cust-no]=d.[cust-no]WHERE c.active='a' and d.[ar-balance]>1000

SELECT [job].[cust-no],[job].[job-no],[jc-inv].[document],[ar-term].[Term-desc],[jc-inv].[gross-amt]+[jc-inv].[add-charges] 'Inv Amt' from [job] with(nolock)INNER JOIN [jc-inv] with(nolock) on [job].[job-no]=[jc-inv].[job-no]INNER JOIN [ar-term] with(nolock) on [job].[term-code]=[ar-term].[term-code]WHERE [job].[statuscode]='open'

Page 21: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL - Sub QueriesA Subquery or Nested query is a query within another SQL query and with WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further filter the data to be retrieved.

Sub queries are used with SELECT, INSERT, UPDATE, and DELETE statements with the operators like =, <, >, >=, <=, IN, BETWEEN etc.

Here are a few rules that subqueries must follow:• Subqueries must be enclosed within parentheses.• A subquery can have only one column in the SELECT clause, unless multiple columns are in the

main query for the subquery to compare its selected columns.• An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The

GROUP BY can be used to perform the same function as the ORDER BY in a subquery.• Subqueries that return more than one row can only be used with multiple value operators, such

as the IN operator.

Syntax:SELECT column_name [, column_name ] FROM table1 WHERE column_name OPERATOR (SELECT column_name FROM table2 [WHERE])

Example:select * from "item" where "item-no" in (select "whs-code" from warehouse)select * from "item" where "item-no" not in (select "whs-code" from warehouse)

Page 22: Basic SQL Introduction Presented by: Madhuri Bhogadi

DML - Data Manipulation Language

DML is used to modify, delete, insert data in database. DML Commands are INSERT, UPDATE, and DELETE.

UPDATE :The SQL UPDATE Query is used to modify the existing records in a table.You have to use WHERE clause with UPDATE query to update selected rows otherwise all the rows will be updated.

Syntax:UPDATE table_name SET column1 = value1, column2 = value2....,

columnN = valueN WHERE [condition]

Example:update [sctype] set [price]=100 where [sctype]='Test'update [sctype] set [price]=100 where [sctype] in

('Test','Test1','Test2')

Page 23: Basic SQL Introduction Presented by: Madhuri Bhogadi

SQL Server Management Studio

1. Click on the Shortcut on your desktop if you have one.

2. Go to Start / All Programs / Microsoft SQL Server 2008 ( or your version) / SQL Server Management Studio.

3. Once you click on that it will ask you for the server name Authentication ( User/Password ) .

How to access SQL Management Studio ?

OR

Page 24: Basic SQL Introduction Presented by: Madhuri Bhogadi

New Query From SQL Editor Click on the New Query as you screen in the screen shot.

You will have the editor for writing the queries.

By default it will be master database you have to choose the database where you would like to. In Global Edge we choose either Service or ServiceTR.

Page 25: Basic SQL Introduction Presented by: Madhuri Bhogadi

Query Output How to Execute your query?

Once you are done writing you select statement or Query you can either press F5 or use Execute Button on the editor to get the output.

What else you can do with the Results other than seeing on the screen?

Click on top of the query results or left side to see the options that are available.

We can copy the results (with header columns or with out header columns) to any other file like excel.

OR

You can save to file directly

OR

Print.

Page 26: Basic SQL Introduction Presented by: Madhuri Bhogadi

Summary

Query with :

Select WhereGroup ByOrder By Joining multiple tables

Page 27: Basic SQL Introduction Presented by: Madhuri Bhogadi

Questions?

Page 28: Basic SQL Introduction Presented by: Madhuri Bhogadi

Thank You