Professional Documents
Culture Documents
SQL
SQL allows users to access data in relational database management systems, such as Oracle,Informix,Sybase, Microsoft SQL Server, Access etc. SQL allows users to manipulate and define the data in a database. SQL is an ANSI standard computer language
Data Definition Language. In DDL user define the structure and organization of the stored data and relationships among the stored data items. Data Retrieval Language. An application program to retrieve stored data from the database and use it. Data Manipulation Language. DML allows a user or an application program to update the database by adding new data, removing old data, and modifying previously stored data. Data Control Language. DCL can be used to restrict a users ability to retrieve, add, and modify data, protecting stored data against unauthorized access. Data sharing. Is used to coordinate data sharing by concurrent users, ensuring that they do not interfere with one another. Data intigrity.It defines integrity constraints in the database, protecting it from
SQL Queries
Query is a loose term that refers to a widely available set of SQL commands called clauses. Each clause or command performs some sort of function against the database. For instance, the create clause creates tables in databse and the select clause selects rows that have been inserted into your tables. Construction of Query begins with one of the following clauses:
SQL Query Syntax The syntax of a query is loose, meaning you are free to place line breaks and spacing where you please without injuring the code.Few instances require parentheses, including the insert statement listed below. Parentheses will also be covered during our Functions lesson. Be sure to end all query statements with a semicolon (;). SQL Code: SELECT * FROM table_name;
SEARCH TUTORIALS:
Search
Select Command
Select command is use to select data from the tables located in a database.If we need to SELECT information FROM a table. The most basic SQL structure:
ADVERTISEMENT
To illustrate the above example, assume that we have the following table Name "Store_Information" :
Outp ut
Distinct Keyword:
The SELECT keyword allows us to take all information from a column (or columns) on a table. Of course, there is probability of redundancies. What if we only want to select each DISTINCT element? This is easy to accomplish in SQL. All we need to do is to add DISTINCT after SELECT. The syntax is as follows:
Outp ut
SEARCH TUTORIALS:
Search
WHERE Syntax
To conditionally select the data from a table the WHERE clause is used . eg.if we want to retrieve stores with sales above $1,000. To do this, we use the WHERE keyword. The syntax is as follows:
SELECT "column_name" FROM "table_name"
WHERE "condition"
For example, to select all stores with sales above $1,000 in Table Store_Information.
SQL command
SELECT store_name FROM Store_Information WHERE Sales > 1000
Notes: SQL uses single quotes around string values (most database systems will also accept double quotes). Numeric values not be enclosed in quotes. Output
store_name Los Angeles
Description Equal Not equal Greater than Less than Greater than or equal Less than or equal Between an inclusive range Search for a pattern
SEARCH TUTORIALS:
Search
Insert Command
The insert clause has one function; to insert data into a table. Insert populates each table column with a value. Rows are inserted one right after another into the coresponding column.
ADVERTISEMENT
SQL Code:
Output
Lastname Johnson
Firstname David
Title crew
INSERT INTO employees (Lastname,Firstname,Title) VALUES('Hively','Jessica',DEFAULT); or INSERT INTO employees (Lastname,Firstname,Title) VALUES('Hively','Jessica',NULL);
SEARCH TUTORIALS:
Search
Update Command
This command updates the column values of a table. >Update requires a conditional statement for selecting the row which is to be updated.
ADVERTISEMENT
SEARCH TUTORIALS:
Search
Syntax:
Delete may use with SQL operators as well as subqueries to delete any or all rows that apply to our conditional.
Syntax
Syntax:
SEARCH TUTORIALS:
Search
Order By Command
ADVERTISEMENT
The order by statement allows for table column range. It allows for ascending or descending lists of column values, permitting SQL to reorder your table rows for the purpose of viewing.
Syntax:
Output:-
Output:-
Johnson Davis
David Julie
crew manager
SEARCH TUTORIALS:
Search
WHERE keyword might be used to conditionally select data from a table. This condition can be a simple condition or it can be a compound condition.Compound conditions are made up of multiple simple conditions connected by AND/OR. There is no limit to the number of conditions that can be present in a single SQL statement.
Syntax of Compound condition
Note:-The {}+ means that the expression inside the bracket will occur one or many times.AND and OR can be used interchangeably. In addition,to indicate the order of the condition we may use the parenthesis sign ().
e.g. we may wish to select all store_name with sales greater than $1,000 or all stores with sales less than $500 but greater than $275 in Table Store_Information,
SELECT store_name FROM Store_Information WHERE Sales > 1000 OR (Sales < 500 AND Sales > 275)
Outp ut
San Francisco
SQL In Operator
SEARCH TUTORIALS:
Search
SQL In Operator
ADVERTISEMENT
In is a special kind of operator which uses with where clauses. In the where expression only one value is allowed to be sent through the query. With help of in operator you can send multiple values in the where clause.
The syntax of IN keyword is as follows:
Syntax
Let's you wish to select all records for the Los Angeles and the San Diego stores in Table Store_Information,
The Values inside parenthesis can be one or more, with each values separated by comma. Values can be characters or numerical. If there is only one value inside the parenthesis, then command is equivalent to :-
Comma nd
Output
Store_name
Sales
Date
$1500 $250
Jan-05-2005 Jan-07-2005
SQL Between
SEARCH TUTORIALS:
Search
SQL - Between
ADVERTISEMENT
The BETWEEN keyword allows for selecting a values in range. The syntax for the BETWEEN clause is given below
Syntax:
It select all rows whose column has a value between 'value1' and 'value2'. For example,to select all sales information between January 6, 2005, and January 10, 2005, in Table Store_Information
Syntax
Sales $250
Date Jan-07-2005
$300 $700
Jan-08-2005 Jan-08-2005
SQL Aliases
SEARCH TUTORIALS:
Search
SQL Alias
Most frequently two types of aliases are used:
Example:
Column aliases exist to organizing output.In the previous example, whenever there is total sales, it is listed as SUM(sales). While this is understandable, we can have many cases where the column heading can be complicated (especially if it involves several arithmetic operations). Using a column alias its make the output much more readable. Second is the table alias.This is accomplished by putting an alias directly after the table name in the FROM clause. This is convenient when you want to obtain information from two separate tables ('perform joins'). The advantage of using a table alias when doing joins is readily apparent when we talk about joins. Both types of aliases are placed directly after the item they alias for, separate by a white space. We again use our table, Store_Information,
Syntax
SELECT A1.store_name Store, SUM(A1.Sales) "Total Sales" FROM Store_Information A1 GROUP BY A1.store_name
Output
Notice that difference in the result that the column titles are now different. That is the result of using the column alias. Notice that instead of the somewhat cryptic "Sum(Sales)", we now have "Total Sales", which is much more understandable, as the column header. The advantage of using a table alias is not visible in this example. However, they will become evident in the Join Section
SQL Join
SEARCH TUTORIALS:
Search
SQL Join
To create a single table the join clause combines columns of one table to that of another. Join matches up a column with one table to a column in another.
ADVERTISEMENT
A join query does not alter table, but temporarily combines data from each table to be viewed as a single table.Mainly three types of join statements:
Inner Join :An inner join returns all matching rows.For example given below
Table:-Store_Information
Table:-Geography
Let us we want to find out sales by region. For geting the sales information by region, we have to combine the information from the two tables.Examining the two tables, we find that they are linked via the common field, "store_name". First present the SQL Query and then explain the use:
SELECT A1.region_name REGION, SUM(A2.Sales) SALES FROM Geography A1, Store_Information A2 WHERE A1.store_name = A2.store_name GROUP BY A1.region_name
West
$2050
The first two lines tell SQL to select two fields, the first one is the field "region_name" from table Geography (aliased as REGION), and the second one is the sum of the field "Sales" from table Store_Information (aliased as SALES). Notice how the table aliases are used here: Geography is aliased as A1, and Store_Information is aliased as A2. Without the aliasing, the first line would become
which is much more bulky. In essence, table aliases make the entire SQL statement easier to understand, especially when multiple tables are included. Next, we turn our attention to line 3, the WHERE statement. This is where the condition of the join is specified. In this case, we want to make sure that the content in "store_name" in table Geography matches that in table Store_Information, and the way to do it is to set them equal. This WHERE statement is essential in making sure you get the correct output. Without the correct WHERE statement, a Cartesian Join will result. Cartesian joins will result in the query returning every possible combination of the two (or whatever the number of tables in the FROM statement) tables. In this case, a Cartesian join would result in a total of 4 x 4 = 16 rows being returned.
A Left join returns all rows of the left of the conditional even if there is no right column to match.
A right join will display rows on the right side of the conditional that may or may not have a match.
SEARCH TUTORIALS:
Search
Previously, we had looked at inner join, where we select rows common to the participating tables to a join. One case is that if we are interested in selecting elements in a table regardless of whether they are present in the second table? We will now need to use the SQL OUTER JOIN command.
Example:
The syntax for performing an outer join in SQL is database-dependent. For example, in Oracle, we will place an "(+)" in the WHERE clause on the other side of the table for which we want to include all the rows. Let's we have the following two tables,
Table:-Store_Information
$300 $700
Jan-08-2005 Jan-08-2005
Table:-Geography
If we want to find out sales by region. We see that table Geography includes information on regions and stores, and table Store_Information contains sales information for each store. To get the sales information by region, we have to combine the information from the two tables. Examining the two tables, we find that they are linked via the common field, "store_name".
SELECT A1.store_name, SUM(A2.Sales) SALES FROM Geography A1, Store_Information A2 WHERE A1.store_name = A2.store_name (+) GROUP BY A1.store_name
Output:Store_name Boston New York Los Angeles San Diego $1800 $250 SALES $700
Note: When there is no match on the second table NULL is returned . In this case, "New York" does not appear in the table Store_Information, thus its corresponding "SALES" column is NULL.
SQL Union
SEARCH TUTORIALS:
Search
SQL Union
SQL UNION combine the results of two queries together.
ADVERTISEMENT
In this respect, UNION is similar to JOIN in that they are both used to related information from multiple tables. One restriction of UNION is that all corresponding columns need to be of the same data type and UNION only select distinct values.
Syntax:
[SQL Statement 1] UNION [SQL Statement 2]
Table Store_Information
Store_name Los Angeles San Diego Los Angeles Boston Sales $1500 $250 $300 $700 Date Jan-05-2005 Jan-07-2005 Jan-08-2005 Jan-08-2005
Table Internet_Sales
Date Jan-07-2005 Jan-10-2005 Jan-11-2005 Jan-12-2005 Sales $250 $535 $320 $750
If we want to find out all the dates where there is a sales transaction.We use the following SQL statement:
Outpu t:
Synta x:
SELECT Date FROM Store_Information UNION ALL SELECT Date FROM Internet_Sales
Outpu t:
SQL Subqueries
SEARCH TUTORIALS:
Search
SQL Subqueries
MySQL offers a very limited support for subqueries, however Oracle and DB2 fully support them. They may exist in any of the following types of SQL statements.
Syntax:
SELECT "column_name1" FROM "table_name1" WHERE "column_name2" [Comparison Operator] (SELECT "column_name3" FROM "table_name2" WHERE [Condition])
Example:
Table: Store_Information
Store_name Los Angeles San Diego Los Angeles Boston Sales $1500 $250 $300 $700 Date Jan-05-2005 Jan-07-2005 Jan-08-2005 Jan-08-2005
Table: Internet_Sales
If we want to use a subquery to find the sales of all stores in the West region. Then we use the following SQL statement:
SELECT SUM(Sales) FROM Store_Information WHERE Store_name IN (SELECT store_name FROM Geography WHERE region_name = 'West')
Output:
SUM(Sales) 2050
Here instead of joining the two tables directly and then adding up only the sales amount for stores in the West region, we use subquery to find out which stores are in the West region and then add the sales amount for these stores.
SEARCH TUTORIALS:
Search
SQL Dates
All SQL platform has its own version of date functions.
ADVERTISEMENT
SQL - Timestamp
A timestamp servers as the catch all for dates and times. Retrieving a timestamp is very simple and the result can be manipulated in nearly every way possible.
Syntax:
Select Current_Timestamp;
Return a Timestamp:
2005-06-22 11:33:11.840
SELECT MONTH(CURRENT_TIMESTAMP);- Return a Month(6) SELECT DAY(CURRENT_TIMESTAMP);-Return a Day:(22) SELECT DATE(CURRENT_TIMESTAMP); - returns a date (2004-06-22) SELECT TIME(CURRENT_TIMESTAMP); - returns the time (10:33:11.840) SELECT DAYOFWEEK(CURRENT_TIMESTAMP); - returns a numeric value (1-7) SELECT DAYOFMONTH(CURRENT_TIMESTAMP); - returns a day of month (1-31) SELECT DAYOFYEAR(CURRENT_TIMESTAMP); - returns the day of the year (1-365)
SELECT MONTHNAME(CURRENT_TIMESTAMP); - returns the month name (January December) SELECT DAYNAME(CURRENT_TIMESTAMP); - returns the name of the day (Sunday Saturday) SELECT WEEK(CURRENT_TIMESTAMP); - returns number of the week (1-53)
SEARCH TUTORIALS:
Search
Tables are divided into rows and columns. Each row represents one piece of data,
and each column represent a component of piece of data.Example, if we have a table for recording customer information, then the columns may include information such as First Name, Last Name, birth Date, Address, City, Country, and so on. As a result, when we specify a table, we include the column headers and the data types for that particular column. Data comes in a variety of forms. It could be an integer (such as 1), a real number (such as 0.55), a date/time expression (such as '2000-JAN-25 03:22:22'),a string (such as 'sql'), or even in binary format. When we specify a table, we need to specify the data type associated with each column (i.e., we will specify that 'First Name' is of type char(40) - meaning it is a string with 40 characters). One thing to note is that different relational databases allow for different data types.
Synt ax
CREATE TABLE "table_name" ("column 1" "data_type_for_column_1", "column 2" "data_type_for_column_2", ... )
Examp le
CREATE TABLE customer (First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date date)
Example
Primary Key
A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself , or it can be an artificial field (one that has nothing to do with the actual record). A primary key consist of one or more fields on a table. When multiple fields are used as a primary key then it is called composite key. Primary keys can be specified either when the table is created or by changing the existing table structure with alter command.
CREATE TABLE Customer (SID integer, Last_Name varchar(30), First_Name varchar(30), PRIMARY KEY (SID));
Foreign Key
A foreign key is a field that points to the primary key of another table. The purpose of the foreign key is to ensure referential integrity means only values that are supposed to appear in the database are permitted. For example, say we have two tables, a CUSTOMER table that includes all customer data, and an ORDERS table that includes all customer orders. The constraint here is that all orders must be associated with a customer that is already in the CUSTOMER table. In this case, we will place a foreign key on the ORDERS table and have it relate to the primary key of the CUSTOMER table. By this way, we can ensure that all orders in the ORDERS table are related to a customer in the CUSTOMER table. In other words, the ORDERS table cannot contain information on a customer that is not in the CUSTOMER table. Both Table is given below:-
Table CUSTOMERS
Table ORDERS
Customer_SID Amount
Foreign Key
In the above example, the Customer_SID column in the ORDERS table is a foreign key pointing to the SID column in the CUSTOMER table. Syntax
CREATE TABLE ORDERS (Order_ID integer, Order_Date date, Customer_SID integer, Amount double, Primary Key (Order_ID), Foreign Key (Customer_SID) references CUSTOMER(SID));
SEARCH TUTORIALS:
Search
Drop Index
You can delete an existing index in a table with the DROP INDEX statement. Syntax: Microsoft Access
Syntax: MySQL
To delete a database:
SQL Alter
SEARCH TUTORIALS:
Search
Once a table is created in the database, there are many condition where we have to change the structure of the table.
Add a column Drop a column Change a column name Change the data type for a column changing the primary key specification
Syntax
If we want to add a column called "Gender" to this table. Syntax given below:
If we want to change the data type for "Addr" to char(30).Syntax given below:
SQL Function
SEARCH TUTORIALS:
Search
SQL Functions
A function is a special type of command that return a single value.
ADVERTISEMENT
Types of Functions
The basic types of functions are:
Aggregate functions It operate against a collection of values, but return a single Value.
Scalar functions It operate against a single value, and return a single value based on the input value.Functions like CURRENT_TIME for example, do not require any arguments.
Syntax:
SELECT function(column) FROM table
Aggregate Functions
It return a single value based upon a set of other values. If used among many other expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY clause. No GROUP BY clause is required if the aggregate function is the only value retrieved by the SELECT statement
Supported aggregate functions are:
Function AVG(expression)
COUNT(expression) Counts the rows defined by the expression COUNT(*) MIN(expression) MAX(expression) SUM(expression) Counts all rows in the specified table or view Finds the minimum value in a column by the expression Finds the maximum value in a column by the expression Computes the sum of column values by the expression
Examp
Scalar Functions
Different categories of Scalar Function are:
Built-in Function Date & Time Function Numeric Function String Function
Description Converts a field to upper case Converts a field to lower case Extract characters from a text field Returns the length of a text field Returns the numeric position of a named character within a text field
LEFT(c,number_of_cha Return the left part of a text field requested r) RIGHT(c,number_of_c Return the right part of a text field requested har) ROUND(c,decimals) MOD(x,y) Rounds a numeric field to the number of decimals specified Returns the remainder of a division operation
NOW() FORMAT(c,format)
Returns the current system date Changes the way a field is displayed
SEARCH TUTORIALS:
Search
Group By clause
When Aggregate functions (like SUM) called it return the aggregate of all column values.It was impossible to find the sum for each individual group of column values so Group By clause used.
ADVERTISEMENT
Synta x:
Output
Boston
$700
The GROUP BY keyword is used when selecting multiple columns from tables and at least one arithmetic operator appears in the SELECT statement.
Having Clause
To limit the output based on the corresponding sum (or any other aggregate functions). For example, we might want to see only the stores with sales over $1,500. Instead of using the WHERE clause in the SQL statement, though, we need to use the HAVING clause, which is reserved for aggregate functions. The HAVING clause is placed near the end of the SQL statement. SQL statement with the HAVING clause may or may not include the GROUP BY clause.
Syntax: Having Clause
SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" HAVING (arithmetic function condition)
SELECT store_name, SUM(sales) FROM Store_Information GROUP BY store_name HAVING SUM(sales) > 1500
Output
SUM(Sales) $1800
SEARCH TUTORIALS:
Search
To create a make-table query means for making backup copies of tables and reports, or for archiving records.
Synt ax
Make a Backup Copy The example given below makes a backup copy of the "Persons" table:
If you only want to copy a few fields not copy whole Table, you can do so by listing them after the SELECT statement. The following query creates a Fiddlers table by extracting the names of fiddlers from a Musicians table:
The fields which you copy into a new table need not come from just one table. You can copy from multiple tables as demonstrated in the next example which selects fields from the two tables Suppliers and Products to create a new table for Mexican Suppliers:
SELECT Suppliers.Name, Product, Products.UnitPrice INTO [Mexican Suppliers] FROM Suppliers INNER JOIN Products ON Suppliers.ProductID = Products.ProductID WHERE Suppliers.Country = 'Mexico';
The SELECT...INTO statement doesn't define a primary key for the new table, so you may want to do that manually.
SEARCH TUTORIALS:
Search
View?
ADVERTISEMENT
A VIEW is a virtual table based on the result-set of a SELECT statement. A view contains rows and columns like a real table. The fields in a view consist fields from one or more real tables in the database.
Syntax:
Views may be considered as virtual tables. Generalize way a table has a set of definition, and it physically stores the data. A view also has a set of definitions, which is build on top of table(s) or other view(s), and it does not physically store the data.
Examp le:
TABLE Customer (First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date date)
and we want to create a view called V_Customer that contains only the First_Name, Last_Name, and Country columns from this table, we would type in,
To joins two or more tables view can be used. In this case, users only see one view rather than two tables, and the SQL statement users need to issue becomes much simpler. Let's say we have the following two tables:
Table:Store_Inform ation Store_name Los Angeles San Diego Los Angeles Boston Sales $1500 $250 $300 $700 Date Jan-05-2005 Jan-07-2005 Jan-08-2005 Jan-08-2005
Table:
Geography
region_name East
store_name Boston
If we want to build a view that has sales by region information. We would issue the following SQL statement:
CREATE VIEW V_REGION_SALES AS SELECT A1.region_name REGION, SUM(A2.Sales) SALES FROM Geography A1, Store_Information A2 WHERE A1.store_name = A2.store_name GROUP BY A1.region_name
It gives a view called V_REGION_SALES, that has been defined to store sales by region records. If we want to find out the content of this view then following query:
SQL Server
SEARCH TUTORIALS:
Search
SQL Servers - RDBMS Modern SQL Servers used Relational Data Base Management System.
ADVERTISEMENT
A DBMS is a computer program that can access data from a database. The DBMS program enables you to modify,store and extract information from a database. DBMS programs provides different functions for querying data, modifying data and reporting data.
A RDBMS is a Database Management System where the database is organized and accessed according to the relationships between data stored in table. it was invented by IBM in the early 1970's. RDBMS is the base of SQL for all modern database systems like Oracle, SQL Server, IBM DB2, Mesql, Sybase and Microsoft Access.
SELECT * FROM V_REGION_SALES
SQL Summary
SEARCH TUTORIALS:
Search
SQL Summary
The database that will be used during your course of study was also introduced. The database, which you have seen has consisted of a few tables, which are related to one another, and the data that each table contains at this point. You should have acquired some concept of a modern database and overall background knowledge of the fundamentals of SQL. This tutorial also taught the how to access and manipulat database systems. You have learned how to execute queries,insert new records, retrieve data, delete records and update records in a database with SQL.