Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing rows which have the same value in a certain column in postgresql

Tags:

sql

postgresql

I have two tables, Courses and Faculties.

  • Courses has columns: ID(primary key), description, level, instructor_id(foreign key), and semester.
  • Faculties has columns: faculty_id(primary key), name, date_of_birth, address, email, and level.

instructor_id in Courses references faculty_id in Faculties.

I'm trying to write a query which lists all the instructors who teach more than one course. As I'm new to SQL in general I'm utterly stumped as to how to go about doing this. There are rows in the Courses table with the same value for instructor_id. Thus far I've already joined the tables like this:

SELECT "Courses".description, "Faculties".name FROM "Courses" INNER JOIN 
"Faculties" ON "Courses".instructor = "Faculties".faculty_id;

But I don't know how to filter out the rows which which duplicate values under Instructor column (in other words filter the classes with the same instructor).

like image 955
Omar Kadery Avatar asked Mar 15 '15 20:03

Omar Kadery


People also ask

How do I SELECT a specific column in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.

Which one is used to put the same value in all the rows?

The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It does not remove duplicate rows between the various SELECT statements (all rows are returned). Each SELECT statement within the UNION ALL must have the same number of fields in the result sets with similar data types.

Which one of these is used to put the same value in all the rows in SQL?

The GROUP BY clause is a SQL command that is used to group rows that have the same values. The GROUP BY clause is used in the SELECT statement.


1 Answers

This is an aggregation query. If you just want the instructor id, then you can use:

select instructor_id
from courses
group by instructor_id
having count(*) > 1;

To get additional information, join in the other table.

like image 153
Gordon Linoff Avatar answered Oct 04 '22 09:10

Gordon Linoff