SQL summary Format of insert statement: INSERT INTO <table> (<field>) VALUES <value1>, <value2>, … , <valuen> //Insert a record with the values to the fields listed Format of delete statement: (use with caution) DELETE FROM <table> WHERE <condition> AND/OR <condition> //Delete the record with the field that fits the condition Updating Data in a Table: UPDATE <table> SET <field> = <new value> WHERE <field> = <existing value> //Change the value in the fields of the record that fits the condition to the new value Format of order statement SELECT <field(s)> FROM <table> ORDER BY <field1>, … , <fieldn> //Order the records alphabetically by the first field then the next field SELECT <field(s)> FROM <table> ORDER BY <field1> DESC, … , <fieldn> DESC //Order the records alphabetically in descending order by the first field then the next field Selecting Data in a Table SELECT <field(s)> FROM <table> //Limit the amount of fields on the table SELECT * FROM <table> //Show all fields of the table Format to see specific records SELECT <field(s)> FROM <table> WHERE <condition> // Show the records that fit the condition SELECT <field(s)> FROM <table> WHERE <condition> LIKE <%pattern> //The records where the pattern exists at the end of the value LIKE <pattern%> //The records where the pattern exists at the beginning of the value LIKE <%pattern%> //The records where the pattern exists anywhere in the value SELECT <field(s)> FROM <table> WHERE <condition> AND <condition> //The records where both the conditions are true SELECT <field(s)> FROM <table> WHERE <condition> OR <condition> //The records where either of the conditions are true SELECT <field(s)> FROM <table> WHERE <field> BETWEEN <value1> AND <value2> //The records where the field has values between the two values specified SELECT <field(s)> FROM <table> WHERE <condition> LIMIT <value> //Only the records before the limit value are shown SELECT <fields> FROM <table> WHERE <condition> GROUP BY <field> HAVING (<condition1>, <condition2>…) //Having is for the conditions for the new result set NB* use only when using GROUP BY SELECT DISTINCT <fields> FROM <table> //Removes all duplicates Format for word manipulation SELECT LEFT(<field>,<value>) AS <field> FROM <table> //characters from left until the value SELECT RIGHT(<field> , <value>) AS <field> FROM <table> //all characters from right until the value from right SELECT MID(<field>, <value1>, <value2>) AS <field> FROM <table> //all characters from value 1 until the amount of value 2 e.g. (3,2) will give you the 3rd and 4th values SELECT LENGTH(<field>) AS <field> FROM <table> //give the length of the field SELECT CONCAT(<value1>,<value2>,<value3>) AS <field> FROM <table> //gives the values combined together as one value Format for date manipulation SELECT MONTH(<field>) AS <field> FROM <table> //gives the month of the date SELECT DAY(<field>) AS <field> FROM <table> //gives the day of the date SELECT YEAR(<field>) AS <field> FROM <table> //gives the year of the date SELECT NOW() AS <field> FROM <table> //gives the current date from the computer clock Format for number manipulation SELECT AVG(<field>) AS <field> FROM <table> //gives the average of the records for that field SELECT COUNT(*) FROM <table> WHERE <condition> //Counts the amount of records in the table with the condition SELECT MAX(<field>) AS <field> FROM <table> //Show the record with the biggest value in the field SELECT MIN(<fields>) AS <field> FROM <table> //Show the record with the smallest value in the field SELECT SUM(<field>) AS <field> FROM <table> //Show total sum of the records in the field SELECT <field>, COUNT(*) AS <field> FROM <table> WHERE <condition> GROUP BY <field> //Show the amount of records in every field in the group by condition SELECT ROUND(<field>,<value>) AS <field> FROM <table> //Rounds the field off to the “valueth” decimal place e.g. (3.456,1) => 3.5 SELECT RAND( ) AS <field> FROM <table> //Gives a random number from 0 to 0.9999… SELECT MOD(<value>,<value>) AS <field> FROM <table> //Gives the remainder of the first value after dividing by the second value, same as the % for java SELECT TRUNCATE(<field manipulated>) FROM <table> //Gives the value in the same format as the field SELECT <field> FROM <table> WHERE <field> IN (<value>, <value> …) //Same as saying <field> = <value> OR <field> = <value> … Format for table joins SELECT <table>.<field> FROM <table1>, <table2> WHERE <table1>.<field> = <table2>.<field> //Inner join by just using where conditions SELECT <table>.<field> FROM <table1> INNER JOIN <table2> ON <table1>.<field> = <table2>.<field> //Inner join with full format and the order of the tables do not matter SELECT <table>.<field> FROM <table1> LEFT OUTER JOIN <table2> ON <table1>.<field> = <table2>.<field> //Outer join, table 1 contains info and the second has null value SELECT <table>.<field> FROM <table1> RIGHT OUTER JOIN <table2> ON <table1>.<field> = <table2>.<field> //Outer join, table 2 contains info and the first has null value SELECT <table>.<field> FROM <table1> FULL JOIN <table2> ON <table1>.<field> = <table2>.<field> //Outer join, either table has info and either can have null value Order of the select SELECT DISTINCT <field> FROM <table> WHERE <condition> GROUP BY <field> HAVING <condition> ORDER BY <field> LIMIT <value> SQL Summary of all functions that the IEB could possibly ask in exams. From: http://webcheatsheet.com/sql AVG SELECT Position, Avg(Salary) AS AvgSalary FROM EmployeeStatisticsTable GROUP BY Position Calculates the arithmetic mean (the sum of the values divided by the number of values). CHR SELECT Chr(37) AS Char1, Chr(100) AS Char2 FROM Orders It returns the character associated with the specified ANSI code. COUNT SELECT SellerID, Count(Item) AS Quantity FROM Antiques GROUP BY SellerID Interval Description It calculates the number of records in a select query. yyyy Year DATE SELECT Date() AS Dates FROM Orders It returns a value such as '05.05.2005', q Quater Similar: NOW, except Now returns date and time m Month DATEADD SELECT DateAdd('d',45, Now()) AS Diff FROM Orders y Day of year DATEDIFF Format: DateAdd ( interval, number, date ) w Weekday SELECT DateDiff('d',#05/05/1985#, Now()) AS diff FROM Orders Format: DateDiff ( interval, date1, date2) ww Week The interval is the interval of time you want to add/subtract. h Hour The number is the number of intervals you want to add/subtract. n Minute It can be positive (to get dates in the future) or s Second negative (to get dates in the past). DAY FIRST FIX INT FORMAT IIF ISNULL LCASE / UCASE LEFT The date is the date to which the interval is added/subtracted. SELECT Day(bdate) AS bdDay FROM Orders Similar: hour, minute, month, year, etc. To get part of a date. SELECT First([ItemDesired]) AS One FROM Orders It returns a field value from the first record in the result set of a query. Same as top 1. Opposite: LAST SELECT Fix([Price]) AS intPrice FROM Antiques Same as: SELECT int([Price]) AS intPrice FROM Antiques It returns the integer portion of a number. SELECT Format([BirthDate],'yyyy/mm/dd') AS bd FROM EmployeeAddressTable; SELECT Format([Salary],'General Number') AS SalaryNum FROM EmployeeStatisticsTable; It returns a string containing an expression formatted according to instructions in the expression. Format Explanation General Date Displays date based on your system settings Long Date Displays date based on your system's long date setting Medium Date Displays date based on your system's medium date setting Short Date Displays date based on your system's short date setting Long Time Displays time based on your system's long time setting Medium Time Displays time based on your system's medium time setting Short Time Displays time based on your system's short time setting General Number Displays a number without thousand separators. Currency Displays thousand separators as well as two decimal places. Fixed Displays at least one digit to the left of the decimal place and two digits to the right of the decimal place. Standard Displays the thousand separators, at least one digit to the left of the decimal place, and two digits to the right of the decimal place. Percent Displays a percent value - that is, a number multiplied by 100 with a percent sign. Displays two digits to the right of the decimal place. Scientific Scientific notation. Yes/No Displays No if the number is 0. Displays Yes if the number is not 0. True/False Displays True if the number is 0. Displays False if the number is not 0. On/Off Displays Off if the number is 0. Displays On is the number is not 0. SELECT SellerID, BuyerID, Item, IIf([Price]>400,[Price]*1.05,[Price]*1.15) AS Total FROM Antiques Format: IIf ( expression, truepart, falsepart ) SELECT * FROM tblLearner WHERE isnull(address) is same as: SELECT * FROM tblLearner WHERE address is null SELECT LCase([ItemDesired]) AS small FROM Orders To get all in small or capital letters SELECT Left([ItemDesired],3) AS FirstLetters FROM Orders It returns the leftmost n characters of a string. Format: Left ( string, length ) LEN MAX SELECT Len([ItemDesired]) AS NumChars FROM Orders It returns the length of the specified string. Select SellerID, Max(Price) as MaxPrice From Antiques Group by SellerID It returns the maximum of a set of values in a select query. MID SELECT Mid([ItemDesired],2,5) AS middle FROM Orders It returns a string containing a specified number of characters from a string . Format: Mid( (string, start [, length]) ) MIN MONTH vs MONTHNAME Select SellerID, Min(Price) as MinPrice From Antiques Group by SellerID It returns the minimum of a set of values in a select query. Month gives the number and monthName the name, e.g. SELECT Month(Birthdate) as monthBD from Orders Answer: 1 SELECT MonthName(Month(Birthdate)) as monthBD from Orders Answer: January RIGHT RND ROUND SQR SUM WEEKDAY vs DAY vs WEEKDAYNAME Nested SQL SELECT in INSERT SELECT Right([ItemDesired],3) AS LastLetters FROM Orders It returns the rightmost n characters of a string. Format: Right ( string, length ) It allows you to generate a random number (integer value). You can specify the random number to be a value between 2 user-specified numbers. The syntax for the Rnd function in MS Access is: Int ((upperbound - lowerbound + 1) * Rnd + lowerbound) upperbound The highest value that the random number can be. lowerbound The lowest value that the random number can be. Example Int ((6 - 1 + 1) * Rnd + 1) Result: random number between 1 and 6 Int ((200 - 150 + 1) * Rnd + 150) Result: random number between 150 and 200 Int ((999 - 100 + 1) * Rnd + 100) Result: random number between 100 and 999 The problem is that the value of the random number is visited once, and repeated throughout the query execution. However, if you’d like a random number unique to each record, here’s how to do it: You need an ID or some other AutoNumber field. There must be a reference to the value of ID. Because this value changes on every record’s fetch, the random number re-computes dynamically throughout the execution of the query. Example: Int ((6 - 1 + 1) * Rnd(ID) + 1) It will give the SAME random numbers every time you run it, UNLESS you type Randomize in a query and run it before running this query. When you run the RANDOMIZE in a query it gives a mistake that you can ignore. SELECT Round(Avg(Price),2) AS Profit FROM Orders It returns a number rounded to a specified number of decimal places SELECT Sqr([BuyerId]) AS SquerRoot FROM Antiques It returns the square root of a number Select SellerID, Sum(Price) as TotalSum From Antiques Group by SellerID Having Sum(Price)>57 It returns the sum of a set of values. SELECT Day(Birthdate) as dayBD from Orders Answer: 27, e.g. 27 January 2016 SELECT Weekday(day(Birthdate)) as dayBD from Orders Answer: 4 SELECT Weekdayname(Weekday(day(Birthdate))) as dayBD from Orders Answer: Wednesday SELECT * From Orders Where Price > (SELECT AVG(Price) from Orders) Sometimes you have to add the words ALL or SOME or ANY, e.g. SELECT UnitPrice FROM PRODUCTS WHERE UnitPrice < ALL (SELECT TOP 5 UnitPrice FROM Products ORDER BY UnitPrice DESC) ORDER BY UnitPrice DESC General Format (with columns specified): INSERT INTO departments (department_id,department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700); Copying Rows from another Table: You can use the INSERT statement to add rows to a table where the values are derived from existing tables. In place of the VALUES clause, you use a subquery. In this way, you can easily copy large volumes of data from one table to another with one single SELECT statement. The number of columns and their data types in the column list of the INSERT clause must match the number of values and their data types in the subquery. Examples: Populate the SALES_REPS table with data from the EMPLOYEES table where the job_id is REP. INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, name, salary, commission_pct FROM employees WHERE job_id LIKE '*REP*'; OR if some are from existing and other’s new, e.g. a new employee that gets a new id (automatically generated, i.e. not part of the SQL), but the same details as others from the same department INSERT INTO sales_reps(name, salary, commission_pct) SELECT “John Smith”, salary, commission_pct FROM employees WHERE job_id LIKE '*REP*';