sql queries information

46
SQL (Structured Query Language) A LANGUAGE OF DATABASE

Upload: nishant-munjal

Post on 21-Apr-2017

79 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: SQL Queries Information

SQL (Structured Query Language)A LANGUAGE OF DATABASE

Page 2: SQL Queries Information

SQL OverviewSQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.

SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database.

Page 3: SQL Queries Information

Characteristics of SQL SQL allows the user to create, update, delete, and retrieve data from a database.

* SQL is very simple and easy to learn.

* SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.

Page 4: SQL Queries Information

Advantages of SQL• High Speed:

SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently.

• Well Defined Standards Exist:

SQL databases use long-established standard, which is being adopted by ANSI & ISO. Non-SQL databases do not adhere to any clear standard.

• No Coding Required:

Using standard SQL it is easier to manage database systems without having to write substantial amount of code.

•Emergence of ORDBMS:

Previously SQL databases were synonymous with relational database. With the emergence of Object Oriented DBMS, object storage capabilities are extended to relational databases.

Page 5: SQL Queries Information

Disadvantages of SQL• Difficulty in Interfacing:

Interfacing an SQL database is more complex than adding a few lines of code.

• More Features Implemented in Proprietary way:

Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary extensions to standard SQL to ensure vendor lock-in.

Page 6: SQL Queries Information

SQL Data Types1. BIGINT Data Type

2. BOOLEAN Data Type

3. CHAR Data Type

4. DECIMAL Data Type

5. DOUBLE Data Type

6. FLOAT Data Type

7. INT Data Type

8. SMALLINT Data Type

9. STRING Data Type

10. TIMESTAMP Data Type

11. TINYINT Data Type

12. VARCHAR Data Type

Page 7: SQL Queries Information

SQL LiteralsThe terms literal and constant value are synonymous and refer to a fixed data value

1. Numeric Literals

2. String Literals: String needs to be in single quotes

3. Boolean Literals: TRUE or FALSE

4. Timestamp Literals

5. NULL

Page 8: SQL Queries Information

String Literals

Use the text literal notation to specify values whenever 'string' or appears in the syntax of expressions, conditions, SQL functions, and SQL statements in other parts of this reference

'Hello'

'ORACLE.dbs‘

q'!name LIKE '%DBMS_%%'!'

q'<'So,' she said, 'It's finished.'>‘

Numeric Literals

You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL statements described in other parts of this reference. 25

+6.340.525e-03-1

25f+6.34F0.5d-1D

Page 9: SQL Queries Information

Date Time Literals

You can specify a DATE value as a string literal, or you can convert a character or numeric value to a date value with the TO_DATE function. DATE literals are the only case in which Oracle Database accepts a TO_DATE expression in place of a string literal.

To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal, as shown in this example:

DATE '1998-12-25‘

TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI')

Timestamp Literals

TIMESTAMP '1997-01-31 09:26:56.66 +02:00‘

TIMESTAMP '1999-04-15 8:00:00 US/Pacific‘ (with Zone)

Page 10: SQL Queries Information

Types of SQL Commands1. Data Definition Language

2. Data Manipulation Language

Page 11: SQL Queries Information

Data Definition Language(DDL) CREATE

Creates new databases, tables and views from RDBMS.

Create database tutorialspoint;Create table article;Create view for_students;

DROP

Drops commands, views, tables, and databases from RDBMS.

Drop object_type object_name;Drop database tutorialspoint;Drop table article;Drop view for_students;

ALTER

Modifies database schema.

This command adds an attribute in the relation article with the name subject of string type.

Alter table article add subject varchar;

Page 12: SQL Queries Information

Data Manipulation Language(DML)

SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all froms data modification in a database. SQL contains the following set of commands in its DML section −

1. SELECT/FROM/WHERE

2. INSERT INTO/VALUES

3. UPDATE/SET/WHERE

4. DELETE FROM/WHERE

These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options.

Select author_name From book_author Where age > 50; INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])

UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]

DELETE FROM table_name [WHERE condition];

Page 13: SQL Queries Information

Tables A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns. Here is a sample table called "weather".

city, state, high, and low are the columns. The rows contain the data for this table:

Weathercity state high lowPhoenix Arizona 105 90Tucson Arizona 101 92Flagstaff Arizona 88 69San Diego California 77 60Albuquerque New Mexico 80 72

Page 14: SQL Queries Information

Creating Table CREATE TABLE table_name(column_name1 data_type(size),column_name2 data_type(size),column_name3 data_type(size),....);

CREATE TABLE Persons(PersonID int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255));

Syntax Example

PersonID LastName FirstName Address City

Page 15: SQL Queries Information

Insert into Table INSERT INTO table_name (column1,column2,column3,...)VALUES (value1,value2,value3,...);

INSERT INTO persons(PersonID,LastName,FirstName,Address,City) VALUES(1011,’Mehta’,’Kunal’,’myaddress’,’Haridwar’);

CREATE TABLE persons(PersonID int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255));

PersonID LastName FirstName Address City1011 Mehta Kunal Myaddress Haridwar

Page 16: SQL Queries Information

SELECT STATEMENT• SELECT column_name,column_name FROM table_name;

• SELECT * FROM table_name;

CustomerID CustomerName ContactName Address City PostalCode Country

1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany

2 RAM Ana Trujillo Avda. de la Constitución 2222

México D.F. 05021 Mexico

3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

Page 17: SQL Queries Information

SELECT DISTINCT• In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values.

• The DISTINCT keyword can be used to return only distinct (different) values.

CustomerID CustomerName ContactName Address City PostalCode Country

1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany

2 RAM Ana Trujillo Avda. de la Constitución 2222

México D.F. 05021 Mexico

3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

SELECT DISTINCT column_name,column_name FROM table_name;

Page 18: SQL Queries Information

WHERE Clause The WHERE clause is used to extract only those records that fulfill a specified criterion.

SELECT column_name,column_nameFROM table_nameWHERE column_name operator value;

SELECT * FROM CustomersWHERE Country='Mexico';

CustomerID CustomerName City Country

1 HARI Berlin Germany

2 RAM México D.F. Mexico

3 SHYAM México D.F. Mexico

Page 19: SQL Queries Information

AND & OR Clause The AND operator displays a record if both the first condition AND the second condition are true.

The OR operator displays a record if either the first condition OR the second condition is true.

CustomerID CustomerName City Country

1 HARI Berlin Germany

2 RAM México D.F. Mexico

3 SHYAM México D.F. Mexico

SELECT * FROM CustomersWHERE Country='Germany'AND City='Berlin';

SELECT * FROM CustomersWHERE City='México D.F.'OR City='München';

SELECT * FROM CustomersWHERE Country='Germany'AND (City='Berlin' OR City='München');

Page 20: SQL Queries Information

DELETE STATEMENT DELETE FROM table_name WHERE some_column=some_value;

CustomerID CustomerName City PostalCode Country

1 HARI Berlin 12209 Germany

2 RAM México D.F. 05021 Mexico

3 SHYAM México D.F. 05023 Mexico

DELETE FROM Customers WHERE CustomerName=‘Hari’ AND City=‘Berlin';

DELETE FROM Customers WHERE CustomerName=‘Ram’ AND Country=‘Germany';

Page 21: SQL Queries Information

UPDATE UPDATE table_nameSET column1=value1,column2=value2,...WHERE some_column=some_value;

CustomerID CustomerName City PostalCode Country

1 HARI Berlin 12209 Germany

2 RAM México D.F. 05021 Mexico

3 SHYAM México D.F. 05021 Mexico

Page 22: SQL Queries Information

CustomerID CustomerName City PostalCode Country

1 HARI Berlin 12209 Germany

2 RAM México D.F. 05021 Mexico

3 SHYAM Hamburg 05021 Germany

UPDATE CustomersSET City=‘Hamburg’, COUNTRY=‘GERMANY’WHERE CustomerName=‘SHYAM’;

CustomerID CustomerName City PostalCode Country

1 HARI Hamburg 12209 Germany

2 RAM Hamburg 05021 Germany

3 SHYAM Hamburg 05021 Germany

UPDATE CustomersSET City=‘Hamburg', City=‘Germany';

Page 23: SQL Queries Information

ORDER BY Clause The ORDER BY keyword is used to sort the result-set by one or more columns.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.

SELECT column_name, column_nameFROM table_nameORDER BY column_name ASC|DESC;

SELECT * FROM CustomersORDER BY Country;

CustomerID CustomerName City Country

1 HARI Berlin Germany

2 RAM México D.F. Mexico

3 SHYAM México D.F. MexicoSELECT * FROM CustomersORDER BY Country DESC;

Page 24: SQL Queries Information

DROP & TRUNCATE DROP TABLE table_name

DROP DATABASE database_name

TRUNCATE TABLE table_name

Page 25: SQL Queries Information

ALTER TABLE STATEMENT ALTER TABLE table_nameADD column_name datatype

ALTER TABLE table_nameDROP COLUMN column_name

P_Id FirstName Address City

1 Ola Timoteivn 10 Sandnes

2 Tove Borgvn 23 Sandnes

3 Kari Storgt 20 Stavanger

ALTER TABLE PersonsADD DOB date

P_Id FirstName Address City DOB

1 Ola Timoteivn 10 Sandnes

2 Tove Borgvn 23 Sandnes

3 Kari Storgt 20 StavangerALTER TABLE Persons

ALTER COLUMN DOB year

Page 26: SQL Queries Information

Creating Views Syntax:

CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition

Example:

CREATE VIEW [Current Product List] ASSELECT ProductID,ProductNameFROM ProductsWHERE Discontinued=No

Query from View: SELECT * FROM [Current Product List]

Page 27: SQL Queries Information

Updating Views Syntax:

CREATE OR REPLACE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition

Example:

CREATE OR REPLACE VIEW [Current Product List] ASSELECT ProductID,ProductName,CategoryFROM ProductsWHERE Discontinued=No

Page 28: SQL Queries Information

Aggregate Functions1. AVG() - Returns the average value

2. COUNT() - Returns the number of rows

3. MAX() - Returns the largest value

4. MIN() - Returns the smallest value

5. SUM() - Returns the sum

Page 29: SQL Queries Information

SQL Scalar Functions1. UCASE() - Converts a field to upper case

a) SELECT UCASE(column_name) FROM table_name;

2. LCASE() - Converts a field to lower casea) SELECT LCASE(column_name) FROM table_name;

3. MID() - Extract characters from a text fielda) SELECT SUBSTRING(column_name,start,length) AS some_name FROM table_name;

4. LEN() - Returns the length of a text field

5. ROUND() - Rounds a numeric field to the number of decimals specified

6. NOW() - Returns the current system date and time

7. FORMAT() - Formats how a field is to be displayeda) SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate FROM Products;

Page 30: SQL Queries Information

LIKE The LIKE operator is used to search for a specified pattern in a column.

SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern;

SELECT * FROM CustomersWHERE City LIKE 's%';

SELECT * FROM CustomersWHERE Country LIKE '%land%';

SELECT * FROM CustomersWHERE Country NOT LIKE '%land%';

Page 31: SQL Queries Information

IN SELECT column_name(s)FROM table_nameWHERE column_name IN (value1,value2,...);

SELECT * FROM CustomersWHERE City IN ('Paris','London');

Page 32: SQL Queries Information

BETWEEN SELECT column_name(s)FROM table_nameWHERE column_name BETWEEN value1 AND value2;

SELECT * FROM ProductsWHERE Price BETWEEN 10 AND 20;

◦ SQL statement selects all products with a price BETWEEN 10 and 20

SELECT * FROM ProductsWHERE Price NOT BETWEEN 10 AND 20;

◦ To display the products outside the range of the previous example, use NOT BETWEEN

Page 33: SQL Queries Information

Joins An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

There are four types of JOINS.

1. INNER JOIN: Returns all rows when there is at least one match in BOTH tables

2. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

3. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

4. FULL JOIN: Return all rows when there is a match in ONE of the tables

Page 34: SQL Queries Information

Inner Join

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados

Ana Trujillo Mexico

3 Antonio Moreno Taquería

Antonio Moreno Mexico

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDateFROM OrdersINNER JOIN CustomersON Orders.CustomerID=Customers.CustomerID;

OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

Output:

Customers

Orders

Page 35: SQL Queries Information

… SELECT column_name(s)FROM table1INNER JOIN table2ON table1.column_name=table2.column_name;

SELECT column_name(s)FROM table1JOIN table2ON table1.column_name=table2.column_name;

Page 36: SQL Queries Information

Left Join The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.

Syntax:

SELECT column_name(s)FROM table1LEFT JOIN table2ON table1.column_name=table2.column_name;

or

SELECT column_name(s)FROM table1LEFT OUTER JOIN table2ON table1.column_name=table2.column_name;

Page 37: SQL Queries Information

… SELECT Customers.CustomerName, Orders.OrderIDFROM CustomersLEFT JOIN OrdersON Customers.CustomerID=Orders.CustomerIDORDER BY Customers.CustomerName;

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados

Ana Trujillo Mexico

3 Antonio Moreno Taquería

Antonio Moreno Mexico

CustomerName OrderID

Alfreds Futterkiste null

Ana Trujillo Emparedados y helados 10308

Antonio Moreno Taquería null

Customers

Orders

Output:

Page 38: SQL Queries Information

Right Join The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match.

SELECT column_name(s)FROM table1RIGHT JOIN table2ON table1.column_name=table2.column_name;

or

SELECT column_name(s)FROM table1RIGHT OUTER JOIN table2ON table1.column_name=table2.column_name;

Page 39: SQL Queries Information

… SELECT Orders.OrderID, Customers.CustomerNameFROM OrdersRIGHT JOIN CustomersON Orders.CustomerID=Customers.CustomerIDORDER BY Orders.OrderID;

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados

Ana Trujillo Mexico

3 Antonio Moreno Taquería

Antonio Moreno Mexico

Customers

Orders

Output:

OrderID CustomerName

Alfreds Futterkiste

10309 Ana Trujillo Emparedados y helados

Antonio Moreno Taquería

Page 40: SQL Queries Information

Full Join or Full Outer Join• The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).

• The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

SELECT column_name(s)FROM table1FULL OUTER JOIN table2ON table1.column_name=table2.column_name;

Page 41: SQL Queries Information

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados

Ana Trujillo Mexico

3 Antonio Moreno Taquería

Antonio Moreno Mexico

Customers

Orders

Output:

SELECT Customers.CustomerName, Orders.OrderIDFROM CustomersFULL OUTER JOIN OrdersON Customers.CustomerID=Orders.CustomerIDORDER BY Customers.CustomerName;

CustomerName OrderID

Alfreds Futterkiste

Ana Trujillo Emparedados y helados 10308

Antonio Moreno Taquería

10309

10310

Page 42: SQL Queries Information

Union The UNION operator is used to combine the result-set of two or more SELECT statements.

SELECT City FROM CustomersUNIONSELECT City FROM SuppliersORDER BY City;

SELECT column_name(s) FROM table1UNION ALLSELECT column_name(s) FROM table2;

SELECT column_name(s) FROM table1UNIONSELECT column_name(s) FROM table2;

Syntax:

This will list all the DISTINCT city names from both the tables.

Output:Query:

SELECT City FROM CustomersUNION ALLSELECT City FROM SuppliersORDER BY City;

SELECT column_name(s) FROM table1UNION ALLSELECT column_name(s) FROM table2;

Syntax:

This will list all the city names includes duplicate from both the tables.

Output:Query:

Page 43: SQL Queries Information

SQL Operators1. Arithmetic Operators

2. BETWEEN Operator

3. Comparison Operators

4. EXISTS Operator

5. IN Operator

6. IS NULL Operator

7. LIKE Operator

8. Logical Operators

9. REGEXP Operator

10. RLIKE Operator

Page 44: SQL Queries Information

Intersection

Page 45: SQL Queries Information

Minus

Page 46: SQL Queries Information

THANKS