Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Thursday, July 11, 2013

Notes PostgreSQL


Installation Notes
--prefix=/usr/local/pgsql # default


1)  ./configure --prefix=/home/chee/usr/pgsql --with-perl --with-python --enable-odbc --enable-syslog

2) gmake

3) gmake check

4) gmake install

5) add path to LD_LIBRARY_PATH, PATH, MANPATH

6) create user "postgresq" -> adduser postgres

7) Install database directory:
   cd /home/chee/usr/pgsql/
   mkdir data
   chown postgres /home/chee/usr/pgsql/data    # change owner of "data" to "postgres"
   su - postgres                               # install db as user "postgres"
   ~/usr/pgsql/bin/initdb -D /home/chee/usr/pgsql/data   # installing db
   
8) Starting the database:

/home/chee/usr/pgsql/bin/postmaster -D /home/chee/usr/pgsql/data
or
    /home/chee/usr/pgsql/bin/pg_ctl -D /home/chee/usr/pgsql/data -l logfile start

     This will start the server in the foreground. To put the server in the
     background use something like

#### does not seem to work
     nohup /home/chee/usr/pgsql/bin/postmaster -D /home/chee/pgsql/data \
         </dev/null >>server.log 2>&1 </dev/null &

     To stop a server running in the background you can type

###     kill `cat /usr/local/pgsql/data/postmaster.pid`
     kill `cat /usr/local/pgsql/data/postmaster.pid`

     In order to allow TCP/IP connections (rather than only Unix domain
     socket ones) you need to pass the "-i" option to "postmaster".

  4. Create a database:

     createdb testdb

     Then enter

     psql testdb

     to connect to that database. At the prompt you can enter SQL commands
     and start experimenting.






     --with-includes=DIRECTORIES

          "DIRECTORIES" is a colon-separated list of directories that will
          be added to the list the compiler searches for header files. If
          you have optional packages (such as GNU Readline) installed in a
          non-standard location, you have to use this option and probably
          also the corresponding "--with-libraries" option.

          Example: --with-includes=/opt/gnu/include:/usr/sup/include.

     --with-libraries=DIRECTORIES

          "DIRECTORIES" is a colon-separated list of directories to search
          for libraries. You will probably have to use this option (and the
          corresponding "--with-includes" option) if you have packages
          installed in non-standard locations.

          Example: --with-libraries=/opt/gnu/lib:/usr/sup/lib.

     --with-pgport=NUMBER

          Set "NUMBER" as the default port number for server and clients.
          The default is 5432. The port can always be changed later on, but
          if you specify it here then both server and clients will have the
          same default compiled in, which can be very convenient. Usually
          the only good reason to select a non-default value is if you
          intend to run multiple PostgreSQL servers on the same machine.

     --with-CXX

          Build the C++ interface library.

     --with-perl

          Build the Perl interface module. The Perl interface will be
          installed at the usual place for Perl modules (typically under
          "/usr/lib/perl"), so you must have root access to perform the
          installation step (see step 4). You need to have Perl 5 installed
          to use this option.

     --with-python

          Build the Python interface module. You need to have root access to
          be able to install the Python module at its default place
          ("/usr/lib/pythonx.y"). To be able to use this option, you must
          have Python installed and your system needs to support shared
          libraries. If you instead want to build a new complete interpreter
          binary, you will have to do it manually.

     --with-tcl

          Builds components that require Tcl/Tk, which are libpgtcl,
          pgtclsh, pgtksh, PgAccess, and PL/Tcl. But see below about
          "--without-tk".

     --without-tk

          If you specify "--with-tcl" and this option, then programs that
          require Tk (pgtksh and PgAccess) will be excluded.

     --with-tclconfig=DIRECTORY, --with-tkconfig=DIRECTORY

          Tcl/Tk installs the files "tclConfig.sh" and "tkConfig.sh", which
          contain configuration information needed to build modules
          interfacing to Tcl or Tk. These files are normally found
          automatically at their well-known locations, but if you want to
          use a different version of Tcl or Tk you can specify the directory
          in which to find them.

     --enable-odbc

          Build the ODBC driver. By default, the driver will be independent
          of a driver manager. To work better with a driver manager already
          installed on your system, use one of the following options in
          addition to this one. More information can be found in the
          Programmer's Guide.

     --with-iodbc

          Build the ODBC driver for use with iODBC.

     --with-unixodbc

          Build the ODBC driver for use with unixODBC.

     --with-odbcinst=DIRECTORY

          Specifies the directory where the ODBC driver will expect its
          "odbcinst.ini" configuration file. The default is
          "/usr/local/pgsql/etc" or whatever you specified as
          "--sysconfdir". It should be arranged that the driver reads the
          same file as the driver manager.

          If either the option "--with-iodbc" or the option
          "--with-unixodbc" is used, this option will be ignored because in
          that case the driver manager handles the location of the
          configuration file.

     --with-java

          Build the JDBC driver and associated Java packages. This option
          requires Ant to be installed (as well as a JDK, of course). Refer
          to the JDBC driver documentation in the Programmer's Guide for
          more information.

     --with-krb4[=DIRECTORY], --with-krb5[=DIRECTORY]

          Build with support for Kerberos authentication. You can use either
          Kerberos version 4 or 5, but not both. The "DIRECTORY" argument
          specifies the root directory of the Kerberos installation;
          "/usr/athena" is assumed as default. If the relevant header files
          and libraries are not under a common parent directory, then you
          must use the "--with-includes" and "--with-libraries" options in
          addition to this option. If, on the other hand, the required files
          are in a location that is searched by default (e.g., "/usr/lib"),
          then you can leave off the argument.

          "configure" will check for the required header files and libraries
          to make sure that your Kerberos installation is sufficient before
          proceeding.

     --with-krb-srvnam=NAME

          The name of the Kerberos service principal. postgres is the
          default. There's probably no reason to change this.

     --with-openssl[=DIRECTORY]

          Build with support for SSL (encrypted) connections. This requires
          the OpenSSL package to be installed. The "DIRECTORY" argument
          specifies the root directory of the OpenSSL installation; the
          default is "/usr/local/ssl".

          "configure" will check for the required header files and libraries
          to make sure that your OpenSSL installation is sufficient before
          proceeding.

     --with-pam

          Build with PAM (Pluggable Authentication Modules) support.

     --enable-syslog

          Enables the PostgreSQL server to use the syslog logging facility.
          (Using this option does not mean that you must log with syslog or
          even that it will be done by default, it simply makes it possible
          to turn that option on at run time.)

     --enable-debug

          Compiles all programs and libraries with debugging symbols. This
          means that you can run the programs through a debugger to analyze
          problems. This enlarges the size of the installed executables
          considerably, and on non-GCC compilers it usually also disables
          compiler optimization, causing slowdowns. However, having the
          symbols available is extremely helpful for dealing with any
          problems that may arise. Currently, this option is recommended for
          production installations only if you use GCC. But you should
          always have it on if you are doing development work or running a
          beta version.

     --enable-cassert

          Enables assertion checks in the server, which test for many "can't
          happen" conditions. This is invaluable for code development
          purposes, but the tests slow things down a little. Also, having
          the tests turned on won't necessarily enhance the stability of
          your server! The assertion checks are not categorized for
          severity, and so what might be a relatively harmless bug will
          still lead to server restarts if it triggers an assertion failure.
          Currently, this option is not recommended for production use, but
          you should have it on for development work or when running a beta
          version.

     --enable-depend

          Enables automatic dependency tracking. With this option, the
          makefiles are set up so that all affected object files will be
          rebuilt when any header file is changed. This is useful if you are
          doing development work, but is just wasted overhead if you intend
          only to compile once and install. At present, this option will
          work only if you use GCC.

     If you prefer a C or C++ compiler different from the one "configure"
     picks then you can set the environment variables CC or CXX,
     respectively, to the program of your choice. Similarly, you can
     override the default compiler flags with the CFLAGS and CXXFLAGS
     variables. For example:

     env CC=/opt/bin/gcc CFLAGS='-O2 -pipe' ./configure


###############################################
Starting a session (assume database "testdb" already exist)
   =>psql testdb

Information:
   =>select current_user;
   =>select current_timestamp;

System:
- case INSENSITIVE
- use ";" to end statement
- prompt "=>" is first prompt, "->" are subsequent prompts, ended with ";"


PHP connection:
1. In data/postgresql.conf
      tcpip_socket=true

2. In data/pg_hba.conf:
      # TYPE     DATABASE    IP_ADDRESS     MASK               AUTH_TYPE  AUTH_ARGUMENT

local      all                                           trust
host       all         127.0.0.1      255.255.255.255    trust
host       all         129.94.176.241 255.255.255.255    trust

3. Run "postmaster -i ........"




User:
1. Creating user from Unix shell:   createuser demouser1
2. Creating user from within pgsql:
   a) start PostgreSQL by:  psql
   b) creating new user: CREATE USER demouser2;
3. Changing user permissions:
        test=> ALTER USER demouser2 CREATEDB;
        test=> CREATE GROUP demogroup WITH USER demouser1, demouser2;
        test=> CREATE TABLE grouptest (col INTEGER);
        test=> GRANT ALL on grouptest TO GROUP demogroup;
        test=> \connect test demouser2
        You are now connected to database test as user demouser2.
        test=> \q

Commands:
;                        to end sentence
\g                       (go) to end sentence
\p                       (print) to display buffer contents
\r                       (reset) to erase or reset buffer
\q                       (quit)to exit pgsql
\l                       (list) to list databases in the system
\d                       to list all Tables in the database
                         ORACLE: select * from cat
\d TABLE                 to list all attributes or colums of the TABLE
\connect <DB> <USER>     connect to database DB as user USER

\i FILE                  to read/run SQL script
\o FILE                  to print results to file called FILE
\o                       to switch output back to STDOUT
\t                       to switch off column titles when displaying query results
\z                       to see ownership of db objects


Data Types   PostgresQL    Oracle      Description
----------------------------------------------------------------------
char string  CHAR(n)       CHAR(n)     blank-padded string, fixed storage
             VARCHAR(n)    VARCHAR2(n) variable storage length
----------------------------------------------------------------------
number       INTEGER                   integer, +/-2billion range
             FLOAT                     float pt, 15-digit precision
             NUMERIC(p,d)  NUMBER(p,d) user-defined precision and decimal
----------------------------------------------------------------------
date/time    DATE          DATE          date
             TIME                        time
             TIMESTAMP                   date and time

DATE - use
"show datestyle" or
"SET DATESTYLE TO 'ISO'|'POSTGRES'|'SQL'|'US'|'NONEUROPEAN'|'EUROPEAN'|'GERMAN'"

***** PostgresQL has even more data types than listed here.




***************
Creating table
CREATE TABLE friend (
                     firstname CHAR(15),
                      lastname  CHAR(20)   );

Inserting Values
INSERT INTO friend VALUES (
        'Cindy',
        'Anderson'    );

Selecting Records
SELECT <attribute/column> FROM <relation/table>;
SELECT * FROM friend;
SELECT <attribute/column> FROM <relation/table> WHERE <attribute> <OP> <value>;
SELECT <attrib> FROM <relation> ORDER BY <attrib1, attrib2> DESC;
<OP> = {=, <, >, ........}
use "\t" in psql to omit the column titles.


Delete records
DELETE FROM <relation>;       !!! delete all rows
DELETE FROM <relation> WHERE <attribute> <OP> <value>;


Update
UPDATE <relation>  SET <attribute> = <value> WHERE <attribute> = <value>;


Destroying table
DROP TABLE <relation>


Input / Output data using COPY
NULL is displayed as  \N
COPY table TO 'file' USING DELIMITERS '|';
COPY table FROM 'file';
COPY table FROM stdin;
COPY table TO stdout;
COPY table TO 'file' WITH NULL AS '\';          NULL as blanks
COPY table FROM 'file' WITH NULL AS '\';        NULL as blanks
COPY table FROM 'file' WITH NULL AS '?';        NULL as '?'

Copying across network
- use stdin, stdout or pgsql's \copy command

Sunday, February 14, 2010

How to use Merge in SQLServer 2008

This is a description of how to use the SQL Server 2008 feature - "Merge ... Using".

The operation here involves 2 Tables.
Tsrc = Source table where the information is downloaded from.
Trgt = Local table, typically our working version of the table.


The real life situation / scenario is that from time to time, Tsrc will be changed. At different times, we need to update our local table Trgt such that it reflects the source table (Tsrc) but also require to keep the records of old data.


The process involve a merge between the local and the source tables and the results are kept in the local table.
- The source table is unchanged.
- The local table has extra columns BASE_RUN_I and Clatest.
- Column BASE_RUN_I keeps track of the runs each time we perform a download and merge from the source database.
- Column Clatest keeps track of whether the record is the latest record or has been modified.


Define the two tables as follows:
CREATE TABLE [dbo].[Tsrc](
[C1] [int] NOT NULL,
[C2] [nchar](3) NULL,
[C3] [date] NOT NULL
) ON [PRIMARY]



CREATE TABLE [dbo].[Trgt](
[BASE_RUN_I] [int] NOT NULL, -- a run id
[C1] [int] NOT NULL,
[C2] [nchar](3) NULL,
[C3] [date] NOT NULL,
[Clatest] [int] NOT NULL -- is 0 if record is old, is 1 if record is the new/latest.
) ON [PRIMARY]


The Merge process actually occurs in a temporary table-space facilitated by a VIEW. The view can be defined as follows:

CREATE VIEW [dbo].[VTemp]
AS
SELECT BASE_RUN_I, C1, C2, C3, Clatest
FROM dbo.Trgt
WHERE (Clatest = 1)



There is also a temporary table called UpdateRecords which are created from the Merge process. This table contain the meta-data about which records have changed from the Merge process.

The description below is based on the complete Insert Into .. Select .. Merge operations.
The results from the merge operation, which return multiple records, are inserted into the local table Trgt.

Overall Description:
1. Get desired data from source table. Lines 5-13
2. Merge results from step 1 with local table. Lines 4-26. In this process there are three conditions and one post processing.
3. Within the merge operation, the 3 conditions are: i) when there is a match between source and local table conditions; ii) when record is in source but not in local iii) when record is in local but not in source. Within each of these conditions, there are operations that perform a change to the local table.
4. At the end of the merge operation, as a post process, meta-data can be outputted as a temporary table (eg UpdateRecords table).
5. From the temporary table of the Merge operation, select the records which have been replaced. Lines 2-28.
6. From step 6, insert the results back into the local table Trgt. Line 1.


Detailed Description: From the innnermost loop ......
Lines 8-10: Downloads records from Source table, with relevant conditions.
Lines 5-13: The downloaded source data is aliased as src(C1,C2,C3), to be used as the source of the Merge operation
Line 14: Specify conditions for merge.
Lines 15-17: Columns C1, C3 are info to identify records between source and local tables. When identified, then if the C2 info is different between source and local tables, or either one is null, then update C2 info and Base_Run_I identifier.
Lines 18-21: When records in source but not in local, then put data from source to local.
Lines 22-24: When records in local but not in source, then mark the record as obsolete by setting Clatest = 0.
Line 4: This merging process does not merged with the local table, but rather it merges with the sub-table of the local table, where the entries are the most current ones, ie Clatest = 1.
Line 26: Outputs the merge process including special value $action which has values 'UPDATE', 'INSERT', etc. And also Deleted and Inserted values.
Lines 04-26: The complete merge process. At the end of this, both view and its real data in the local table Trgt, would have been changed. It also outputs meta data including inserted information and deleted information.

Eg. Deleted.BASE_RUN_I AS prevBaseRunId, Deleted.C1, Deleted.C2 AS prevCQC, Deleted.C3, 0 AS prevClatest, Inserted.Clatest AS newClatest

Lines 27: The results from the merge process, acting like a temporary table for the Select command.
Lines 02-28: Selection of META results from the merge process to extract information of updated records. Note in the actual merge process of lines 04-26, for the case when a row is being updated, the Trgt table and view will hold the updated record only, the previous record is not kept. Example

Before merge: {BASE_RUN_I, C1, C2, C3, Clatest} = {23, 1, 2, 3, 1} -> old
After merge: {BASE_RUN_I, C1, C2, C3, Clatest} = {24, 1, 5, 3, 1} -> new

There are no extra rows added to keep track of the old record. However at the end of the merge process, there are Meta-fields available which keep track of the old record as: Deleted.BASE_RUN_I, Deleted.C1, Deleted.C2, Deleted.C3, Deleted.Clatest. In this example:
{Deleted.BASE_RUN_I, Deleted.C1, Deleted.C2, Deleted.C3, Deleted.Clatest} = {23, 1, 2, 3, 1}

In Line 26, these Meta-fields are selective extracted into the temporary table called UpdateRecords. Also a new field called prevClatest is created with values 0 to indicate old results.

Finally, in line 2, the select statement chooses {prevBaseRunId, C1, prevCQC, C3, prevClatest}, in the example this is:
{23, 1, 2, 3, 0}

And ultimately in Line 1, the results from Line 2 which represent replaced records, are added back into the local table Trgt.

Lines 01-28: Add records to local table Trgt, those records selected by Lines 02-28 which are in fact old records which have been updated and use prevClatest into the Clatest column.


------------------------------------
01 INSERT INTO Trgt
02 SELECT prevBaseRunId, C1, prevCQC, C3, prevClatest
03 FROM (
04 MERGE VTemp AS trgt
05 USING (SELECT crr.C1, crr.C2, crr.C3
06 FROM Tsrc AS crr
07 INNER JOIN (
08 SELECT DISTINCT C1
09 FROM Tsrc
10 WHERE C1>2 AND C2 in ('A','A0')
11 ) as c
12 ON c.C1 = crr.C1
13 ) AS src (C1, C2, C3)
14 ON trgt.C1 = src.C1 AND trgt.C3 = src.C3
15 WHEN MATCHED AND ((trgt.C2 != src.C2) OR (ISNULL(trgt.C2,'') != ISNULL(src.C2,'')))
16 -- record exists for given client and rating date, but rating value has changed so update record
17 THEN UPDATE SET C2 = src.C2, BASE_RUN_I = @BASE_RUN_I
18 WHEN NOT MATCHED BY TARGET
19 -- records in source that are not in target, insert new records in target
20 THEN INSERT (BASE_RUN_I, C1, C2, C3, Clatest)
21 VALUES (@BASE_RUN_I, src.C1, src.C2, src.C3, 1)
22 WHEN NOT MATCHED BY SOURCE
23 -- records in target that are no longer in source, expire target records
24 THEN UPDATE SET Clatest = 0
25 -- record exists for given client and rating date, but rating value has changed so insert the previous record with old rating
26 OUTPUT $action, Deleted.BASE_RUN_I AS prevBaseRunId, Deleted.C1, Deleted.C2 AS prevCQC, Deleted.C3, 0 AS prevClatest, Inserted.Clatest AS newClatest)
27 AS UpdatedRecords (Action, prevBaseRunId, C1, prevCQC, C3, prevClatest, newClatest)
28 WHERE Action = 'UPDATE' AND newClatest = 1

Monday, May 04, 2009

Notes SQL





Contents
=========
DB Termininology
Select Statement
Update Statement
Insert Statement
Delete Statement
Examples
Exporting DB
Replace Text / String
GROUP BY, DISTINCT
INNER JOIN ... ON
LEFT, RIGHT, FULL JOIN
DB tasks
COUNT


DB Termininology
=================
DDL Data Definition Language
CREATE
DROP
ALTER
TRUNCATE




DML Data Manipulation Language
SELECT
UPDATE
INSERT
DELETE


DCS Data Control Statements
GRANT
CONNECT
REVOKE
COMMIT
ROLLBACK
LOCK TABLE
AUDIT


Other Commands
desc
select count(*) from table    - count the total records for the table.


SQLPlus
select * from cat         - list all tables


Select Statement
=================
SELECT [columns] FROM [tables] WHERE [search_condition] LIKE [pattern] ORDER BY [order_expression ASC|DSC]
           *                           col1='blah'             'B%'
        col1,col2                       col1 < '123'           '%B'
                             cond1 AND cond2          '[abcd]%'
           
        [Agg func]


... where
[Agg func] = aggregate function = Avg(), Sum(), Min(), Max(), Count(*), Count(DISTINCT col)

WHERE logical operators
=  <  >  >=  <=  <> NOT  !=
BETWEEN foo AND bar
IN
    The IN operator implements comparison to a list of values, that is, it tests whether a value matches any value in a list of values. IN comparisons have the following general format:
           value-1 [NOT] IN ( value-2 [, value-3] ... )
     This comparison tests if value-1 matches value-2 or matches value-3, and so on. It is equivalent to the following logical predicate:
           value-1 = value-2 [ OR value-1 = value-3 ] ...
     or if NOT is included:
           NOT (value-1 = value-2 [ OR value-1 = value-3 ] ...)
     For example,
           SELECT name FROM s WHERE city IN ('Rome','Paris')




Update Statement
=================
UPDATE [table] SET [set_expression] WHERE [search_condition]

Insert Statement
==================
INSERT INTO [table] ([column list]) VALUES ([value list])
                    (col1, col2)            ('one', 'two', 3)

INSERT INTO [table] ([column list])  SELECT "column3", "column4", ...  FROM "table2"

INSERT INTO [table] ([column list])
SELECT "column3", "column4", ...
FROM ( MERGE ................. OUTPUT ....... )
AS [dummy table name] ([column list])



Delete Statement
=================
DELETE FROM [table] WHERE [search condition]


Examples
=========
select menuid from menu where foodid not in (select foodid from food);
--- check if there are any rows in menu with a foodid that is not in the food table. Note that
menuid and foodid are the primary keys for the menu and food table respectively.

    Compare values in one table but not the other.
select  distinct B.ex  from B
where B.ex not in (select  distinct F.ex from F)

Exporting DB
=============
When exporting a DB or table within a DB, we can use the Export function in HeidiSQL.

Note: Need to remove "MySQL specific comments" such as "/*«number» ... */" when uploading
to phpAdmin.

In the example below, need to remove "/*!32312 IF NOT EXISTS*/" or remove "/*!32312 */"

CREATE TABLE /*!32312 IF NOT EXISTS*/ `stateau` (
  `StateID` int(10) unsigned NOT NULL auto_increment,
  `Name` varchar(50) default NULL,
  `Code` varchar(3) default NULL,
  `Postcode` mediumint(8) unsigned default NULL,
  PRIMARY KEY  (`StateID`)
) TYPE=InnoDB AUTO_INCREMENT=4 /*!40100 DEFAULT CHARSET=latin1*/;

In MySQL syntax, the number in /*«number» ... */ stands for the version number.


Replace Text / String
======================
UPDATE Products_Descriptions SET ProductDescription = REPLACE(LTRIM(RTRIM(ProductDescription)), '©', '©')
update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);


GROUP BY, DISTINCT
====================

O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the customers.

SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer

The result-set will look like this:

Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000


Using GROUP BY by more than one column. When grouping, all columns that appear in the SELECT column list, that are not aggregated (used along with one of the SQL aggregate functions), have to appear in the GROUP BY clause too. For example:
      SELECT CustomerName, OrderDate, SUM(OrderPrice) FROM Sales
      GROUP BY CustomerName, OrderDate




DISTINCT cannot be used to get the results above.
Note that the following statements are the same:
   SELECT DISTINCT(Customers), OrderPrice FROM Orders
   SELECT DISTINCT Customers, OrderPrice FROM Orders
   SELECT Customers, OrderPrice FROM Orders

Their results are:
1000 Hansen
1600 Nilsen
700 Hansen
300 Hansen
2000 Jensen
100 Nilsen

Distinct always applies across all column names listed in the SELECT statement.



INNER JOIN ... ON
===================
The "Persons" table:

P_Id LastName FirstName Address City
1 Hansen   Ola   Timoteivn 10 Sandnes
2 Svendson Tove  Borgvn    23 Sandnes
3 Pettersen Kari Storgt    20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Now we want to list all the persons with any orders.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678

LEFT, RIGHT, FULL JOIN
========================
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.



The RIGHT JOIN keyword Return all 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.


The FULL JOIN keyword return rows when there is a match in one of the tables.

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

DB tasks
==========
   Copy table from one DB to another DB, given that the structure of the table has been created in the
   destination DB.
(MSSQL)
insert into DB2.dbo.table1
select * from DB1.dbo.table1


    List all column names in a table
(MSSQL)
SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'TableName'
SELECT Column_Name + ',' FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'TableName'

SELECT table_name=sysobjects.name,
         column_name=syscolumns.name,
         datatype=systypes.name,
         length=syscolumns.length
    FROM sysobjects
    JOIN syscolumns ON sysobjects.id = syscolumns.id
    JOIN systypes ON syscolumns.xtype=systypes.xtype
   WHERE sysobjects.xtype='U'
ORDER BY sysobjects.name,syscolumns.colid


    Select First N rows
(MSSQL)
SELECT TOP 10 name, description FROM TABLEA ORDER BY name
    The above query will return the first 10 rows sorted by name. How do I get the bottom 10 rows? Use the DESC keyword in the ORDER BY clause and it will sort it in reverse order.


    Counting the number of categories
select count(*) , ENTITY_ID
from Merge_CBA_ASBCommProp
group by ENTITY_ID

    The results are:
(name) ENTITY_ID
957240 3
830842 1
492520 2


COUNT
========
If the following code returns 15 records:
SELECT distinct a, b
FROM Tab
then to count the number for rows returned, we need:
SELECT count(*)
FROM
(
SELECT distinct a, b
FROM Tab
) AS outt
Note "AS outt" is needed for the inner results table to be ALIASED, otherwise the outer select cannot use it.