SQL Syntax, Query Examples and Notes

Who actually believes that SQL can be used by non-technical people?  Some links, samples, and other related stuff.

Subquery Examples

SELECT TOP 20 TheX, COUNT(TheX) AS TheY FROM (
SELECT (dateadd(dd, datediff(dd,0, LastChanged), 0)) as TheX
FROM [InventoryLocation]) AS TheSub
GROUP BY TheX
ORDER BY TheX DESC

 

Null Notes

"In SQL a null term in a calculation results in a null."

Got burned by NULL in an dynamically built "IN" criteria from a subquery... from StackOverflow: "An in statement will be parsed identically to field=val1 or field=val2 or field=val3. Putting a null in there will boil down to field=null which won't work."

SQL Server: varchar(30) - int - bigint

Variables ( SQL Server )

DECLARE @find varchar(30);  
/* Also allowed: DECLARE @find varchar(30) = 'Man%';  */ 
SET @find = 'Man%';  
SELECT p.LastName, p.FirstName, ph.PhoneNumber 
FROM Person.Person AS p  
JOIN Person.PersonPhone AS ph ON p.BusinessEntityID = ph.BusinessEntityID 
WHERE LastName LIKE @find; 

 

NOT TESTED: Clean up messy SQL: http://www.cleancss.com/sql-beautify/

 

 

 

 

UPDATE SYNTAX EXAMPLES:

UPDATE un_word set cat='female' WHERE cat like 'female%'
(This query was to clean up (trim excess spaces) from some records that had spaces after the word "female")

UPDATE monitor SET last_check=NOW(), last_result='Success' WHERE id=1;

UPDATE survey SET datagroup=2 WHERE datagroup=1

Example with join - from stackoverflow.com.

UPDATE CE
SET sJobNumber = AD.JobNumber
FROM CostEntry CE
    INNER JOIN ActiveCostDetails As AD
        ON CE.lUniqueID = AD.UniqueID
WHERE CE.SEmployeeCode = '002'  AND substring(CostCentre, 3, 1) = sCategoryCode

 

 

 

Tags: SQL, query, syntax, examples, structured query language, tsql

Related Scribbles:
  • Crystal Reports Notes
  • Databases. MySQL, SQL Server, etc.
  • MS Access Notes
  • Multi-Column vs Multiple Single Column Indexes
  • MySQL Notes
  • Notes
  • Replace String example SQL
  • Set ODBC TimeOut on Pass-Through Query in Access
  • SQL Case Example
  • SQL Group By Vs. Having
  • SQL UNION Example
  • SQL Update + Join on Combination Primary Key With Subselect
  • SQL Server


  • ID: 190
    Author:
    leonard
    Date Updated:
    2019-06-04 11:25:38
    Date Created:
    2003-11-16 18:03:21

    Edit

    Comments?
     >> Leonard Chan's Homepage  >> Scribble Web  >> SQL Syntax, Query Examples and Notes
    leonard.lotus-land.ca is hosted by Perceptus Solutions Inc.