Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Sunday, April 1, 2012

SQL- distinct

select distinct city, college_name from students

> so the combination of city and college should be distinct we can not have it like

select city, distinct college_name from students

but we can have it with an aggregate e.g. for each city give me the count of distinct colleges :) eh!

select city, count(distinct college_name) from students

postgres - from clause in update sql

update students set college_name = c.name from colleges c
where students.city = c.city

weired SQL but awesome isn't??!!

> In update we cannot use aliases for the update table so have to use the full name in case of ambiguous columns e.g. city

> we can have any number of from tables with aliases and have a join on the update table and also can update a value using a value from the join table

Monday, March 5, 2012

SQL: exists

Today I figured out that we can use sql "exists" in the select part of a query

e.g. select name, exists (select 1 from girls where bf_name = boys.name) has_bf from boys b

result:
name has_bf
------------
A t
B f
C t