An Introduction To Database & SQL
What is database? Often abbreviated DB. A collection of information organized in such a way that a computer program can quickly select desired pieces of data. You can think of a database as an electronic filing system. Traditional databases are organized by fields, records, and files. A field is a single piece of information; a record is one complete set of fields; and a file is a collection of records. For example, a telephone book is analogous to a file. It contains a list of records, each of which consists of three fields: name, address, and telephone number.
A computer database is a structured collection of records or data that is stored in a computer system so that a computer program or person using a query language can consult it to answer queries. The records retrieved in answer to queries are information that can be used to make decisions. The computer program used to manage and query a database is known as a database management system (DBMS). The central concept of a database is that of a collection of records, or pieces of information. Typically, for a given database, there is a structural description of the type of facts held in that database: this description is known as a schema. The schema describes the objects that are represented in the database, and the relationships among them. There are a number of different ways of organizing a schema, that is, of modelling the database structure: these are known as database models (or data models). The model in most common use today is the relational model, which in layman's terms represents all
Indra nil Basu
[email protected]
1
An Introduction To Database & SQL
information in the form of multiple related tables each consisting of rows and columns (the true definition uses mathematical terminology). This model represents relationships by the use of values common to more than one table. Other models such as the hierarchical model and the network model use a more explicit representation of relationships. The term database refers to the collection of related records, and the software should be referred to as the database management system or DBMS. When the context is unambiguous, however, many database administrators and programmers use the term database to cover both meanings.
Indra nil Basu
[email protected]
2
An Introduction To Database & SQL
What is DBMS? Stands for "Database Management System." In short, a DBMS is a database program. Technically speaking, it is a software system that uses a standard method of cataloging, retrieving, and running queries on data. The DBMS manages incoming data, organizes it, and provides ways for the data to be modified or extracted by users or other programs. Some DBMS examples include MySQL, PostgreSQL, Microsoft Access, SQL Server, FileMaker, Oracle, RDBMS, dBASE, Clipper, and FoxPro. Since there are so many database management systems available, it is important for there to be a way for them to communicate with each other. For this reason, most database software comes with an Open Database Connectivity (ODBC) driver that allows the database to integrate with other databases. For example, common SQL statements such as SELECT and INSERT are translated from a program's proprietary syntax into a syntax other databases can understand.
Description
A DBMS is a complex set of software programs that controls the organization, storage, management, and retrieval of data in a database. A DBMS includes: 1. A modeling language to define the schema of each database hosted in the DBMS, according to the DBMS data model. o
The four most common types of organizations are the hierarchical, network, relational and object models. Inverted lists and other methods are also used. A given database management system may provide one or more of the four models. The optimal structure depends on the natural organization of the application's data, and on the application's requirements (which include transaction rate (speed), reliability, maintainability, scalability, and cost).
Indra nil Basu
[email protected]
3
An Introduction To Database & SQL
o
The dominant model in use today is the ad hoc one embedded in SQL, despite the objections of purists who believe this model is a corruption of the relational model, since it violates several of its fundamental
principles
for
the
sake
of
practicality
and
performance. Many DBMSs also support the Open Database Connectivity API that supports a standard way for programmers to access the DBMS. 2. Data structures (fields, records, files and objects) optimized to deal with very large amounts of data stored on a permanent data storage device (which implies relatively slow access compared to volatile main memory). 3. A database query language and report writer to allow users to interactively interrogate the database, analyze its data and update it according to the users privileges on data. o
It also controls the security of the database.
o
Data security prevents unauthorized users from viewing or updating the database. Using passwords, users are allowed access to the entire database or subsets of it called subschemas. For example, an employee database can contain all the data about an individual employee, but one group of users may be authorized to view only payroll data, while others are allowed access to only work history and medical data.
o
If the DBMS provides a way to interactively enter and update the database, as well as interrogate it, this capability allows for managing personal databases. However, it may not leave an audit trail of actions or provide the kinds of controls necessary in a multi-user organization. These controls are only available when a set of application programs are customized for each data entry and updating function.
4. A transaction mechanism, that ideally would guarantee the ACID properties, in order to ensure data integrity, despite concurrent user accesses (concurrency control), and faults (fault tolerance). o
It also maintains the integrity of the data in the database.
o
The DBMS can maintain the integrity of the database by not allowing more than one user to update the same record at the same time. The DBMS can help prevent duplicate records via unique index constraints; for example, no two customers with the
Indra nil Basu
[email protected]
4
An Introduction To Database & SQL
same customer numbers (key fields) can be entered into the database. See ACID properties for more information (Redundancy avoidance).
The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data. When a DBMS is used, information systems can be changed much more easily as the organization's information requirements change. New categories of data can be added to the database without disruption to the existing system. Organizations may use one kind of DBMS for daily transaction processing and then move the detail onto another computer that uses another DBMS better suited for random inquiries and analysis. Overall systems design decisions are performed by data administrators and systems analysts. Detailed database design is performed by database administrators. Database servers are specially designed computers that hold the actual databases and run only the DBMS and related software. Database servers are usually multiprocessor computers, with RAID disk arrays used for stable storage. Connected to one or more servers via a high-speed channel, hardware database accelerators are also used in large volume transaction processing environments. DBMS's are found at the heart of most database applications. Sometimes DBMSs are built around a private multitasking kernel with built-in networking support although nowadays these functions are left to the operating system.
Advantages of Using a Database Management System Indra nil Basu
[email protected]
5
An Introduction To Database & SQL
There are three main features of a database management system that make it attractive to use a DBMS in preference to other systems. These features are: • • •
Centralised data management, Data independence Systems integration.
In a database system, the data is managed by the DBMS and all access to the data is through the DBMS providing a key to effective data processing. This contrasts with conventional data processing systems where each application program has direct access to the data it reads or manipulates. In the conventional data processing application programs, the programs usually are based on a considerable knowledge of data structure and format. In such environment any change of data structure or format would require appropriate changes to the application programs. If major changes were to be made to the data, the application programs may need to be rewritten. In a database system, the database management system provides the interface between the application programs and the data. When changes are made to the data representation, the metadata maintained by the DBMS is changed but the DBMS continues to provide data to application programs in the previously used way. The DBMS handles the task of transformation of data wherever necessary. This independence between the programs and the data is called data independence. Data independence is important because every time some change needs to be made to the data structure, the programs that were being used before the change would continue to work. To provide a high degree of data independence, a DBMS must include a sophisticated metadata management system.
Indra nil Basu
[email protected]
6
An Introduction To Database & SQL
In DBMS, all files are integrated into one system thus reducing redundancies and making data management more efficient. In addition, DBMS provides centralised control of the operational data. Some of the advantages of data independence, integration and centralised control are: 1. 2. 3. 4. 5. 6. 7. 8. 9.
Redundancies and inconsistencies can be reduced Better service to the Users Flexibility of the system is improved Cost of developing and maintaining systems is lower Standards can be enforced Security can be improved Integrity can be improved Enterprise requirements can be identified Data model must be developed
Features and Abilities Of DBMS One can characterize a DBMS as an "attribute management system" where attributes are small chunks of information that describe something. For example, "color" is an attribute of a car. The value of the attribute may be a color such as "red", "blue", "silver", etc. Lately databases have been modified to accept large or unstructured (pre-digested or pre-categorized) information as well, such as images and text documents. However, the main focus is still on descriptive attributes.
Indra nil Basu
[email protected]
7
An Introduction To Database & SQL
DBMS roll together frequently-needed services or features of attribute management. This allows one to get powerful functionality "out of the box" rather than program each from scratch or add and integrate them incrementally. Such features include: 1. Query ability
Querying is the process of requesting attribute information from various perspectives and combinations of factors. Example: "How many 2-door cars in Texas are green?" A database query language and report writer to allow users to interactively interrogate the database, analyze its data and update it according to the users privileges on data. It also controls the security of the database. Data security prevents unauthorized users from viewing or updating the database. Using passwords, users are allowed access to the entire database or subsets of it called subschemas. For example, an employee database can contain all the data about an individual employee, but one group of users may be authorized to view only payroll data, while others are allowed access to only work history and medical data. If the DBMS provides a way to interactively enter and update the database, as well as interrogate it, this capability allows for managing personal databases. However, it may not leave an audit trail of actions or provide the kinds of controls necessary in a multi-user organization. These controls are only available when a set of application programs are customized for each data entry and updating function. 2. Backup and replication
Copies of attributes need to be made regularly in case primary disks or other equipment fails. A periodic copy of attributes may also be created for a distant organization that cannot readily access the original. DBMS usually provide utilities to facilitate the process of extracting and disseminating attribute sets.
Indra nil Basu
[email protected]
8
An Introduction To Database & SQL
When data is replicated between database servers, so that the information remains consistent throughout the database system and users cannot tell or even know which server in the DBMS they are using, the system is said to exhibit replication transparency. 3. Rule enforcement
Often one wants to apply rules to attributes so that the attributes are clean and reliable. For example, we may have a rule that says each car can have only one engine associated with it (identified by Engine Number). If somebody tries to associate a second engine with a given car, we want the DBMS to deny such a request and display an error message. However, with changes in the model specification such as, in this example, hybrid gas-electric cars, rules may need to change. Ideally such rules should be able to be added and removed as needed without significant data layout redesign. 4. Security
Often it is desirable to limit who can see or change which attributes or groups of attributes. This may be managed directly by individual, or by the assignment of individuals and privileges to groups, or (in the most elaborate models) through the assignment of individuals and groups to roles which are then granted entitlements. 5. Computation
There are common computations requested on attributes such as counting, summing, averaging, sorting, grouping, cross-referencing, etc. Rather than have each computer application implement these from scratch, they can rely on the DBMS to supply such calculations.
Indra nil Basu
[email protected]
9
An Introduction To Database & SQL
6. Change and access logging
Often one wants to know who accessed what attributes, what was changed, and when it was changed. Logging services allow this by keeping a record of access occurrences and changes 7. Automated optimization
If there are frequently occurring usage patterns or requests, some DBMS can adjust themselves to improve the speed of those interactions. In some cases the DBMS will merely provide tools to monitor performance, allowing a human expert to make the necessary adjustments after reviewing the statistics collected.
Indra nil Basu
[email protected]
10
An Introduction To Database & SQL
RDBMS Short for relational database management system and pronounced as separate letters, a type of database management system (DBMS) that stores data in the form of related tables. Relational databases are powerful because they require few assumptions about how data is related or how it will be extracted from the database. As a result, the same database can be viewed in many different ways. An important feature of relational systems is that a single database can be spread across several tables. This differs from flatfile databases, in which each database is self-contained in a single table. Almost all full-scale database systems are RDBMS's. Small database systems, however, use other designs that provide less flexibility in posing queries.
What is RDBMS? RDBMS stands for Relational Database Management System. RDBMS data is structured in database tables, fields and records. Each RDBMS table consists of database table rows. Each database table row consists of one or more database table fields. RDBMS store the data into collection of tables, which might be related by common fields (database table columns). RDBMS also
Indra nil Basu
[email protected]
11
An Introduction To Database & SQL
provide relational operators to manipulate the data stored into the database tables. Most RDBMS use SQL as database query language. Edgar Codd introduced the relational database model. Many modern DBMS do not conform to the Codd’s definition of a RDBMS, but nonetheless they are still considered to be RDBMS. The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL
What is the Difference between DBMS and RDBMS? A DBMS has to be persistent, that is it should be accessible when the program created the data ceases to exist or even the application that created the data restarted. A DBMS also has to provide some uniform methods independent of a specific application for accessing the information that is stored. RDBMS is a Relational Data Base Management System Relational DBMS. This adds the additional condition that the system supports a tabular structure for the data, with enforced relationships between the tables. This excludes the databases that don't support a tabular structure or don't enforce relationships between tables. Many DBA's think that RDBMS is a Client Server Database system but thats not the case with RDBMS. Yes you can say DBMS does not impose any constraints or security with regard to data manipulation it is user or the programmer responsibility to ensure the ACID PROPERTY of the database whereas the rdbms is more with this regard bcz rdbms difine the integrity constraint for the purpose of holding ACID PROPERTY. Quote:
Indra nil Basu
[email protected]
12
An Introduction To Database & SQL
DBMS are for smaller organizations with small amount of data, where security of the data is not of major concern and RDBMS are designed to take care of large amounts of data and also the security of this data.
What is SQL? Abbreviation of structured query language, and pronounced either seekwell or as separate letters. SQL is a standardized query language for requesting information from a database. The original version called SEQUEL (structured English query language) was designed by an IBM research center in 1974 and 1975. SQL was first introduced as a commercial database system in 1979 by Oracle Corporation.
Structured Query Language (SQL) is a specialized language for updating, deleting, and requesting information from databases. SQL is an ANSI and ISO standard, and is the de facto standard database query language. A variety of established database products support SQL, including products from Oracle and Microsoft SQL Server. It is widely used in both industry and academia, often for enormous, complex databases. Indra nil Basu
[email protected]
13
An Introduction To Database & SQL
In a distributed database system, a program often referred to as the database's "back end" runs constantly on a server, interpreting data files on the server as a standard relational database. Programs on client computers allow users to manipulate that data, using tables, columns, rows, and fields. To do this, client programs send SQL statements to the server. The server then processes these statements and returns replies to the client program. SQL is •
SQL stands for Structured Query Language
•
SQL allows you to access a database
•
SQL is an ANSI standard computer language
•
SQL can execute queries against a database
•
SQL can retrieve data from a database
•
SQL can insert new records in a database
•
SQL can delete records from a database
•
SQL can update records in a database
•
SQL is easy to learn
SQL Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Indra nil Basu
[email protected]
14
An Introduction To Database & SQL
The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).
SQL Queries
With SQL, we can query a database and have a result set returned. A query like this: SELECT LastName FROM Persons
Gives a result set like this: LastName Hansen Svendson Pettersen
Note: Some database systems require a semicolon at the end of the SQL statement. We don't use the semicolon in our tutorials. SQL Data Manipulation Language (DML)
SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update, insert, and delete records. These query and update commands together form Manipulation Language (DML) part of SQL: •
SELECT - extracts data from a database table
•
UPDATE - updates data in a database table
•
DELETE - deletes data from a database table
•
INSERT INTO - inserts new data into a database table
Indra nil Basu
[email protected]
the Data
15
An Introduction To Database & SQL
SQL Data Definition Language (DDL)
The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We can also define indexes (keys), specify links between tables, and impose constraints between database tables. The most important DDL statements in SQL are: •
CREATE TABLE - creates a new database table
•
ALTER TABLE - alters (changes) a database table
•
DROP TABLE - deletes a database table
•
CREATE INDEX - creates an index (search key)
•
DROP INDEX - deletes an index
The SQL SELECT Statement
The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set). Syntax
SELECT column_name(s)
Indra nil Basu
[email protected]
16
An Introduction To Database & SQL
FROM table_name Note: SQL statements are not case sensitive. SELECT is the same as select.
SQL SELECT Example
To select the content of columns named "LastName" and "FirstName", from the database table called "Persons", use a SELECT statement like this: SELECT LastName,FirstName FROM Persons
The database table "Persons": LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
The result LastName
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
Select All Columns
To select all columns from the "Persons" table, use a * symbol instead of column names, like this: Indra nil Basu
[email protected]
17
An Introduction To Database & SQL
SELECT * FROM Persons
Result LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
The Result Set
The result from a SQL query is stored in a result-set. Most database software systems allow navigation of the result set with programming functions, like: Move-To-First-Record, Get-Record-Content, Move-ToNext-Record, etc. Programming functions like these are not a part of this tutorial. To learn about accessing data with function calls, please visit our ADO tutorial.
Semicolon after SQL Statements?
Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server. Some SQL tutorials end each SQL statement with a semicolon. Is this necessary? We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.
Indra nil Basu
[email protected]
18
An Introduction To Database & SQL
The SELECT DISTINCT Statement
The DISTINCT keyword is used to return only distinct (different) values. The SELECT statement returns information from table columns. But what if we only want to select distinct elements? With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement: Syntax
SELECT DISTINCT column_name(s) FROM table_name
Using the DISTINCT keyword
To select ALL values from the column named "Company" we use a SELECT statement like this: SELECT Company FROM Orders
"Orders" table Company
OrderNumber
Sega
3412
W3Schools
2312
Trio
4678
W3Schools
6798
Result
Indra nil Basu
[email protected]
19
An Introduction To Database & SQL
Company Sega W3Schools Trio W3Schools
Note that "W3Schools" is listed twice in the result-set. To select only DIFFERENT values from the column named "Company" we use a SELECT DISTINCT statement like this: SELECT DISTINCT Company FROM Orders
Result: Company Sega W3Schools Trio
Now "W3Schools" is listed only once in the result-set.
Indra nil Basu
[email protected]
20
An Introduction To Database & SQL
The WHERE clause is used to specify a selection criterion.
The WHERE Clause
To conditionally select data from a table, a WHERE clause can be added to the SELECT statement. Syntax
SELECT column FROM table WHERE column operator value With the WHERE clause, the following operators can be used: Operator Description =
Equal
<>
Not equal
>
Greater than
<
Less than
>=
Greater than or equal
<=
Less than or equal
BETWEEN Between an inclusive range LIKE
Search for a pattern
IN
If you know the exact value you want to return for at least one of the columns
Indra nil Basu
[email protected]
21
An Introduction To Database & SQL
Note: In some versions of SQL the <> operator may be written as !=
Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a WHERE clause to the SELECT statement: SELECT * FROM Persons WHERE City='Sandnes' "Persons" table LastName
FirstName
Address
City
Year
Hansen
Ola
Timoteivn 10
Sandnes
1951
Svendson
Tove
Borgvn 23
Sandnes
1978
Svendson
Stale
Kaivn 18
Sandnes
1980
Pettersen
Kari
Storgt 20
Stavanger
1960
Result LastName
FirstName
Address
City
Year
Hansen
Ola
Timoteivn 10
Sandnes
1951
Svendson
Tove
Borgvn 23
Sandnes
1978
Svendson
Stale
Kaivn 18
Sandnes
1980
Using Quotes
Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes. Indra nil Basu
[email protected]
22
An Introduction To Database & SQL
For text values: This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove
For numeric values: This is correct: SELECT * FROM Persons WHERE Year>1965 This is wrong: SELECT * FROM Persons WHERE Year>'1965'
The LIKE Condition
The LIKE condition is used to specify a search for a pattern in a column. Syntax
SELECT column FROM table WHERE column LIKE pattern
Indra nil Basu
[email protected]
23
An Introduction To Database & SQL
A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
Using LIKE
The following SQL statement will return persons with first names that start with an 'O': SELECT * FROM Persons WHERE FirstName LIKE 'O%' The following SQL statement will return persons with first names that end with an 'a': SELECT * FROM Persons WHERE FirstName LIKE '%a'
The following SQL statement will return persons with first names that contain the pattern 'la': SELECT * FROM Persons WHERE FirstName LIKE '%la%'
Indra nil Basu
[email protected]
24
An Introduction To Database & SQL
The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into a table. Syntax
INSERT INTO table_name
Indra nil Basu
[email protected]
25
An Introduction To Database & SQL
VALUES (value1, value2,....) You can also specify the columns for which you want to insert data: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
Insert a New Row
This "Persons" table: LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
And this SQL statement: INSERT INTO Persons VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes') Will give this result: LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
Hetland
Camilla
Hagabakka 24
Sandnes
Insert Data in Specified Columns
This "Persons" table: Indra nil Basu
[email protected]
26
An Introduction To Database & SQL
LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
Hetland
Camilla
Hagabakka 24
Sandnes
And This SQL statement: INSERT INTO Persons (LastName, Address) VALUES ('Rasmussen', 'Storgt 67') Will give this result: LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
Hetland
Camilla
Hagabakka 24
Sandnes
Rasmussen
Indra nil Basu
[email protected]
Storgt 67
27
An Introduction To Database & SQL
The Update Statement
The UPDATE statement is used to modify the data in a table. Syntax
UPDATE table_name SET column_name = new_value WHERE column_name = some_value
Person: LastName
FirstName
Address
City
Nilsen
Fred
Kirkegt 56
Stavanger
Rasmussen
Storgt 67
Update one Column in a Row
We want to add a first name to the person with a last name of "Rasmussen": UPDATE Person SET FirstName = 'Nina' WHERE LastName = 'Rasmussen' Result: LastName
FirstName
Address
City
Nilsen
Fred
Kirkegt 56
Stavanger
Rasmussen
Nina
Storgt 67
Indra nil Basu
[email protected]
28
An Introduction To Database & SQL
Update several Columns in a Row
We want to change the address and add the name of the city: UPDATE Person SET Address = 'Stien 12', City = 'Stavanger' WHERE LastName = 'Rasmussen' Result: LastName
FirstName
Address
City
Nilsen
Fred
Kirkegt 56
Stavanger
Rasmussen
Nina
Stien 12
Stavanger
Indra nil Basu
[email protected]
29
An Introduction To Database & SQL
The DELETE Statement
The DELETE statement is used to delete rows in a table. Syntax
DELETE FROM table_name WHERE column_name = some_value
Person: LastName
FirstName
Address
City
Nilsen
Fred
Kirkegt 56
Stavanger
Rasmussen
Nina
Stien 12
Stavanger
Delete a Row
"Nina Rasmussen" is going to be deleted: DELETE FROM Person WHERE LastName = 'Rasmussen'
Result
Indra nil Basu
[email protected]
30
An Introduction To Database & SQL
LastName
FirstName
Address
City
Nilsen
Fred
Kirkegt 56
Stavanger
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name or DELETE * FROM table_name Practice : To practice the SQL try the following link: http://www.w3schools.com/sql/sql_tryit.asp
Indra nil Basu
[email protected]
31
An Introduction To Database & SQL
SQL ORDER BY The ORDER BY keyword is used to sort the result. Sort the Rows
The ORDER BY clause is used to sort the rows. Orders: Company
OrderNumber
Sega
3412
ABC Shop
5678
W3Schools
6798
W3Schools
2312
Indra nil Basu
[email protected]
32
An Introduction To Database & SQL
Example
To display the company names in alphabetical order: SELECT Company, OrderNumber FROM Orders ORDER BY Company Result: Company
OrderNumber
ABC Shop
5678
Sega
3412
W3Schools
6798
W3Schools
2312
Example
To display the company names in alphabetical order AND the OrderNumber in numerical order: SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber Result: Company
OrderNumber
ABC Shop
5678
Sega
3412
W3Schools
2312
Indra nil Basu
[email protected]
33
An Introduction To Database & SQL
W3Schools
6798
Example
To display the company names in reverse alphabetical order: SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC Result: Company
OrderNumber
W3Schools
6798
W3Schools
2312
Sega
3412
ABC Shop
5678
Example
To display the company names in reverse alphabetical order AND the OrderNumber in numerical order: SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC Result: Company
OrderNumber
W3Schools
2312
W3Schools
6798
Sega
3412
ABC Shop
5678
Notice that there are two equal company names (W3Schools) in the result above. The only time you will see the second column in ASC Indra nil Basu
[email protected]
34
An Introduction To Database & SQL
order would be when there are duplicated values in the first sort column, or a handful of nulls.
SQL AND & OR AND & OR
AND and OR join two or more conditions in a WHERE clause. The AND operator displays a row if ALL conditions listed are true. The OR operator displays a row if ANY of the conditions listed are true. Original Table (used in the examples) LastName FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Svendson
Stephen
Kaivn 18
Sandnes
Indra nil Basu
[email protected]
35
An Introduction To Database & SQL
Example
Use AND to display each person with the first name equal to "Tove", and the last name equal to "Svendson": SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson' Result: LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Example
Use OR to display each person with the first name equal to "Tove", or the last name equal to "Svendson": SELECT * FROM Persons WHERE firstname='Tove' OR lastname='Svendson' Result: LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Svendson
Stephen
Kaivn 18
Sandnes
Example
You can also combine AND and OR (use parentheses to form complex expressions): Indra nil Basu
[email protected]
36
An Introduction To Database & SQL
SELECT * FROM Persons WHERE (FirstName='Tove' OR FirstName='Stephen') AND LastName='Svendson' Result: LastName
FirstName
Address
City
Svendson
Tove
Borgvn 23
Sandnes
Svendson
Stephen
Kaivn 18
Sandnes
SQL IN IN
The IN operator may be used if you know the exact value you want to return for at least one of the columns.
Indra nil Basu
[email protected]
37
An Introduction To Database & SQL
SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)
Original Table (used in the examples) LastName FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Nordmann
Anna
Neset 18
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
Example 1
To display the persons with LastName equal to "Hansen" or "Pettersen", use the following SQL: SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') Result: LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
SQL BETWEEN
Indra nil Basu
[email protected]
38
An Introduction To Database & SQL
BETWEEN ... AND
The BETWEEN ... AND operator selects a range of data between two values. These values can be numbers, text, or dates. SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2
Original Table (used in the examples) LastName FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Nordmann
Anna
Neset 18
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
Example 1
To display the persons alphabetically between (and including) "Hansen" and exclusive "Pettersen", use the following SQL: SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen' Result: LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Nordmann
Anna
Neset 18
Sandnes
Indra nil Basu
[email protected]
39
An Introduction To Database & SQL
IMPORTANT! The BETWEEN...AND operator is treated differently in different databases. With some databases a person with the LastName of "Hansen" or "Pettersen" will not be listed (BETWEEN..AND only selects fields that are between and excluding the test values). With some databases a person with the last name of "Hansen" or "Pettersen" will be listed (BETWEEN..AND selects fields that are between and including the test values). With other databases a person with the last name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND selects fields between the test values, including the first test value and excluding the last test value). Therefore: Check how your database treats the BETWEEN....AND operator!
Example 2
To display the persons outside the range used in the previous example, use the NOT operator: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen' Result: LastName
FirstName
Address
City
Pettersen
Kari
Storgt 20
Stavanger
Svendson
Tove
Borgvn 23
Sandnes
Indra nil Basu
[email protected]
40
An Introduction To Database & SQL
SQL Alias With SQL, aliases can be used for column names and table names.
Column Name Alias
The syntax is: SELECT column AS column_alias FROM table
Table Name Alias
The syntax is: SELECT column FROM table AS table_alias
Example: Using a Column Alias
This table (Persons): LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
And this SQL: Indra nil Basu
[email protected]
41
An Introduction To Database & SQL
SELECT LastName AS Family, FirstName AS Name FROM Persons
Returns this result: Family
Name
Hansen
Ola
Svendson
Tove
Pettersen
Kari
Example: Using a Table Alias
This table (Persons): LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
And this SQL: SELECT LastName, FirstName FROM Persons AS Employees Returns this result: Table Employees:
Indra nil Basu
[email protected]
42
An Introduction To Database & SQL
LastName
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
SQL JOIN Joins and Keys
Sometimes we have to select data from two or more tables to make our result complete. We have to perform a join. Tables in a database can be related to each other with keys. A primary key is a column with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. In the "Employees" table below, the "Employee_ID" column is the primary key, meaning that no two rows can have the same Employee_ID. The Employee_ID distinguishes two persons even if they have the same name. When you look at the example tables below, notice that: •
The "Employee_ID" column is the primary key of the "Employees" table
•
The "Prod_ID" column is the primary key of the "Orders" table
•
The "Employee_ID" column in the "Orders" table is used to refer to the persons in the "Employees" table without using their names
Indra nil Basu
[email protected]
43
An Introduction To Database & SQL
Employees: Employee_ID
Name
01
Hansen, Ola
02
Svendson, Tove
03
Svendson, Stephen
04
Pettersen, Kari
Orders: Prod_ID
Product
Employee_ID
234
Printer
01
657
Table
03
865
Chair
03
Referring to Two Tables
We can select data from two tables by referring to two tables, like this: Example
Who has ordered a product, and what did they order? SELECT Employees.Name, Orders.Product FROM Employees, Orders WHERE Employees.Employee_ID=Orders.Employee_ID
Indra nil Basu
[email protected]
44
An Introduction To Database & SQL
Result Name
Product
Hansen, Ola
Printer
Svendson, Stephen
Table
Svendson, Stephen
Chair
Example
Who ordered a printer? SELECT Employees.Name FROM Employees, Orders WHERE Employees.Employee_ID=Orders.Employee_ID AND Orders.Product='Printer'
Result Name Hansen, Ola
Using Joins
OR we can select data from two tables with the JOIN keyword, like this: Example INNER JOIN
Syntax SELECT field1, field2, field3
Indra nil Basu
[email protected]
45
An Introduction To Database & SQL
FROM first_table INNER JOIN second_table ON first_table.keyfield = second_table.foreign_keyfield Who has ordered a product, and what did they order? SELECT Employees.Name, Orders.Product FROM Employees INNER JOIN Orders ON Employees.Employee_ID=Orders.Employee_ID The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that do not have matches in Orders, those rows will not be listed. Result Name
Product
Hansen, Ola
Printer
Svendson, Stephen
Table
Svendson, Stephen
Chair
Example LEFT JOIN
Syntax SELECT field1, field2, field3 FROM first_table LEFT JOIN second_table ON first_table.keyfield = second_table.foreign_keyfield List all employees, and their orders - if any.
Indra nil Basu
[email protected]
46
An Introduction To Database & SQL
SELECT Employees.Name, Orders.Product FROM Employees LEFT JOIN Orders ON Employees.Employee_ID=Orders.Employee_ID The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed. Result Name
Product
Hansen, Ola
Printer
Svendson, Tove Svendson, Stephen
Table
Svendson, Stephen
Chair
Pettersen, Kari Example RIGHT JOIN
Syntax SELECT field1, field2, field3 FROM first_table RIGHT JOIN second_table ON first_table.keyfield = second_table.foreign_keyfield List all orders, and who has ordered - if any. SELECT Employees.Name, Orders.Product FROM Employees RIGHT JOIN Orders
Indra nil Basu
[email protected]
47
An Introduction To Database & SQL
ON Employees.Employee_ID=Orders.Employee_ID The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches in the first table (Employees). If there had been any rows in Orders that did not have matches in Employees, those rows also would have been listed. Result Name
Product
Hansen, Ola
Printer
Svendson, Stephen
Table
Svendson, Stephen
Chair
Example
Who ordered a printer? SELECT Employees.Name FROM Employees INNER JOIN Orders ON Employees.Employee_ID=Orders.Employee_ID WHERE Orders.Product = 'Printer' Result Name Hansen, Ola
Indra nil Basu
[email protected]
48
An Introduction To Database & SQL
SQL UNION and UNION ALL UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. Note: With UNION, only distinct values are selected. SQL Statement 1 UNION SQL Statement 2
Employees_Norway: E_ID
E_Name
01
Hansen, Ola
02
Svendson, Tove
03
Svendson, Stephen
04
Pettersen, Kari
Employees_USA: E_ID
E_Name
01
Turner, Sally
02
Kent, Clark
03
Svendson, Stephen
04
Scott, Stephen
Indra nil Basu
[email protected]
49
An Introduction To Database & SQL
Using the UNION Command Example
List all different employee names in Norway and USA: SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA Result E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them is listed. The UNION command only selects distinct values.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. SQL Statement 1 UNION ALL
Indra nil Basu
[email protected]
50
An Introduction To Database & SQL
SQL Statement 2
Using the UNION ALL Command Example
List all employees in Norway and USA: SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA Result E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Svendson, Stephen Scott, Stephen
Indra nil Basu
[email protected]
51
An Introduction To Database & SQL
SQL Create Database, Table, and Index Create a Database
To create a database: CREATE DATABASE database_name
Create a Table
To create a table in a database: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, ....... ) Example
This example demonstrates how you can create a table named "Person", with four columns. The column names will be "LastName", "FirstName", "Address", and "Age": Indra nil Basu
[email protected]
52
An Introduction To Database & SQL
CREATE TABLE Person ( LastName varchar, FirstName varchar, Address varchar, Age int )
This example demonstrates how you can specify a maximum length for some columns: CREATE TABLE Person ( LastName varchar(30), FirstName varchar, Address varchar, Age int(3) ) The data type specifies what type of data the column can hold. The table below contains the most common data types in SQL: Data Type
Description
integer(size) int(size) smallint(size) tinyint(size)
Hold integers only. The maximum number of digits are specified in parenthesis.
decimal(size,d) numeric(size,d)
Hold numbers with fractions. The maximum number of digits are specified in "size". The maximum number of
Indra nil Basu
[email protected]
53
An Introduction To Database & SQL
digits to the right of the decimal is specified in "d". char(size)
Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis.
varchar(size)
Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis.
date(yyyymmdd)
Holds a date
Create Index
Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Note: Updating a table containing indexes takes more time than updating a table without, this is because the indexes also need an update. So, it is a good idea to create indexes only on columns that are often used for a search.
A Unique Index Creates a unique index on a table. A unique index means that two rows cannot have the same index value. CREATE UNIQUE INDEX index_name ON table_name (column_name) The "column_name" specifies the column you want indexed. A Simple Index Creates a simple index on a table. When the UNIQUE keyword is omitted, duplicate values are allowed.
Indra nil Basu
[email protected]
54
An Introduction To Database & SQL
CREATE INDEX index_name ON table_name (column_name) The "column_name" specifies the column you want indexed. Example
This example creates a simple index, named "PersonIndex", on the LastName field of the Person table: CREATE INDEX PersonIndex ON Person (LastName) If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name: CREATE INDEX PersonIndex ON Person (LastName DESC) If you want to index more than one column you can list the column names within the parentheses, separated by commas: CREATE INDEX PersonIndex ON Person (LastName, FirstName)
Indra nil Basu
[email protected]
55
An Introduction To Database & SQL
SQL Drop Database
Index,
Table
and
Drop Index
You can delete an existing index in a table with the DROP INDEX statement.
Indra nil Basu
[email protected]
56
An Introduction To Database & SQL
Syntax for Microsoft SQLJet (and Microsoft Access): DROP INDEX index_name ON table_name
Syntax for MS SQL Server: DROP INDEX table_name.index_name
Syntax for IBM DB2 and Oracle: DROP INDEX index_name
Syntax for MySQL: ALTER TABLE table_name DROP INDEX index_name
Delete a Table or Database
To delete a table (the table structure, attributes, and indexes will also be deleted): DROP TABLE table_name
To delete a database: DROP DATABASE database_name
Indra nil Basu
[email protected]
57
An Introduction To Database & SQL
Truncate a Table
What if we only want to get rid of the data inside a table, and not the table itself? Use the TRUNCATE TABLE command (deletes only the data inside the table): TRUNCATE TABLE table_name
Indra nil Basu
[email protected]
58
An Introduction To Database & SQL
SQL ALTER TABLE ALTER TABLE
The ALTER TABLE statement is used to add or drop columns in an existing table. ALTER TABLE table_name ADD column_name datatype ALTER TABLE table_name DROP COLUMN column_name Note: Some database systems don't allow the dropping of a column in a database table (DROP COLUMN column_name). Person: LastName
FirstName
Address
Pettersen
Kari
Storgt 20
Example―To add a column named "City" in the "Person" table:
ALTER TABLE Person ADD City varchar(30)
Result: LastName
FirstName
Address
Pettersen
Kari
Storgt 20
Indra nil Basu
[email protected]
City
59
An Introduction To Database & SQL
Example
To drop the "Address" column in the "Person" table: ALTER TABLE Person DROP COLUMN Address
Result: LastName
FirstName
Pettersen
Kari
City
SQL Functions SQL has a lot of built-in functions for counting and calculations. Function Syntax
The syntax for built-in SQL functions is: SELECT function(column) FROM table
Types of Functions
There are several basic types and categories of functions in SQL. The basic types of functions are: •
Aggregate Functions
•
Scalar functions
Aggregate functions
Aggregate functions operate against a collection of values, but return a single value. Indra nil Basu
[email protected]
60
An Introduction To Database & SQL
Note: If used among many other expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY clause!! "Persons" table (used in most examples) Name
Age
Hansen, Ola
34
Svendson, Tove
45
Pettersen, Kari
19
Aggregate functions in MS Access Function Description AVG(column)
Returns the average value of a column
COUNT(column)
Returns the number of rows (without a NULL value) of a column
COUNT(*)
Returns the number of selected rows
FIRST(column)
Returns the value of the first record in a specified field
LAST(column)
Returns the value of the last record in a specified field
MAX(column)
Returns the highest value of a column
MIN(column)
Returns the lowest value of a column
STDEV(column) STDEVP(column) SUM(column)
Returns the total sum of a column
VAR(column) VARP(column) Aggregate functions in SQL Server Function Description AVG(column)
Returns the average value of a column
BINARY_CHECKSUM CHECKSUM CHECKSUM_AGG COUNT(column)
Returns the number of rows (without a NULL value) of a column
COUNT(*)
Returns the number of selected rows
COUNT(DISTINCT column)
Returns the number of distinct results
FIRST(column)
Returns the value of the first record in a specified field (not supported in SQLServer2K)
LAST(column)
Returns the value of the last record in a specified field (not supported in SQLServer2K)
Indra nil Basu
[email protected]
61
An Introduction To Database & SQL
MAX(column)
Returns the highest value of a column
MIN(column)
Returns the lowest value of a column
STDEV(column) STDEVP(column) SUM(column)
Returns the total sum of a column
VAR(column) VARP(column)
Scalar functions
Scalar functions operate against a single value, and return a single value based on the input value. Useful Scalar Functions in MS Access Function Description UCASE(c)
Converts a field to upper case
LCASE(c)
Converts a field to lower case
MID(c,start[,end])
Extract characters from a text field
LEN(c)
Returns the length of a text field
INSTR(c,char)
Returns the numeric position of a named character within a text field
LEFT(c,number_of_char)
Return the left part of a text field requested
RIGHT(c,number_of_char)
Return the right part of a text field requested
ROUND(c,decimals)
Rounds a numeric field to the number of decimals specified
MOD(x,y)
Returns the remainder of a division operation
NOW()
Returns the current system date
FORMAT(c,format)
Changes the way a field is displayed
DATEDIFF(d,date1,date2)
Used to perform date calculations
Indra nil Basu
[email protected]
62
An Introduction To Database & SQL
SQL GROUP BY and HAVING Aggregate functions (like SUM) often need an added GROUP BY functionality. GROUP BY...
GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called, and without the GROUP BY function it was impossible to find the sum for each individual group of column values. The syntax for the GROUP BY function is: SELECT column,SUM(column) FROM table GROUP BY column
GROUP BY Example
This "Sales" Table: Company
Amount
W3Schools
5500
IBM
4500
W3Schools
7100
And This SQL: Indra nil Basu
[email protected]
63
An Introduction To Database & SQL
SELECT Company, SUM(Amount) FROM Sales
Returns this result: Company
SUM(Amount)
W3Schools
17100
IBM
17100
W3Schools
17100
The above code is invalid because the column returned is not part of an aggregate. A GROUP BY clause will solve this problem: SELECT Company,SUM(Amount) FROM Sales GROUP BY Company Returns this result: Company
SUM(Amount)
W3Schools
12600
IBM
4500
HAVING...
HAVING... was added to SQL because the WHERE keyword could not be used against aggregate functions (like SUM), and without HAVING... it would be impossible to test for result conditions. The syntax for the HAVING function is: SELECT column,SUM(column) FROM table
Indra nil Basu
[email protected]
64
An Introduction To Database & SQL
GROUP BY column HAVING SUM(column) condition value This "Sales" Table: Company
Amount
W3Schools
5500
IBM
4500
W3Schools
7100
This SQL: SELECT Company,SUM(Amount) FROM Sales GROUP BY Company HAVING SUM(Amount)>10000 Returns this result Company
SUM(Amount)
W3Schools
12600
Indra nil Basu
[email protected]
65
An Introduction To Database & SQL
SQL SELECT INTO Statement The SELECT INTO Statement
The SELECT INTO statement is most often used to create backup copies of tables or for archiving records. Syntax
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source
Indra nil Basu
[email protected]
66
An Introduction To Database & SQL
Make a Backup Copy
The following example makes a backup copy of the "Persons" table: SELECT * INTO Persons_backup FROM Persons The IN clause can be used to copy tables into another database: SELECT Persons.* INTO Persons IN 'Backup.mdb' FROM Persons If you only want to copy a few fields, you can do so by listing them after the SELECT statement: SELECT LastName,FirstName INTO Persons_backup FROM Persons
You can also add a WHERE clause. The following example creates a "Persons_backup" table with two columns (FirstName and LastName) by extracting the persons who lives in "Sandnes" from the "Persons" table: SELECT LastName,Firstname INTO Persons_backup
Indra nil Basu
[email protected]
67
An Introduction To Database & SQL
FROM Persons WHERE City='Sandnes' Selecting data from more than one table is also possible. The following example creates a new table "Empl_Ord_backup" that contains data from the two tables Employees and Orders: SELECT Employees.Name,Orders.Product INTO Empl_Ord_backup FROM Employees INNER JOIN Orders ON Employees.Employee_ID=Orders.Employee_ID
Indra nil Basu
[email protected]
68
An Introduction To Database & SQL
SQL CREATE VIEW Statement A view is a virtual table based on the result-set of a SELECT statement.
What is a View?
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from a single table. Note: The database design and structure will NOT be affected by the functions, where, or join statements in a view. Syntax
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Note: The database does not store the view data! The database engine recreates the data, using the view's SELECT statement, every time a user queries a view.
Indra nil Basu
[email protected]
69
An Introduction To Database & SQL
Using Views
A view could be used from inside a query, a stored procedure, or from inside another view. By adding functions, joins, etc., to a view, it allows you to present exactly the data you want to the user. The sample database Northwind has some views installed by default. The view "Current Product List" lists all active products (products that are not discontinued) from the Products table. The view is created with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No We can query the view above as follows: SELECT * FROM [Current Product List]
Another view from the Northwind sample database selects every product in the Products table that has a unit price that is higher than the average unit price: CREATE VIEW [Products Above Average Price] AS SELECT ProductName,UnitPrice FROM Products WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products) We can query the view above as follows: SELECT * FROM [Products Above Average Price]
Indra nil Basu
[email protected]
70
An Introduction To Database & SQL
Another example view from the Northwind database calculates the total sale for each category in 1997. Note that this view selects its data from another view called "Product Sales for 1997": CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for 1997] GROUP BY CategoryName
We can query the view above as follows: SELECT * FROM [Category Sales For 1997]
We can also add a condition to the query. Now we want to see the total sale only for the category "Beverages": SELECT * FROM [Category Sales For 1997] WHERE CategoryName='Beverages'
Indra nil Basu
[email protected]
71
An Introduction To Database & SQL
SQL Servers - RDBMS Modern SQL Servers are built on RDBMS.
DBMS - Database Management System
A Database Management System (DBMS) is a computer program that can access data in a database. The DBMS program enables you to extract, modify, or store information in a database.
Indra nil Basu
[email protected]
72
An Introduction To Database & SQL
Different DBMS programs provides different functions for querying data, reporting data, and modifying data.
RDBMS - Relational Database Management System
A Relational Database Management System (RDBMS) is a Database Management System (DBMS) where the database is organized and accessed according to the relationships between data. RDBMS was invented by IBM in the early 1970's. RDBMS is the basis for SQL, and for all modern database systems like Oracle, SQL Server, IBM DB2, Sybase, MySQL, and Microsoft Access.
SQL Quick Reference SQL Syntax Statement AND / OR
Syntax SELECT FROM WHERE AND|OR condition
ALTER TABLE (add column) ALTER TABLE ADD column_name datatype
Indra nil Basu
[email protected]
column_name(s) table_name condition table_name
73
An Introduction To Database & SQL
ALTER TABLE (drop column) ALTER TABLE DROP COLUMN column_name
table_name
AS (alias for column)
SELECT column_name FROM table_name
AS
AS (alias for table)
SELECT FROM table_name AS table_alias
BETWEEN
SELECT FROM WHERE BETWEEN value1 AND value2
CREATE DATABASE
CREATE DATABASE database_name
CREATE INDEX
CREATE INDEX ON table_name (column_name)
index_name
CREATE TABLE
CREATE ( column_name1 column_name2 ....... )
table_name
column_alias column_name column_name(s) table_name column_name
TABLE
data_type, data_type,
CREATE UNIQUE INDEX
CREATE UNIQUE INDEX ON table_name (column_name)
index_name
CREATE VIEW
CREATE VIEW SELECT FROM WHERE condition
DELETE FROM
DELETE FROM table_name (Note: Deletes the entire table!!)
view_name AS column_name(s) table_name
or DELETE FROM table_name WHERE condition DROP DATABASE
DROP DATABASE database_name
DROP INDEX
DROP INDEX table_name.index_name
DROP TABLE
DROP TABLE table_name
GROUP BY
SELECT column_name1,SUM(column_name2) FROM table_name GROUP BY column_name1
HAVING
SELECT column_name1,SUM(column_name2) FROM table_name GROUP BY column_name1 HAVING SUM(column_name2) condition value
IN
SELECT FROM
Indra nil Basu
[email protected]
column_name(s) table_name
74
An Introduction To Database & SQL
WHERE IN (value1,value2,..) INSERT INTO
column_name
INSERT INTO VALUES (value1, value2,....)
table_name
or INSERT INTO table_name (column_name1, column_name2,...) VALUES (value1, value2,....) LIKE
SELECT FROM WHERE LIKE pattern
ORDER BY
SELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC]
SELECT
SELECT FROM table_name
column_name(s)
SELECT *
SELECT FROM table_name
*
SELECT DISTINCT
SELECT DISTINCT FROM table_name
column_name(s)
INTO SELECT backup INTO FROM original_table_name
* new_table_name
SELECT (used to create copies of tables)
column_name(s) table_name column_name
or SELECT column_name(s) INTO new_table_name FROM original_table_name TRUNCATE TABLE TRUNCATE TABLE table_name (deletes only the data inside the table) UPDATE
UPDATE table_name SET column_name=new_value [, column_name=new_value] WHERE column_name=some_value
WHERE
SELECT FROM WHERE condition
Indra nil Basu
[email protected]
column_name(s) table_name
75
An Introduction To Database & SQL
SQL Summary This tutorial has taught you the standard computer language for accessing and manipulating database systems. You have learned how to execute queries, retrieve data, insert new records, delete records and update records in a database with SQL. SQL is a standard language that works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, MySQL, Sybase, and other database systems.
Indra nil Basu
[email protected]
76