Thursday, August 22, 2013

Beginning SQL

Hit the new query button
There is a drop down directly beneath that that by default is set to Master. We will select Northwind instead.
Make sure you are specifying the correct DB. A lazy DB developer will ruin databases. Outside of MSSMS and at the top of your query you specify it like this,
use northwind

--select everything from the products table

select *
from products
--F5 will execute the query

--Comma seperate
select productname, productID

from products

GO
USE SAMPLE
GO

CREATE TABLE tblContacts(
USE SAMPLE_DB
ID INT IDENTITY NOT NULL,
FIRSTNAME
FIRSTNAME VARCHAR(100),
LASTNAME VARCHAR(100))


If you were to continue on, and you only wanted to run this query, 
select productname, productID

from products|
you could highlight it before executing.

--Use brackets for space delimited names
SELECT [FULL NAME]
FROM CUSTOMER
--FROM<---CLAUSE keyword

select distinct CategoryID
from products
--district will eliminate duplicates

select CategoryID
from Categories

select SupplierID, CategoryID
from products
--This will generate redundant results

select distinct *
from products
--this does nothing because every line has a unique identifier

select distinct SupplierID, CategoryID
from products
--this will eliminate the redundancies

Select removes columns. Where removes rows. It is like a crosshair on a grid: Select specifies the Y-axis and Where specifies the X-axis

1. Select
2. From
3. Where

select *
FROM Products

WHERE UnitPrice > 30 AND UnitsInStock < 10


SELECT ProductName
FROM Products

ORDER BY ProductName
--alphabetical order

SELECT ProductName
FROM Products

ORDER BY ProductName desc
--Reversed alphabetical order

SELECT ProductName
FROM Products
ORDER BY ProductName asc
--this is assumed

/*If you do these, either the city or the country will be all jumbled up and out of order*/
SELECT ContactName, Country, City
FROM Customers
ORDER BY Country 
SELECT ContactName, Country, City
FROM Customers
ORDER BY Country
/*The way around situations like these is to do drilldowns*/
select ContactName, Country, City
FROM Customers

ORDER BY City, Country  
/*You probably would want the cities sub-alphabetized within the countries alphabetized, in which case you would change it to*/
select ContactName, Country, City
FROM Customers

ORDER BY Country, City 











No comments:

Post a Comment