Beruflich Dokumente
Kultur Dokumente
SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard
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
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.
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
and
SELECT * FROM table_name; Eg SELECT * FROM employee
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'
The AND & OR operators are used to filter records based on more than one condition.
SELECT * FROM employee WHERE FirstName='Tove' AND LastName='Svendson' SELECT * FROM employee WHERE FirstName='Tove' OR FirstName='Ola'
We use the following SELECT statement: SELECT * FROM employee ORDER BY LastName DESC
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')
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';
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'
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%'
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.
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.
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
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
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
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.
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
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.
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:
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) )
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.
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) )
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).
Serial_no 1 2 3 4
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.
examcode int NOT NULL, S_Id int, PRIMARY KEY (serial), CONSTRAINT fk_ Exam_enrollment FOREIGN KEY (S_Id) REFERENCES student(P_Id) )
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.
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')
the following SQL: MySQL: ALTER TABLE student ALTER City SET DEFAULT 'mumbai'
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
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.
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.
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
Auto-increment allows a unique number to be generated when a new record is inserted into a table.
) 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.
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.
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)
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 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'
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
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
Example
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
We will have to use the IS NOT NULL operator: SELECT LastName,FirstName,Address FROM student WHERE Address IS NOT NULL
VARCHAR(size)
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.
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
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 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 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 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
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
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
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)
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.