Sie sind auf Seite 1von 48

What is SQL?

SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?


SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language. However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner. Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!

Using SQL in Your Web Site


To build a web site that shows some data from a database, you will need the following:

An RDBMS database program (i.e. MS Access, SQL Server, MySQL)

A server-side scripting language, like PHP or ASP SQL HTML / CSS

RDBMS
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.

SQL DML and DDL


SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL). The query and update commands form the DML part of SQL:

SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are:

CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a 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 database.

The result is stored in a result table, called the result-set.


SQL SELECT Syntax SELECT column_name(s) FROM table_name

and
SELECT * FROM table_name; Eg SELECT * FROM employee

The SQL SELECT DISTINCT Statement


In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name(s) FROM table_name Eg SELECT DISTINCT(dept_no) FROM employee;

The WHERE clause is used to filter records.

The WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax SELECT column_name(s) FROM table_name WHERE column_name operator value SELECT dept_no FROM employee WHERE emp_id=12;

This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove This is correct: SELECT * FROM Persons WHERE Year=1965 This is wrong: SELECT * FROM Persons WHERE Year='1965'

Operators Allowed in the WHERE Clause


With the WHERE clause, the following operators can be used: Operator = <> > < >= <= BETWEEN LIKE IN Description Equal Not equal Greater than Less than Greater than or equal Less than or equal Between an inclusive range Search for a pattern If you know the exact value you want to return for at least one of the columns

The AND & OR operators are used to filter records based on more than one condition.

The AND & OR Operators


The AND operator displays a record if both the first condition and the second condition is true. The OR operator displays a record if either the first condition or the second condition is true.

SELECT * FROM employee WHERE FirstName='Tove' AND LastName='Svendson' SELECT * FROM employee WHERE FirstName='Tove' OR FirstName='Ola'

Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions). Now we want to select only the persons with the last name equal to "Svendson" AND the first name equal to "Tove" OR to "Ola": We use the following SELECT statement: SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR FirstName='Ola') The ORDER BY keyword is used to sort the result-set.

The ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

SELECT * FROM employee ORDER BY LastName

ORDER BY DESC Example


Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.

We use the following SELECT statement: SELECT * FROM employee ORDER BY LastName DESC

The INSERT INTO statement is used to insert new records in a table.

The INSERT INTO Statement


The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) INSERT INTO employee VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

Insert Data Only in Specified Columns


It is also possible to only add data in specific columns. The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns: INSERT INTO employee (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')

The UPDATE statement is used to update records in a table.

The UPDATE Statement


The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
UPDATE employee SET Address='chembur', City='mumbai' WHERE LastName='Ray' AND FirstName='Abhishak';

SQL UPDATE Warning


Be careful when updating records. If we had omitted the WHERE clause in the example above, like this: UPDATE employee SET Address='chembur', City='mumbai' All the records of Address,City will be updated with chembur,mumbai The DELETE statement is used to delete records in a table.

The DELETE Statement


The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax DELETE FROM table_name

WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! DELETE FROM employee WHERE LastName='Tjessem' AND FirstName='Jakob'

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 Note: Be very careful when deleting records. You cannot undo this statement! The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

The LIKE Operator


The LIKE operator is used to search for a specified pattern in a column.
SQL LIKE Syntax SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern

SELECT * FROM Persons WHERE City LIKE 's%' SELECT * FROM Persons WHERE City LIKE '%s'

SELECT * FROM Persons WHERE City LIKE '%tav%' NOT LIKE SELECT * FROM Persons WHERE City NOT LIKE '%tav%'

Using the _ Wildcard


Now we want to select the persons with a first name that starts with any character, followed by "la" from the "Persons" table. We use the following SELECT statement: SELECT * FROM Persons WHERE FirstName LIKE '_la' SELECT * FROM Persons WHERE LastName LIKE 'S_end_on'

The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...)

SELECT * FROM employee WHERE LastName IN ('Hansen','Pettersen') The BETWEEN operator is used in a WHERE clause to select a range of data between two values.

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.

SQL BETWEEN Syntax SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2

SELECT * FROM employee WHERE LastName BETWEEN 'Hansen' AND 'Pettersen' NOT BETWEEN: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'

SQL Alias
You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names. An alias name could be anything, but usually it is short.
SQL Alias Syntax for Tables SELECT column_name(s) FROM table_name AS alias_name

SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.

Different SQL JOINs


Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.

JOIN: Return rows when there is at least one match in both tables LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table, even if there are no matches in the

left table FULL JOIN: Return rows when there is a match in one of the tables

SQL INNER JOIN Keyword


The INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: INNER JOIN is the same as JOIN. SELECT s.LastName, s.FirstName FROM student INNER JOIN Orders ON s.S_Id=college.P_Id ORDER BY s.LastName

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).
SQL LEFT JOIN Syntax SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: In some databases LEFT JOIN is called LEFT OUTER JOIN. SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all the rows from the right table (table_name2), even if there

are no matches in the left table (table_name1).


SQL RIGHT JOIN Syntax SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN. SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The SQL UNION operator combines two or more SELECT statements.

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
SQL UNION Syntax SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
SQL UNION ALL Syntax SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2

PS: The column names in the result-set of a UNION are always equal to the column names in

the first SELECT statement in the UNION. SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA

SQL UNION ALL Example


Now we want to list all employees in Norway and USA: SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA

The CREATE DATABASE Statement


The CREATE DATABASE statement is used to create a database.
SQL CREATE DATABASE Syntax CREATE DATABASE database_name

CREATE DATABASE Example


Now we want to create a database called "my_db". We use the following CREATE DATABASE statement:
CREATE DATABASE university

Database tables can be added with the CREATE TABLE statement.

The CREATE TABLE Statement


The CREATE TABLE statement is used to create a table in a database.
SQL CREATE TABLE Syntax CREATE TABLE table_name ( column_name1 data_type,

column_name2 data_type, column_name3 data_type, .... )

The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.

CREATE TABLE Example


Now we want to create a table called "Persons" that contains five columns: P_Id, LastName, FirstName, Address, and City. We use the following CREATE TABLE statement:
CREATE TABLE student ( S_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )

The S_Id column is of type int and will hold a number. The LastName, FirstName, Address, and City columns are of type varchar with a maximum length of 255 characters.

SQL Constraints
Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement). We will focus on the following constraints:

NOT NULL UNIQUE PRIMARY KEY

FOREIGN KEY CHECK DEFAULT

By default, a table column can hold NULL values.

SQL NOT NULL Constraint


The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values: CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

SQL UNIQUE Constraint


The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:

MySQL: CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (S_Id) )

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "S_Id" column when the table is already created, use the following SQL: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE student ADD UNIQUE (S_Id) MySQL / SQL Server / Oracle / MS Access: ALTER TABLE student ADD CONSTRAINT uc_student UNIQUE (S_Id,LastName)

To DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL: MySQL: ALTER TABLE student DROP INDEX uc_student

SQL PRIMARY KEY Constraint


Previous Next Chapter

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "S_Id" column when the "student" table is created: MySQL:
CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (S_Id) )

MySQL / SQL Server / Oracle / MS Access: CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_student PRIMARY KEY (S_Id,LastName) )

SQL PRIMARY KEY Constraint on ALTER TABLE


To create a PRIMARY KEY constraint on the "S_Id" column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE student ADD PRIMARY KEY (S_Id) To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE student ADD CONSTRAINT pk_student PRIMARY KEY (S_Id,LastName) Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).

To DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL: MySQL: ALTER TABLE student DROP PRIMARY KEY

SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an example. Look at the following two tables: The "student" table: S_Id 1 2 3 LastName Ram Svendson Pettersen FirstName dev Tove Kari Address mumbai 10 mumbai 23 mumbai 20 City mumbai mumbai mumbai

The "Exam_enrollment" table:

Serial_no 1 2 3 4

Examcode 77895 44678 22456 24562

S_Id 3 3 2 1

Note that the "S_Id" column in the "Exam_enrollment" table points to the "S_Id" column in the "student" table. The "S_Id" column in the "student" table is the PRIMARY KEY in the "student" table. The "S_Id" column in the "student" table is a FOREIGN KEY in the " Exam_enrollment table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY Constraint on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created: MySQL: CREATE TABLE Exam_enrollment ( serial int NOT NULL, examcode int NOT NULL, S_Id int, PRIMARY KEY (serial), FOREIGN KEY (serial) REFERENCES student(S_Id) ) To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Orders ( serial int NOT NULL,

examcode int NOT NULL, S_Id int, PRIMARY KEY (serial), CONSTRAINT fk_ Exam_enrollment FOREIGN KEY (S_Id) REFERENCES student(P_Id) )

SQL FOREIGN KEY Constraint on ALTER TABLE


To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Exam_enrollment ADD FOREIGN KEY (S_Id) REFERENCES student(S_Id) To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders ADD CONSTRAINT fk_ Exam_enrollment FOREIGN KEY (S_Id) REFERENCES student(S_Id)

To DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL: MySQL: ALTER TABLE Exam_enrollment DROP FOREIGN KEY fk_ Exam_enrollment

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

SQL CHECK Constraint on CREATE TABLE


The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0. My SQL: CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (S_Id>0) ) To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_student CHECK (S_Id>0 AND City='mumbai') )

SQL CHECK Constraint on ALTER TABLE


To create a CHECK constraint on the "P_Id" column when the table is already created, use the

following SQL: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE student ADD CHECK (S_Id>0) To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE student ADD CONSTRAINT chk_student CHECK (S_Id>0 AND City='mumbai')

SQL DEFAULT Constraint


The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified.

SQL DEFAULT Constraint on CREATE TABLE


The following SQL creates a DEFAULT constraint on the "City" column when the "student" table is created: My SQL / SQL Server / Oracle / MS Access: CREATE TABLE student ( S_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'mumbai' )

SQL DEFAULT Constraint on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use

the following SQL: MySQL: ALTER TABLE student ALTER City SET DEFAULT 'mumbai'

To DROP a DEFAULT Constraint


To drop a DEFAULT constraint, use the following SQL: MySQL: ALTER TABLE student ALTER City DROP DEFAULT

SQL CREATE INDEX Statement


Previous Next Chapter

The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading the whole table.

Indexes
An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:


CREATE INDEX index_name

ON table_name (column_name) SQL CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:


CREATE UNIQUE INDEX index_name ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "SIndex" on the "LastName" column in the "Persons" table:
CREATE INDEX SIndex ON student(LastName)

If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
CREATE INDEX SIndex ON student (LastName, FirstName)

Indexes, tables, and databases can easily be deleted/removed with the DROP statement.

The DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.
DROP INDEX Syntax for MySQL: ALTER TABLE table_name DROP INDEX index_name

The DROP TABLE Statement


The DROP TABLE statement is used to delete a table. DROP TABLE table_name

The DROP DATABASE Statement


The DROP DATABASE statement is used to delete a database.
DROP DATABASE database_name

The TRUNCATE TABLE Statement


What if we only want to delete the data inside the table, and not the table itself? Then, use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name

The ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax

To add a column in a table, use the following syntax:


ALTER TABLE table_name ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE table_name DROP COLUMN column_name

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name ALTER COLUMN column_name datatype ALTER TABLE student ALTER COLUMN DateOfBirth year

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "student" table. We use the following SQL statement: ALTER TABLE student DROP COLUMN DateOfBirth

Auto-increment allows a unique number to be generated when a new record is inserted into a table.

AUTO INCREMENT a Field


Very often we would like the value of the primary key field to be created automatically every time a new record is inserted. We would like to create an auto-increment field in a table.

Syntax for MySQL


The following SQL statement defines the "S_Id" column to be an auto-increment primary key field in the "Persons" table: CREATE TABLE student ( S_Id int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (S_Id)

) MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: ALTER TABLE student AUTO_INCREMENT=100

SQL Views
Previous Next Chapter

A view is a virtual table. This chapter shows how to create, update, and delete a view.

SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL 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 one single table.
SQL CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


If you have the Northwind database you can see that it has several 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 in the Northwind sample database selects every product in the "Products" table with a unit price 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]

Another view in 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'

SQL Updating a View


You can update a view by using the following syntax:
SQL CREATE OR REPLACE VIEW Syntax CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition

Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the following SQL:
CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No

SQL Dropping a View


You can delete a view with the DROP VIEW command.
SQL DROP VIEW Syntax DROP VIEW view_name

MySQL Date Functions

The following table lists the most important built-in date functions in MySQL: Function NOW() CURDATE() CURTIME() DATE() EXTRACT() DATE_ADD() DATE_SUB() DATEDIFF() DATE_FORMAT() Description Returns the current date and time Returns the current date Returns the current time Extracts the date part of a date or date/time expression Returns a single part of a date/time Adds a specified time interval to a date Subtracts a specified time interval from a date Returns the number of days between two dates Displays date/time data in different formats

Definition and Usage


NOW() returns the current date and time.
Syntax NOW()

Example

The following SELECT statement:


SELECT NOW(),CURDATE(),CURTIME()

SQL IS NULL
How do we select only the records with NULL values in the "Address" column? We will have to use the IS NULL operator: SELECT LastName,FirstName,Address FROM student WHERE Address IS NULL

SQL IS NOT NULL


How do we select only the records with no NULL values in the "Address" column?

We will have to use the IS NOT NULL operator: SELECT LastName,FirstName,Address FROM student WHERE Address IS NOT NULL

MySQL Data Types


In MySQL there are three main types : text, number, and Date/Time types. Text types: Data type CHAR(size) Description Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type Holds a string with a maximum length of 255 characters Holds a string with a maximum length of 65,535 characters For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data Holds a string with a maximum length of 16,777,215 characters For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data Holds a string with a maximum length of 4,294,967,295 characters For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z') Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

VARCHAR(size)

TINYTEXT TEXT BLOB MEDIUMTEXT MEDIUMBLOB LONGTEXT LONGBLOB ENUM(x,y,z,etc.)

SET

Number types: Data type TINYINT(size) Description -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number

of digits may be specified in parenthesis MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter *The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number. Date types: Data type DATE() Description A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31' *A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59' *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MMDD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-0109 03:14:07' UTC A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in

DATETIME()

TIMESTAMP()

TIME()

YEAR()

two-digit format: 70 to 69, representing years from 1970 to 2069 *Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:

AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value.

Useful scalar functions:


UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed

The AVG() Function


The AVG() function returns the average value of a numeric column.
SQL AVG() Syntax SELECT AVG(column_name) FROM table_name Eg SELECT AVG(marks) FROM student

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:
SELECT COUNT(column_name) FROM table_name SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:


SELECT COUNT(*) FROM student

The MAX() Function

The MAX() function returns the largest value of the selected column.
SQL MAX() Syntax SELECT MAX(column_name) FROM table_name Eg SELECT MAX(marks) FROM student

SQL MIN() Function

The MIN() Function


The MIN() function returns the smallest value of the selected column.
SQL MIN() Syntax SELECT MIN(column_name) FROM table_name SELECT MIN(marks) FROM student

SQL SUM() Function

The SUM() Function


The SUM() function returns the total sum of a numeric column.
SQL SUM() Syntax SELECT SUM(column_name) FROM table_name SELECT SUM(marks) FROM student

Aggregate functions often need an added GROUP BY statement.

The GROUP BY Statement


The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SQL GROUP BY Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer

GROUP BY More Than One Column


We can also use the GROUP BY statement on more than one column, like this: SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate

The HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
SQL HAVING Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000

Account Management Statements


In MySQL user account information?s are stored in mysql database tables. In this section we will describe you about Create User, Drop User, Grant Syntax, Rename User, Revoke Syntax and Set Password Syntax.

In MySQL user account information?s are stored in mysql database tables. In this section we will describe you about Create User, Drop User, Grant Syntax, Rename User, Revoke Syntax and Set Password Syntax.

CREATE USER Syntax The general syntax of CREATE USER statement is : CREATE USER user [IDENTIFIED BY [PASSWORD] 'password']..... In It is used to create a new MySQL account. But for using this statement you need the global CREATE USER privilege or the INSERT privilege for mysql database. The CREATE USER statement creates a new record for each account in user table of mysql database. But if account is already exists then it occurs the error message. By the IDENTIFIED BY clause we can give the password to account. If you want to specify a password in plain text the does not include the PASSWORD keyword. But when you specify the PASSWORD keyword then password returned as the hashed value by the PASSWORD() function. Each account can be named by using the same format as for GRANT statement like ?root?@?localhost?. But when you define only the username as part of the account name then a hostname part of ?%? is used. Example :
mysql> CREATE USER chandan IDENTIFIED BY 'chandan'; Query OK, 0 rows affected (0.04 sec) mysql> select user from user; +---------+ | user | +---------+ | | | chandan | | | | root | +---------+ 4 rows in set (0.00 sec)

DROP USER Syntax The general syntax of DROP USER statement is : DROP USER user [, user] ... DROP USER statement is used to remove one or more than MySQL account. But for using this statement you need the global CREATE USER privilege or DELETE privilege. Example :
mysql> DROP USER chandan; Query OK, 0 rows affected (0.69 sec) mysql> select user from user; +------+ | user | +------+ | | | | | root | +------+ 3 rows in set (0.11 sec)

This statement is used to delete only that MySQL accounts which have no privileges and it removes each account only from user table. For removing a MySQL account completely you have to perform the following steps :

Firstly use SHOW GRANTS statements for determining the account has what type of privileges. Then use REVOKE statement for revoking the privileges that displayed by SHOW GRANTS statement. Use DROP USER statement for removing the account.

DROP USER statement cannot automatically close any open user session. But, if any open session user is dropped then this statement does not effect until the session is closed. After closing the session the user is dropped. GRANT Syntax The general syntax of GRANT statement is: GRANT priv_type [(column_list)] [, priv_type [(column_list)]] ... ON [object_type] {tbl_name | * | *.* | db_name.*} TO user [IDENTIFIED BY [PASSWORD] 'password'] [, user [IDENTIFIED BY [PASSWORD] 'password']] ... [WITH with_option [with_option] ...] object_type = TABLE | FUNCTION | PROCEDURE with_option = GRANT OPTION | MAX_QUERIES_PER_HOUR count | MAX_UPDATES_PER_HOUR count | MAX_CONNECTIONS_PER_HOUR count | MAX_USER_CONNECTIONS count By using GRANT statement we can enable the system administrator for creating MySQL user accounts and for granting the right to from accounts. But for using the GRANT statement you need the GRANT OPTION privilege and you also required the privileges which you are granting. The REVOKE statement is used to relate and enable the administrator for removing the account privileges. But when grant tables hold the privilege rows which contain the mixed case database or the table name and the lower_case_table_name system variable is set to non-zero value then REVOKE statement cannot used for revoking these privileges. Privileges can be granted at several levels:

Global level Global level privileges are applied to all databases on a given server. These type of privileges are stored in the user table of mysql database. Ex ? GRANT ALL ON *.* and REVOKE ALL ON *.*; Database level Database level privileges are applied to all objects in a given database. These type of privileges are stored in the db and host tables of the mysql databases. Ex ? GRANT ALL ON

database_ name.* and REVOKE ALL ON database_name.*

Table level Table level privileges are applied to all columns on a given table. These type of privileges are stored in the table_priv table of the mysql database. EX ? GRANT ALL ON database_name.table_name and REVOKE ALL ON database_name.table_name. Column level Column level privileges are applied to single column on a given table. These type of privileges are stored in columns_priv table of mysql database. And at the time of using REVOKE statement you have to specify the same column name that were granted. Routine level Routine level privileges like CREATE ROUTINE, EXECUTE, ALTER ROUTING and GRANT privileges are applied to stored routines. These type of privileges can be granted at global and database level. Except CREATE ROUTINE, rest of these privileges can be granted at routine level for particular routines and they are stored in the procs_priv table of mysql database.

The object_type clause was included in the version of MySQL5.0.6. This clause can be defined as TABLE, FUNCTION or PROCEDURE when the following object is a table, function or procedure. priv_type can be specified as any of the following : Privilege
ALL [PRIVILEGES] ALTER CREATE CREATE USER CREATE VIEW DELETE DROP INSERT SELECT

Meaning
Sets all simple privileges except GRANT OPTION Enables use of ALTER TABLE Enables use of CREATE TABLE Enables use of CREATE USER, DROP USER, RENAME USER, and REVOKE ALL PRIVILEGES. Enables use of CREATE VIEW Enables use of DELETE Enables use of DROP TABLE Enables use of INSERT Enables use of SELECT

UPDATE USAGE GRANT OPTION

Enables use of UPDATE Synonym for ?no privileges? Enables privileges to be granted

The privileges like PROCESS, FILE, REPLICATION CLIENT, RELOAD, REPLICATION SLAVE, SHUTDOWN, SHOW DATABASES, SUPER privileges are administrative privileges which can only be granted globally. And other privileges can also be granted global or more specific levels. Example for granting the global privilege :
mysql> CREATE USER raj@localhost IDENTIFIED BY 'raj'; Query OK, 0 rows affected (0.00 sec) mysql> select user from user; +---------+ | user | +---------+ | | | chandan | | | | raj | | root | +---------+ 5 rows in set (0.00 sec) mysql> GRANT ALL ON *.* TO raj@localhost; Query OK, 0 rows affected (0.00 sec)

In usernames Mysql does not support wildcards. Anonymous users are defined by inserting in user table of mysql database with User=?? or creating a user account with an empty name with the GRANT statement. By executing the following query of any anonymous users :
mysql> SELECT HOST, USER FROM USER WHERE USER=''; +-----------+------+ | HOST | USER | +-----------+------+ | % | | | localhost | | +-----------+------+ 2 rows in set (0.00 sec)

By using following statement you can delete the local anonymous user account :
mysql> DELETE FROM USER WHERE HOST='localhost' AND User=''; Query OK, 1 row affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.06 sec)

The WITH GRANT OPTIONS clause is used to provide the ability to user for providing to

other users any privileges. But you have to careful about who is providing you the GRANT OPTION privilege because two users that have the different privileges can be able to join privileges. By the GRANT OPTION you can only assign only those privilege which yourself you have. The MAX_QUERIES_PER_HOUR count, MAX_UPDATES_PER_HOUR count, and MAX_CONNECTIONS_PER_HOUR count options is used to limit the total number of queries, updates and logins, a user can perform these between specified one hour period. But if count is 0 then there is no limitation for that user. The MAX_USER_CONNECTIONS count option is used to limit the number of simultaneous connections, which the account can make. RENAME USER Syntax The general syntax of RENAME USER statement is: RENAME USER old_user TO new_user [, old_user TO new_user] ... The RENAME USER statement is used to rename the existing MySQL user accounts but for using this statement you need the global CREATE USER privilege or the UPDATE privilege. But if old account does not exists or the new account exists then it occurs the error. Example :
mysql> RENAME USER chandan TO chand; Query OK, 0 rows affected (0.80 sec) mysql> SELECT User FROM User; +-------+ | User | +-------+ | | | chand | | raj | | root | +-------+ 4 rows in set (0.16 sec)

REVOKE Syntax The general syntax of REVOKE statement is : REVOKE priv_type [(column_list)] [, priv_type [(column_list)]] ... ON [object_type] {tbl_name | * | *.* | db_name.*} FROM user [, user] ... REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ... The REVOKE statement is used to enable the system administrator for revoking the privileges from MySQL accounts but for using this statement you need the GRANT OPTION privilege and you also need the privileges that you are revoking. All level of privileges and allowable priv_type values we have discussed above. But when grant tables hold the privilege rows which contain the mixed case database or the

table name and the lower_case_table_name system variable is set to non-zero value then REVOKE statement cannot used for revoking these privileges. It will be necessary to manipulate the grant tables directly. By using following statement you can revoke all privileges for the name user. Example :
mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM chand; Query OK, 0 rows affected (0.01 sec) mysql> SHOW GRANTS FOR chand \G; *************************** 1. row *************************** Grants for chand@%: GRANT USAGE ON *.* TO 'chand'@'%' IDENTIFIED BY PASSWORD '*A 59F8074680E742CC90A8595EFD7D1404FC8ED2F' 1 row in set (0.00 sec)

SET PASSWORD Syntax The general syntax of SET PASSWORD statement is: SET PASSWORD [FOR user] = PASSWORD('some password') The SET PASSWORD statement is used to assign a password to existing user. If you are not using FOR clause then its set the password for the current user. Any client using non anonymous account and it is connected with the server can change the password for that account. But if you are using FOR clause then it sets the password for a specified account on current server host but for this you must have the UPDATE privilege. Example :
mysql> SELECT User, Password FROM User; +-------+------------------------------------------+ | User | Password | +-------+------------------------------------------+ | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | | | | raj | *7A5773507B1A6F85B4954BC90D6FB55416B0DCF8 | | chand | *DD13F1F66054912AB8F82CA33BBDEE9E442582DB | +-------+------------------------------------------+ 4 rows in set (0.00 sec) mysql> SET PASSWORD FOR chand=PASSWORD('chand2'); Query OK, 0 rows affected (0.00 sec) mysql> SELECT User, Password FROM User; +-------+------------------------------------------+ | User | Password | +-------+------------------------------------------

-+ | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | | | | raj | *7A5773507B1A6F85B4954BC90D6FB55416B0DCF8 | | chand | *8CCD023D22DCD5607CD453A60598EF23B29DCA6B | +-------+------------------------------------------+ 4 rows in set (0.00 sec)

Writing Subqueries Posted on: March 13, 2008 at 12:00 AM A subquery can be defined as a query within a query. In other words, any query results that we reuse in another query. Subquery is known as nestee queries or subselects also. Subqueries don?t include any new functionality but the queries are more readable

Writing Subqueries

A subquery can be defined as a query within a query. In other words, any query results that we reuse in another query. Subquery is known as nestee queries or subselects also. Subqueries don?t include any new functionality but the queries are more readable with using subqueries rather than of joins. We will describe you the subqueries with the help of following tables :
mysql> SELECT * FROM Client; +------+---------------+----------+ | C_ID | Name | City | +------+---------------+----------+ | 1 | A K Ltd | Delhi | | 2 | V K Associate | Mumbai | | 3 | R K India | Banglore | | 4 | R S P Ltd | Kolkata | | 5 | A T Ltd | Delhi | | 6 | D T Info | Delhi | +------+---------------+----------+ 6 rows in set (0.08 sec) mysql> SELECT * FROM Products; +---------+-------------+------+----------+ | Prod_ID | Prod_Detail | C_ID | price | +---------+-------------+------+----------+ | 111 | Monitor | 1 | 7000.00 | | 112 | Processor | 2 | 11000.00 | | 113 | Keyboard | 2 | 1200.00 |

| 114 | Mouse | 3 | 500.00 | | 115 | CPU | 5 | 15500.00 | +---------+-------------+------+----------+ 5 rows in set (0.00 sec)

There are 3 basic types of subqueries in SQL:


Predicate Subqueries - extended logical constructs in the WHERE (and HAVING) clause. Scalar Subqueries - standalone queries that return a single value; they can be used anywhere a scalar value is used. Table Subqueries - queries nested in the FROM clause.

All subqueries must be enclosed in parentheses. Predicate Subqueries Predicate Subqueries can be used in the HAVING and WHERE clause only because both are special logical construct. These subqueries must retrieve one column.

IN Subquery The IN subquery tests if a scalar values match with the single query column value in any subquery result row. The general syntax is : Value_1 [NOT] IN (query_1)

In the following example we are getting the list of clients that are available in Products table also. Example :
mysql> SELECT * FROM Client WHERE C_ID IN -> (SELECT C_ID FROM Products); +------+---------------+---------+ | C_ID | Name | City | +------+---------------+---------+ | 1 | A K Ltd | Delhi | | 2 | V K Associate | Mumbai | | 3 | R K India | Banglore | | 5 | A T Ltd | Delhi | +------+---------------+---------+ 4 rows in set (0.00 sec)

In the following example we are getting the list of clients that are not available in Products table also. Example :

mysql> SELECT * FROM Client WHERE C_ID NOT IN -> (SELECT C_ID FROM Products); +------+-----------+---------+ | C_ID | Name | City | +------+-----------+---------+ | 4 | R S P Ltd | Kolkata | | 6 | D T Info | Delhi | +------+-----------+---------+ 2 rows in set (0.01 sec)

Quantified Subqueries A quantified subquery can use the all comparison operators for several types of tests. The general syntax is : Value_1 {=|>|<|>=|<=|<>} {ANY | ALL | SOME} (query_1) The comparison operator is used to compare value_1 to the single query column value from each subquery result row. If we are using ALL clause then must match the all rows in subquery, or subquery must be empty. If we are using ANY or SOME clause then must match at least one row in the subquery. Example :

mysql> SELECT * FROM Client WHERE C_ID= ANY(SELECT C_ID FROM Products); +------+---------------+----------+ | C_ID | Name | City | +------+---------------+----------+ | 1 | A K Ltd | Delhi | | 2 | V K Associate | Mumbai | | 3 | R K India | Banglore | | 5 | A T Ltd | Delhi | +------+---------------+----------+ 4 rows in set (0.00 sec)

Exists Subqueries The EXISTS subquery is used to tests whether a subquery returns at least one row or a qualifying row exists. The general syntax is : Exists (query_1) Any EXISTS subquery should contain an outer reference. It must be a correlated subquery. Example :

mysql> SELECT * FROM Client -> WHERE EXISTS -> (SELECT * FROM Products WHERE Client.C_ID=Products.C_ID); +------+---------------+----------+ | C_ID | Name | City | +------+---------------+----------+ | 1 | A K Ltd | Delhi | | 2 | V K Associate | Mumbai | | 3 | R K India | Banglore | | 5 | A T Ltd | Delhi | +------+---------------+----------+ 4 rows in set (0.00 sec)

Scalar Subqueries The Scalar Subquery is a subquery which returns a single value. A Scalar subquery can be used almost anywhere a single column value can be used. The subquery have to reference only one column in the select list. It must not retrieve more than one row. When subquery retrieve one row then the value of select list column becomes the value of the Scalar Subquery. Example :
mysql> SELECT (SELECT Name FROM Client WHERE C_ID=1); +----------------------------------------+ | (SELECT Name FROM Client WHERE C_ID=1) | +----------------------------------------+ | A K Ltd | +----------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT (SELECT C_ID FROM Products WHERE C_ID=2) FROM Client; ERROR 1242 (21000): Subquery returns more than 1 row mysql> SELECT (SELECT C_ID FROM Products WHERE C_ID=1) FROM Client; +------------------------------------------+ | (SELECT C_ID FROM Products WHERE C_ID=1) | +------------------------------------------+ | 1 | | 1 | | 1 | | 1 | | 1 | | 1 | +------------------------------------------+ 6 rows in set (0.01 sec)

Table Subqueries Table subqueries are used in the FROM Clause , replace the table name. These subqueries can have correlation name also. Example :

mysql> SELECT Client.*,Price -> FROM Client, Products -> WHERE Client.C_ID=Products.C_ID -> AND Price>1000; +------+---------------+--------+----------+ | C_ID | Name | City | Price | +------+---------------+--------+----------+ | 1 | A K Ltd | Delhi | 7000.00 | | 2 | V K Associate | Mumbai | 11000.00 | | 2 | V K Associate | Mumbai | 1200.00 | | 5 | A T Ltd | Delhi | 15500.00 | +------+---------------+--------+----------+ 4 rows in set (0.06 sec)

Using Single Value Subqueries Firstly we will start with a simple query :
mysql> SELECT MAX(Price) FROM Products; +------------+ | MAX(Price) | +------------+ | 15500.00 | +------------+ 1 row in set (0.60 sec)

The above example retrieve only a single value and its representing the maximum Price of the Product. In this example we used a MySQL Function MAX() that finds the greatest values in a specified column. Single ? value subqueries is used to return a single column value and then they are typically used for comparison. For Example :
mysql> SELECT * FROM Client c,Products p WHERE c.C_ID=p.C_ID -> AND p.Price=(SELECT MAX(Price) FROM Products); +------+---------+-------+---------+------------+------+----------+ | C_ID | Name | City | Prod_ID | Prod_Detail | C_ID | price | +------+---------+-------+---------+------------+------+----------+ | 5 | A T Ltd | Delhi | 115 | CPU | 5 | 15500.00 | +------+---------+-------+---------+------------+------+----------+ 1 row in set (0.02 sec)

In the above example we are getting the detail of products that have the highest price and the client details also.

Das könnte Ihnen auch gefallen