SQL

SQL


1.    SELECT id, name, FROM Products;    
//Retrieving Multiple or Individual Columns from the specific DB-table
2.    SELECT * FROM Products;          
//Retrieving All Columns (* stand for / means all columns)
3.    SELECT id, name, price FROM Products order by price, name;
//Sorting By Multiple Columns name
//Order by == Sort by == Classify by == Categorize by = Assort /Class /Separate
4.    SELECT id, name, price FROM Products order by 2,3;  
//Sorting By Columns Position or Number or Index
5.    SELECT id, name, price FROM Products order by 2  DESC/ASC;  
//Sorting By Sort Direction( Descend / ascend; Descendance / Ascendance)
6.    SELECT id, name, price FROM Products WHERE price = 3;  
//Using the WHERE Clause as search condition


WHERE Clause Operators
=    Equality
<>    Nonequality
!=    Nonequality
<    Less than
<=    Less than or equal to
!<    Not less than
>    Greater than
>=    Greater than or equal to
!>    Not greater than
BETWEEN    Between two specified values
IS NULL    Is a NULL value


7.    SELECT id, price, FROM Products WHERE id= ‘D’ and price <=3
//Combining WHERE Clauses with operator “and” as more search condition
8.    SELECT id, price, FROM Products WHERE id= ‘D’ or price <=3
 //Combining WHERE Clauses with operator ‘Or” as connective search condition
9.    SELECT id, price, FROM Products WHERE id= ‘D’ or id = ‘E’ and price <=3
//Combining Where Clause with more than one operator by using order
10.    SELECT id, price, FROM Products WHERE ( id= ‘D’ or id = ‘E’ ) and price <=3
11.    SELECT id, price, FROM Products WHERE id in (‘D’, ‘E’) order by price;
 //Using the IN operator to express more than one operator ‘or’.
12.    SELECT id, FROM Products WHERE NOT id =‘D’ order by price;
//Using the NOT operator to express the negative or Non equality
13.    SELECT id, name FROM Products WHERE name like ‘Fish%’;
//Using the like Wildcard ‘…%...’ for finding the string including substring provided by you
14.    SELECT name + ‘ (‘ + country + ‘)” FROM Venders order by name;
//Using concatenating/connective/connecting Fields
15.    SELECT name || ‘ (‘ || country || ‘)” FROM Venders order by name;
//Using concatenating Fields
16.    SELECT RTRIM(name)  || ‘ (‘ || country || ‘)’  FROM Venders ;
//Using RTRIM to trim the string retrieved after getting record set
17.    SELECT RTRIM(name)  || ‘ (‘ || country || ‘)’ AS title FROM Venders ;
//Using alias AS name of searching result
18.    SELECT id, quantity*price AS real_price FROM OrderItems WHERE id = 2;
//Performing Mathematical Calculations    
19.    SELECT name, UPPER(name) AS NameUpCase FROM Vendors order by name;
//Commonly used Text-Manipulation Functions:
LEFT(), LENGTH(), LOWER(), LTRIM(), RTRIM(), SOUNDEX(), UPPER(), UCASE(), LCASE();
//Date and Time Manipulation Functions: DATEPART(), YEAR(), to_number(), to_char();
//Commonly Used Numeric Manipulation Functions: ABS(), COS(), EXP(), PI(), SIN(), SQRT(), TAN()
20.    SELECT AVG( price ) AS average_price FROM Products;
//SQL Aggregate Functions: AVG(), COUNT(), MAX(), MIN(), SUM()
21.    SELECT AVG( DISTINCT price ) AS ave_price FROM Products;
//Aggregates on Distinct Values
22.    SELECT COUNT(*) AS A, MIN(price) AS P, MAX(price) AS PP, AVG(price) AP FROM Products;
23.    SELECT COUNT(*) AS products FROM Products WHERE id = ‘D”;
//Data grouping with WHERE clause
24.    SELECT id, COUNT(*) AS products FROM Products GROUP BY id;
 //Creating groups with GROUP BY clause
25.    SELECT COUNT(*) AS products FROM Products GROUP BY id HAVING COUNT(*) >2;
//Filtering groups By using HAVING clause and GROUP BY clause
26.    SELECT id, count(*) AS products FROM Products WHERE price >=4 GROUP BY id HAVING COUNT(*) >=2;
//Filtering groups by using HAVING clause and WHERE clause
27.    SELECT order, COUNT(*) AS item FROM table GROUP BY order HAVING COUNT(*) >2 ORDER BY item, order;
//Filtering By Sub-query ( column name IN ( sub-query) )
28.    SELECT name, contact FROM customers WHERE id IN ( SELECT id FROM order WHERE order IN ( SELECT order FROM OrderItems WHERE id = ‘Dragon’));
//Using sub-queries As Calculated Fields
29.    SELECT name, state, (SELECT COUNT(*) FROM order WHERE order.id = Customers.id ) AS order FROM Customers ORDER BY name;
//Creating A Join with INNER JOIN table-name ON table1.column = table2.column.
30.    SELECT name, price FROM vendors INNER JOIN Products ON vender.id = products.vend_id;
 //Creating A Join with WHERE clause and more than one constraint conditions
31.    SELECT prod_name, vend_name,prod_price,quantity FROM orderItems, Products,Vendors WHERE Products.vend_id = Vendors.vend_id AND OrderItems.id = products.id AND order_num = 20001;
32.    //Using Table Aliases with key words ‘AS’
33.    SELECT name, contact FROM customers AS C, Orders AS O WHERE C.id = O.id;
34.    //Using Different Join Types
35.    SELECT id, name, contact FROM customers WHERE name = ( SELECT name FROM Customers);
36.    SELECT …; …; FROM .., .., WHERE ..=.., AND … = … ;
37.    SELECT …; …; …; FROM … INNDER JOIN … ON … = …;
38.    // Using Joins With Aggregate Functions
39.    SELECT .., …, COUNT( num) AS … FORM … INNDER JOIN … ON … = … GROUP BY…, ORDER BY…, HAVING…;
40.    //Creating Combined Queries
41.    SELECT name, contact, email FROM customers WHERE state IN (‘CH’, ‘IN’, ‘MI’);
42.    SELECT name, contact, email FORM customers WHERE name = ‘Dragon’;
43.    SELECT name, contact, email FROM customers WHERE state IN (‘CH’, ‘IN’, ‘MI’) UNION SELECT name, contact, email FORM customers WHERE name = ‘Dragon’ ORDER BY name;


DML

//Understanding Data insertion or Data manipulation
44.    INSERT INTO customers VALUSE(‘dddd’, ’ddd’, NULL, NULL);
INSERT INTO tablename([]/[some of columns]) VALUSE(‘…’,……….);
45.    INSERT INTO customers(id, name, address ) VALUSE(‘dddd’, ’ddd’, NULL, NULL);
46.    //Copying From One Table to Another
47.    SELECT * INTO customer_copy FROM customers;
//Selecting all columns into the new table means copy
48.    CREATE TABLE customer_copy AS SELECT * FROM customers;
//Create a table with the result by quering
//Updating And Deleting Data
50.    UPDATE customers SET customer_email = ‘al@sina.com’ , contact = ‘Sam Roberts’ WHERE customer_id = ‘kkkk’;
//Update the table with SET column = ‘…’ and WHERE search condition
51.    DELETE FROM customers WHERE id = ‘kkkkk’;
//Delete the line from table. Using DROP table-name to delete a table. Using ALTER table-name DROP column name to delete the column from table
52.    //Creating Tables
53.    CREATE TABLE Products( id  CHAR(10)  NOT  NULL, name CHAR(10)  NOT  NULL, price DECIMAL(8,2)  NOT NULL, description  VARCHAR(100) NULL);
    //Creating table: column name type | constraint | reference | foreign |
54.    CREATE TABLE Orders (number INTERGER NOT NULL, date DATTIME NOT NULL);
55.    //Updating Tables
56.    ALTER TABLE vendors ADD vend_phone CHAR(20);
//Appending a column into table with ALTER TABLE
57.    ALTER TABLE vendors DROP COLUMN vend_phone;
//Delete a column from table with DROP COLUMN
58.    //Deleting Tables
59.    DROP TABLE vendors;
60.    //Creating Views
61.    CREATE VIEW view AS SELECT name, contact, id FROM orders, customers WHERE customers.id = order.id;
//CREATE VIEW view-name AS ( sub-query as view’s content)
62.    //Stored procedures are simply collections of one or more SQL statements saved for futures use. You can think of them as batch files, although in truth they are more than that.
63.    EXECUTE ADDNewProduct(‘ddd’, ‘eee’, ‘ccc’, 9 ,);
64.    //EXECUTE takes the name of the stored procedure and any parameters that need to be passed to it.
65.    //Creating Stored Procedures   

CREATE PROCEDURE MailingListCount (ListCount OUT NUMBER)
AS
BEGIN
      SELECT * FROM customers WHERE NOT email IS NULL;
      ListCount := SQL%ROWCOUNT;
END;

67.    //Here is the Microsoft SQL Server version

CREATE PROCEDURE MailingListCount
AS
DECLARE @count INTERGER
SELECT @count = COUNT(*) FROM customers WHERE NOT email IS NULL;
RETURN @count;


69.    

CREATE PROCEDURE NewOrder  @id  CHAR(10
AS
DECLARS @number INTEGER
SELECT @number = MAX(order_number) FROM Orders
SELECT @order_number = @order_number+1
INSERT INTO Orders(number, date, id) VALUSE (@order_number, GETDATE(), @id)
RETURN @order_number;


70.     //Controlling Transactions


BEGIN TRANSACTION  … …(SQL statement) … COMMIT TRANSACTION;
SAVE TRANSACTION  delete_point;
ROLLBACK TRANSACTION delete_point;


74.    //Creating Cursors

DECLARE customers_cursor CURSOR FOR SELECT * FROM customers WHERE email IS NULL;


76.    //Using Cursors


OPEN CURSOR customers_cursor;
DECLARE TYPE customers_cursor IS REF CURSOR RETURN customers%ROWTYPE;
DECLARE customers_record customers%ROWTYPE
BEGIN
     OPEN customers_cursor;
     FETCH customers_cursor INTO customers_record;
     CLOSE customers_cursor;
END;


79.    //Understanding Constraints
80.    CREATE TABLE vendors (id CHAR(10) NOT NULL PRIMARY KEY, ….);
81.    ALTER TABLE vendors ADD CONSTRAINT PRIMARY KEY (id);
82.    CREATE TABLE vendors (id CHAR(10) NOT NULL PRIMARY KEY, num INTEGER NOT NULL REFERENCES customers (customers_id) );
83.    ALTER TABLE customers ADD CONSTRAINT FOREIGN KEY (id) REFERENCES customers (customers_id) );


84.    //Creating Index
85.    CREATE INDEX products_name_index ON PRODUCTS (products_name);
86.    //Depending/Based on the DBMS being used, triggers can be executed before or after a specified operation is performed.

87.    

CREATE TRIGGER customers_state
ON customers
FOR INSERT, UPDATE   //The trigger will be touched off when operations appear.
AS
UPDATE customers
SET cusomters_state = Upper(customer_state)
WHERE customers.id = inserted.id;

SQL Statement Syntax

 ALTER TABLE table_name
(
ADD|DROP  column datatype      //Adding or deleting a column
 [NULL|NOT NULL]
 [CONSTRAINTS],
 … );
COMMIT [TRASACTION];

CREATE INDEX index_name
ON table_name (column, …);


92.  

 CREATE PROCEDURE procedure_name [parameter] [options]
AS
SQL statement;

93.

CREATE TABLE table_name
(
column  datatype  [NULL|NOT NULL] [CONSTRAINTS],
 … );


94.    

CREATE VIEW view_name
AS
SELECT columns, …
FROM tables, …
[WHERE …]
[GROUP BY …]
[HAVING …]
[ORDER BY..]


95.    DELETE FROM table_name  [WHERE ..];
96.    DROP INDEX|PROCEDURE|TABLE|VIEW name;
97.    INSERT INTO table_name [(columns, … ) ] VALUES ( values, …);
98.    

INSERT INTO table_name[(columns,…)]
SELECT columns, …
FROM table_name
[WHERE ..];


99.    ROLLBACK [TO save_point_name];
100.    ROLLBACK TRANSACTION;
101.    

SELECT column_name,…
FROM table_name,…
[WHERE…]
[UNION …]
[GROUP BY …]
[ HAVING …]
[INNER JOIN …ON…]
[ ORDER BY …];
102.    UPDATE table_name
SET column_name = value, …
[WHERE …];


103.    //String Data Types:  
CHAR, NCHAR, NVARCHAR, TEXT (also called LONG or MEMO or VARCHAR)
104.    //Numeric Date Types;
BIT, DECIMAL(also called NUMERIC), FLOAT(NUMBER), INT(INTEGER), REAL, SAMLLINT, TINYINT
105.    //Date And Time Date Types;
DATE, DATETIME(TIMESTAMP), SMALLDATETIME, TIME
106.    //Binary Data Types
BINARY, LONG RAW, RAW(BINARY), VARBINARY

原文地址:https://www.cnblogs.com/iiiDragon/p/3238676.html