Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to write a loop in a PL/pgSQL function in PostgreSQL 9.3 that returns a table. I used `RETURN NEXT;` with no parameters after each query in the loop, following examples I found, like:
* [plpgsql error "RETURN NEXT cannot have a parameter in function with OUT parameters" in table-returning function](https:/... | The example given may be wholly replaced with `RETURN QUERY`:
```
BEGIN
RETURN QUERY SELECT y_.y, 'hi' FROM generate_series(1,10,1) AS y_(y)
END;
```
which will be a *lot* faster.
In general you should avoid iteration wherever possible, and instead favour set-oriented operations.
Where `return next` over a loop... | What [@Craig already explained](https://stackoverflow.com/a/27665012/939860).
**Plus**, if you really need a loop, you can have this simpler / cheaper. You don't need to declare an additional record variable and assign repeatedly. Assignments are comparatively expensive in plpgsql. Assign to the `OUT` variables declar... | How to use RETURN NEXT in a PL/pgSQL function? | [
"",
"sql",
"database",
"postgresql",
"plpgsql",
"return-next",
""
] |
I have an array, "templates".
```
puts templates
```
gives me the following output:
```
{"id"=>4, "subject"=>"invoice", "body"=>"dear sirs", "description"=>"banking", "groups"=>"123", 0=>4, 1=>"invoice", 2=>"dear sirs", 3=>"banking", 4=>"123"}
```
I would like to "put" a certain element e.g. "dear sirs". I have tri... | You access `"dear sirs"` using the key that's associated with it, `"body"`:
```
puts templates["body"]
``` | If you want to get a hash value by numeric index then you can do `templates.values[index]`
e.g
`templates.values[0] => 4
templates.values[1] => "invoice"
templates.values[2] => "dear sirs"` | "putting" a certain object to the screen from inside an array | [
"",
"sql",
"ruby",
"hashtable",
""
] |
I get an error near `WHERE` clause on executing this query.
```
update AssetData set EmployeeName = ISNULL(EmployeeName,'') +@reasEmp
where ([AssetNumber] like'%" + WA_number.Text + "%')
and ID IN (SELECT ID FROM AssetData ORDER BY ID DESC
where ([AssetNumber] like'%" + WA_number.Text + "%') LIMIT 1)
```
Someone pl... | ```
and ID IN (SELECT ID FROM AssetData ORDER BY ID DESC
where ([AssetNumber] like'%" + WA_number.Text + "%') LIMIT 1)
```
The `where` should become before `ORDER BY`. Although legal, `in ( ... limit 1)` doesn't make sense because `in` should be used with a list. I recommend using `= max(ID)` instead
```
and ID = (SE... | try this
i think your are using SQL SERVER
```
update AssetData set EmployeeName = ISNULL(EmployeeName,'') +@reasEmp
where [AssetNumber] like'%" + WA_number.Text + "%'
and ID IN (SELECT TOP 1 ID FROM AssetData
where [AssetNumber] like'%" + WA_number.Text + "%'
ORDER BY ID DESC)
``` | Nested SQL query having select subquery in update statement | [
"",
"sql",
"asp.net",
"database",
""
] |
I have database with 2 tables, 1 for storing customers Id and for customer informations. The second table is ordered with key/value because I need to store undefined values.
**Table structure**
*table customers:*
```
=================
id | status
=================
```
*table customers\_info*
```
==============... | Try this:
```
SELECT ci.id_customer AS CustomerId, ci.value AS CustomerName
FROM customers_info ci
WHERE ci.key = 'name'
ORDER BY ci.id_customer;
```
Check the [**SQL FIDDLE DEMO**](http://www.sqlfiddle.com/#!2/eef5ce/2)
**OUTPUT**
```
| CUSTOMERID | CUSTOMERNAME |
|------------|--------------|
| 1 | ... | ```
DROP TABLE IF EXISTS eav_hell;
CREATE TABLE eav_hell
(id_customer INT NOT NULL
,attribute VARCHAR(12) NOT NULL
,value VARCHAR(12) NOT NULL
,PRIMARY KEY(id_customer,attribute)
);
INSERT INTO eav_hell VALUES
(1,'name','Doe'),
(1,'age',25),
(1,'city','NY'),
(2,'name','Smith');
SELECT id_customer
, MAX(CASE WH... | MySQL join multiple lines | [
"",
"mysql",
"sql",
"select",
"group-by",
"pivot",
""
] |
I am working on a database that has been made in a terrible way. I have to find an ID in a comma'd column.
The column values could be:
* 6154
* 5145,6154,4562
* 161545
My query is:
```
SELECT resource_id,filename,id FROM image WHERE other_vendors = '".$vendor_id."'
```
`$vendor_id` will be 6154
Now how do I match... | Just use build in function [find\_in\_set](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set), which search string in comma separated list:
```
SELECT resource_id,filename,id FROM image WHERE find_in_set('6154',other_vendors)
``` | I think this is the easiest method:
```
SELECT resource_id,filename,id FROM image WHERE (','+other_vendors +',') like '%,$vendor_id,%'
``` | SQL LIKE REGEXP Matching Single Value and Comma'd String | [
"",
"mysql",
"sql",
"regex",
""
] |
I have this value in my field which have 5 segment for example `100-200-300-400-500`.
How do I query to only retrieve the first 3 segment? Which mean the query result will display as `100-200-300`. | The old `SUBSTR` and `INSTR` will be faster and less CPU intensive as compared to `REGEXP`.
```
SQL> WITH DATA AS(
2 SELECT '100-200-300-400-500' str FROM dual
3 )
4 SELECT substr(str, 1, instr(str, '-', 1, 3)-1) str
5 FROM DATA
6 /
STR
-----------
100-200-300
SQL>
```
The above `SUBSTR` and `INSTR` ... | ```
((\d)+-(\d)+-(\d)+)
```
If the Position of this sequence is arbitrary, you might go for **REG**ular**EXP**ressions
```
select regexp_substr(
'Test-Me 100-200-300-400-500 AGain-Home',
'((\d)+-(\d)+-(\d)+)'
) As Result
from dual
RESULT
-----------
100... | Retrieve segment from value | [
"",
"sql",
"oracle",
"substr",
""
] |
I am trying to figure out the right code for the below logic. If there is a certain value in the first column, display the value from the second column for that specific record.
Can someone please help? Thanks.
```
CASE WHEN TableA.Column1 = 'a' THEN 'select TableA.Column2 '
WHEN TableA.Column4 = 'b' THEN 'select... | You were almost there just remove the `select` from `case statement`. Since all the values are coming from same table no need of `select` in case statement just keep `column name` it will fetch the corresponding column value.
```
SELECT CASE
WHEN Column1 = 'a' THEN Column2
WHEN Column4 = 'b' THEN Col... | Try this:
```
SELECT (CASE WHEN A.Column1 = 'a' THEN A.Column2
WHEN A.Column4 = 'b' THEN A.Column5
ELSE A.Column6
END) AS [Test]
FROM TableA A;
``` | Select statement inside CASE - SQL | [
"",
"sql",
"sql-server",
"select",
"sql-server-2012",
"case",
""
] |
I have a query like this:
```
SELECT i.*
FROM items i
WHERE i.id
IN (
SELECT c.item_id
FROM cart c
WHERE c.sessID=MY_SESSION_ID
)
```
It's working beautifully, but I need to sort items from the cart by date of purchase (cart.id) DESC.
I don't want sort in PHP. How can I sort by cart.id?
I tried:
... | Try this query:
```
SELECT i.* FROM items i LEFT OUTER JOIN cart c
ON i.id = c.item_id WHERE c.sessID=MY_SESSION_ID AND
c.item_id is not null ORDER BY c.id
``` | Change your **Sub query** to `Inner Join`. `Sub query` will not allow to you refer the columns outside of `sub query`. So change it to `Inner join`
```
SELECT i.*
FROM items i
JOIN (SELECT item_id,
id
FROM cart) C
ON i.id = c.item_id
AND c.sessID = MY_SE... | ORDER BY id IN Subquery | [
"",
"sql",
"select",
"join",
"subquery",
"sql-order-by",
""
] |
I have Data in column like below
```
ferrari motor
motor
tata motor
motor corp
hundai motor
```
So When I use this query
```
SELECT * FROM `table` WHERE MATCH(`name`) AGAINST ('%motor' IN BOOLEAN MODE) LIMIT 10
```
I get results in random order like below
```
tata motor
motor corp
ferrari motor
motor
hundai motor
... | A very simple solution would be to sort by the position of the searched string:
```
SELECT *
FROM `table`
WHERE MATCH(`name`) AGAINST ('%motor' IN BOOLEAN MODE)
ORDER BY INSTR(UPPER(`name`), UPPER('motor'))
LIMIT 10
```
This would give you
```
motor
motor corp
tata motor
hundai Motor
ferrari motor
```
or
```
mo... | USE a order by case to give special occasions special priority.
```
SELECT * FROM view_sample
WHERE ...
ORDER BY
CASE
WHEN name LIKE 'motor%' THEN 2
WHEN name LIKE '%motor%' THEN 1
ELSE 0 END,
name
```
1. everything thats starts with motor
2. everything that includes at least motor
3. everything e... | Mysql searching Column with beginning of words | [
"",
"mysql",
"sql",
""
] |
Say I have a table, called `tablex`, as follows:
```
name|year
---------
Bob | 2010
Mary| 2011
Sam | 2012
Mary| 2012
Bob | 2013
```
Names appear at most twice. I want to remove from the table only those names that are repeated and have a difference of one year (in which case I want to keep the newer year).
```
name|... | From the question is not clear if you want to SELECT (suppressing the duplicates) or actually DELETE the "duplicates". The select case:
```
SELECT a.Name, a.Year
FROM tablex AS a
WHERE NOT EXISTS (
SELECT * FROM tablex AS b
WHERE b.Name = a.Name
AND b.Year = a.Year +1
);
```
And the delete case:
```
D... | This operation deletes rows from the table where the same name with a newer year also exist:
```
delete from tablex t1 where year < (select max(year) from tablex where name = t1.name)
``` | SQL(ite) Remove (and keep some) duplicates in table | [
"",
"sql",
"sqlite",
"join",
""
] |
I hope I am able to explain what I am looking for. I have a table as follows:
```
ID | Column A| Column B
1 | 1234 | 9876
2 | 1234 | 8765
3 | 9876 | 1234
4 | 2345 | 3456
5 | 3456 | 2345
```
The rule is that For Every value of Column A = Value A and Column B = Value B, I need to hav... | The following should work:
```
SELECT * FROM TABLE1 T1
WHERE NOT EXISTS (SELECT 1 FROM TABLE1 T2
WHERE T1.ColumnA = T2.ColumnB AND
T1.ColumnB = T2.ColumnA)
``` | Use an outer self-join filtering out matches:
```
select a.*
from table1 a
left join table1 b on a.columna = b.columnb
and a.columnb = b.columna
where b.columnb is null
``` | Need to retrieve rows from table where the following condition was not satisfied column A = column B and column B = column A | [
"",
"sql",
"join",
"notin",
""
] |
I'm trying to find any tables with columns containing the word `date` somewhere in the column name.
All of my queries are either all or nothing: they return all tables in the DB, or no results at all.
When I run a query without the variable, it works, as seen here.
```
select *
from MyDB.INFORMATION_SCHEMA.COLUMNS
... | One query with cursor to loop through all the database on your server or you can explicitly loop through certain database
## Query
```
DECLARE @DB_Name SYSNAME;
DECLARE @Sql NVARCHAR(MAX)= '';
DECLARE @cur CURSOR;
SET @Cur = CURSOR FOR
SELECT name
FROM sys.sysdatabases
--WHERE name IN ('DBName1', 'DBName2', 'DBNa... | You can use what ever source of column info you prefer but the issue you are having is because of your variable declaration.
declare @temp varchar = 'date' is equivalent to
declare @temp varchar(1) = 'date' so
select @temp returns 'd' so you are getting any columns containing 'd'
when you declare your variable make s... | Find table information where part of column matches char variable | [
"",
"sql",
"sql-server",
""
] |
My end goal...`SELECT` all fields from `qry1` on rows where either the home phone, cell phone, OR work phone match `tbl2`
This is my current SQL syntax that's "failing." By failing I mean it hasn't finished executing after 10-15 minutes while the individual joins each (independently) run in a minute or two a piece.
`... | If the individual joins work fast, the composite OR condition is probably slow because it cannot use a single index whereas the individual conditions can each use a single index for the three joining conditions. Because it can't use one index, it is probably doing non-indexed sequential table scans. (You should study t... | `or` can be rather difficult for SQL optimizers. I would suggest 3 indexes and the folllowing query:
```
SELECT qry1.*
FROM qry1
WHERE EXISTS (SELECT 1 FROM tbl2 WHERE qry1.CellPhone = tbl2.CellPhone) OR
EXISTS (SELECT 1 FROM tbl2 WHERE qry1.HomePhone = tbl2.HomePhone) OR
EXISTS (SELECT 1 FROM tbl2 WHERE q... | How do I perform a JOIN if one of multiple conditions is true? | [
"",
"sql",
"ms-access",
"ms-access-2010",
""
] |
I have a Table Valued Function as following. But it is giving a error. That is saying "Msg 156, Level 15, State 1, Procedure GetOpeningByRepAcc, Line 36
Incorrect syntax near the keyword 'begin'."
But I didn't able to fix this. Any idea please?
```
create FUNCTION [dbo].[GetOpeningByRepAcc]
(
@Date datetime,@AccId i... | You have two lots of `BEGIN... END` in your function this is causing the error. Looking at your function though it can be simplified hugely, you are performing pretty much the same query 3 times, just summing different columns, two of them are:
```
SET @Topup = ( SELECT SUM(Qty)
FROM DailyItemStoc... | I think that you have one extra `end ... begin`. Please try the following version of you function:
```
create FUNCTION [dbo].[GetOpeningByRepAcc]
(
@Date datetime,@AccId int,@CenterId datetime,@ItemId int
)
RETURNS @ReturnData TABLE
(
Opening decimal(10,3),
Topup decimal(10,3),
Returnsv decimal(10,3)
)
as
begin
... | SQL Table valued function | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-function",
""
] |
I have a query that gets a count of all the tickets assigned to a team:
```
SELECT 'Application Developers' AS team, COUNT(Assignee) AS tickets
from mytable WHERE status = 'Open' AND Assignee like '%Application__bDevelopers%'
UNION ALL
SELECT 'Desktop Support' AS team, COUNT(Assignee) AS tickets
from mytable WHERE s... | You can use `HAVING` for each query:
```
SELECT 'Application Developers' AS team, COUNT(Assignee) AS tickets
from mytable WHERE
status = 'Open'
AND Assignee like '%Application__bDevelopers%'
HAVING COUNT(Assignee) <> 0
```
I'd suggest @NoDisplayName's answer because your query as it stands is quite inefficien... | Instead of using Union all between bunch of queries Change your query like this.
Use `Having clause` to filter the group's where `count <> 0`
```
SELECT CASE
WHEN Assignee LIKE '%Application__bDevelopers%' THEN 'Application Developers'
WHEN Assignee LIKE '%Desktop__bSupport%' THEN 'Desktop Support'
... | How can I exclude COUNT results which are 0? | [
"",
"sql",
"sql-server",
""
] |
I want to get the month no when I only knows month name.
(If month name January should return 1)
I tried this.
```
SELECT DATEPART(MM,'january 01 2011')
```
But here I want to pass whole date value(january 01 2011). But I only need to pass month name.
(Without using 'Case')
Is there any way to do this? | You can pass month name and append `01 2011` (or whatever other day + year you wish) to it, like this:
```
@declare monthName varchar(20);
@set monthName = 'january';
SELECT DATEPART(MM,monthName+' 01 2011')
```
or
```
SELECT MONTH(monthName+' 01 2011')
``` | you can also use `Case`
```
DECLARE @month VARCHAR(15)='mar'
SELECT CASE @month
WHEN 'Jan' THEN 1
WHEN 'feb' THEN 2
WHEN 'mar' THEN 3
WHEN 'apr' THEN 4
WHEN 'may' THEN 5
WHEN 'jun' THEN 6
WHEN 'jul' THEN 7
WHEN 'aug' THEN 8
WHEN 'sep' TH... | Get month numbe passing only month name | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Suppose I have a query stored in a variable like this (it's actually dynamically populated and more complex, but this is for demonstration purposes):
```
DECLARE @Query VARCHAR(1000) = 'SELECT * FROM dbo.MyTable'
```
Is there a way to check if the query would return any results? Something like this, but this doesn't ... | Try Executing the `Dynamic query` and use `@@RowCount` to find the existence of rows.
```
DECLARE @Query NVARCHAR(1000) = 'SELECT * FROM [dbo].[Mytable]',
@rowcnt INT
EXEC Sp_executesql @query
SELECT @rowcnt = @@ROWCOUNT
IF @rowcnt > 0
BEGIN
PRINT 'row present'
END
``` | Try this:
```
DECLARE @Query NVARCHAR(1000) = 'SELECT @C = COUNT(*) FROM dbo.MyTable'
DECLARE @Count AS INT
EXEC sp_executesql @Query, N'@C INT OUTPUT', @C=@Count OUTPUT
IF (@Count > 0)
BEGIN
END
``` | SQL "if exists..." dynamic query | [
"",
"sql",
"sql-server",
"exists",
""
] |
I need to do an aggregation of data as follows. This pertains to imports of various grades of ore along various dates. I have the following sample data and want to get cumulative data as on date per grade
```
Grade Dat Amount
----------------
A 12/1/2014 100
A 12/4/2014 ... | I guess the following is what you want:
```
select a.grade, a.dat, (select sum(amount) from table1 b
where (a.grade=b.grade) and (a.dat >= b.dat))
from table1 a
```
(Assuming there are no duplicate grade/dat rows.) | I will guess that you want to see a cumulative over time thus:
```
select grade
,dat
,amount
,sum(amount)
over (partition by grade order by dat range between UNBOUNDED PRECEDING and current row) cumulative_amount
from table1;
```
That gives me the sum of grades until the day of row in th... | aggregate query in SQL | [
"",
"sql",
"ms-access",
""
] |
I have an `UPDATE` pass through query saved in Access 2007. When I double-click on the pass through query it runs successfully. How can I get this query to run from VBA? I'd like it to run when my "splash screen" loads.
I'm currently using the following code:
`CurrentDb.Execute "Q_UPDATE_PASSTHROUGH", dbSQLPassThroug... | Use the QueryDef's `Execute` method:
```
CurrentDb.QueryDefs("Q_UPDATE_PASSTHROUGH").Execute
```
I don't think you should need to explicitly include the *dbSQLPassThrough* option here, but you can try like this if you want it:
```
CurrentDb.QueryDefs("Q_UPDATE_PASSTHROUGH").Execute dbSQLPassThrough
``` | I recently ran into the same problem. While the above mentioned `Execute` method is working for most cases, some people (me included) experiencing a `Run-time error '3001': Invalid Argument` when using the parameter *dbSQLPassThrough*. This was also addressed in the answer above me and happens even in the simplest SQL-... | Execute SQL Server Pass-Through Query From Access VBA | [
"",
"sql",
"ms-access",
"vba",
"pass-through",
""
] |
I am trying to `get max value` of a column in my query but I cant found any solution. My query is
```
SELECT pz.id,
sz.Price + cr.AddedCost AS price
FROM piz pz, crust cr, size sz
WHERE
pz.SizeID = sz.id AND
pz.CrustID = tp.id
```
Then I receive some records like the following
```
ID price
-----------... | What happens when you do this.
Change all your old style comma separated join to Inner join for better readability.
```
SELECT pz.id,
sz.Price + cr.AddedCost AS price
FROM piz pz
INNER JOIN crust cr
ON pz.CrustID = cr.id
INNER JOIN size sz
ON pz.SizeID = sz.id
WHER... | use Max function :) select MAX(column) from ... | Get record with Max value from SELECT query | [
"",
"mysql",
"sql",
"navicat",
""
] |
I'm trying to create a simple query that turns a grading/evaluation column that currently contains the values 0,1,2,3,4,5 into Terrible, Poor, Bad, Mediocre, and Good. But as you can see there are only 5 label values but 6 number values.
So the number 5 needs to display as 5, while all the other numbers will turn into... | You need an `ELSE` option to handle the cases that aren't matched. Use `TO_CHAR` to get all the values to the same datatype.
```
SELECT event_id,
trainee_id,
CASE eval
WHEN 0 THEN 'Terrible'
WHEN 1 THEN 'Bad'
WHEN 2 THEN 'Mediocre'
WHEN 3 THEN 'Fair'
... | Just use `'5'`:
```
SELECT event_id,
trainee_id,
(CASE eval
WHEN 0 THEN 'Terrible'
WHEN 1 THEN 'Bad'
WHEN 2 THEN 'Mediocre'
WHEN 3 THEN 'Fair'
WHEN 4 THEN 'Good'
WHEN 5 THEN '5'
END
)
FROM booking;
```
Alternativ... | CASE statement turning a NUMBER into a CHAR, but the ELSE to keep original NUMBER in Oracle SQL | [
"",
"sql",
"oracle",
"case",
""
] |
I'm still actively learning MS Access/sql (needs to be Office 2003 compliant). I've simplified things down as best as I can.
I have the following table (Main) comprising 2 fields (Ax and Ay) and which extends to several thousand records.
This is the primary database and requires to be searchable:
table: Main
```
Ax ... | to paraphrase a bit, users can select values for Ax & Ay and you only want to return records where both Ax & Ay are in the list of selected values or either of them could be null but not both.
now you want to add Astr for both Ax and Ay. you could use a co-related sub-query as below or you could join to Afull twice, o... | Whatever works at the end of the day, but here is an alternative, basically it selects the value for the first expression that evaluates true. if A?Str is null or less than zero it uses the zero value so that you can just add the two results together.
```
Switch(AxStr>=0, AxStr,AxStr<0,0,isnull(AxStr),0) + Switch(AySt... | Access sql display values from second table | [
"",
"sql",
"ms-access",
""
] |
How can I get the result of the current year using SQL?
I have a table that has a column date with the format `yyyy-mm-dd`.
Now, I want to do select query that only returns the current year result.
The pseudo code should be like:
```
select * from table where date is (current year dates)
```
The result should be a... | Use [`YEAR()`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_year) to get only the year of the dates you want to work with:
```
select * from table where YEAR(date) = YEAR(CURDATE())
``` | When I tried these answers on SQL server, I got an error saying curdate() was not a recognized function.
If you get the same error, using getdate() instead of curdate() should work! | SQL - Get result of current year only | [
"",
"mysql",
"sql",
"date",
""
] |
I am working with **MySQL 5.6**. I had created a table with 366 partitions to save data daywise means In a year we have maximum 366 days so I had created 366 partitions on that table. The hash partitions were managed by an integer column which stores 1 to 366 for each record.
**Report\_Summary** Table:
```
CREATE TAB... | I got the solutions for that I had changed my logic of storing **PartitionsId** column in my table. Initially I am storing **DayOfYear(reportTime)** column in **PartitionsId** column. Now I had changed that logic by storing **TO\_DAYS(reportTime)** and stored into **PartitionsId** column.
So my table structure is as b... | There are a few options that I can think of.
1. Create `case` statements that cover multi-year search criteria.
2. Create a `CalendarDays` table and use it to get the distinct list of `DayOfYear` for your `in` clause.
3. Variation of option 1 but using a `union` to search each range separately
**Option 1:** Using `ca... | MySQL: Unable to select the records from specific partitions? | [
"",
"mysql",
"sql",
"select",
"partitioning",
"find-in-set",
""
] |
i have two tables eg:
```
table1
---------------------
|id | name| isActive|
|---|-----|---------|
| 1 | dd | 1 |
| 1 | cc | 1 |
| 1 | zz | 1 |
| 1 | yy | 1 |
---------------------
table2
---------------------
|id | name| isActive|
|---|----|----------|
| 1 | ab | 1 |
| 1 | cd | ... | In your UNION, add extra columns for the columns from the other table. Then combine them using `MAX()`
```
SELECT MAX(Table1Count) AS Table1Count, MAX(Table1IsActive) AS Table1IsActive,
MAX(Table2Count) AS Table2Count, MAX(Table2IsActive) AS Table2IsActive
FROM (SELECT COUNT(*) Table1Count, table1.`isActive` Ta... | Try this:
```
SELECT (SELECT COUNT(*) FROM `table1`) AS Table1Count,
(SELECT COUNT(*) FROM `table2`) AS Table2Count;
``` | Two tables count in to two seprate columns | [
"",
"mysql",
"sql",
"select",
"count",
"subquery",
""
] |
I'm using the following query, but it gives a `NULL` row with the rest of results:
```
SELECT CASE
WHEN csuseragent LIKE '%MSIE+8.0%' or csuseragent like '%Trident%' THEN 'IE'
WHEN csuseragent LIKE '%Firefox%' THEN 'Firefox'
WHEN csuseragent LIKE '%chrome%' THEN 'chrome'
END AS Browser ,count(*) as num
FROM logs.log... | You can use a `having` clause to filter out groups:
```
SELECT CASE
WHEN csuseragent LIKE '%MSIE+8.0%' or csuseragent like '%Trident%' THEN 'IE'
WHEN csuseragent LIKE '%Firefox%' THEN 'Firefox'
WHEN csuseragent LIKE '%chrome%' THEN 'chrome'
END AS Browser ,count(*) as num
FROM logs.log
GROUP BY Browser
HAVING Browse... | Add a `WHERE Browser IS NOT NULL` clause | Mysql SELECT CASE LIKE give a NULL row | [
"",
"mysql",
"sql",
"select",
"group-by",
"case",
""
] |
I have a table (table1) :
```
| Country1 | Country2 |
Canada USA
Canada Mexico
USA Mexico
USA Canada
.
.
.
etc
```
Then I have another table (table2):
```
| Country | Date | Amount |
Canada 01-01 1.00
Canada 01-02 0.23
USA 01-01 2.67
USA 01-02 5.65
US... | The following SELECT should solve your question, or at least should give you the idea how it works.
```
SELECT t1.Country1,
t1.Country2,
(
SELECT AVG(Amount)
FROM table2 t2
WHERE t2.Country = t1.Country1 AND
EXISTS
... | This brings back the same information but in a more logical fashion, in my opinion (your expected output shows the same thing on both rows, just reversed).
```
select t2a.country as country1,
t2b.country as country2,
avg(t2b.amount) as avg_amount
from table2 t2a
join table2 t2b
on t2a.date = t2b.... | finding the average amount for each combination occurence | [
"",
"mysql",
"sql",
""
] |
In my database, I have the table: `Job`. Each job can contain tasks (one to many) - and the same task can be re-used on multiple jobs. Therefore there is a `Task` table and a `JobTask` (junction table for the many-to-many relationship). There is also the `Payment` table, that records payments received (with a `JobId` c... | For each separate `JobId`, `SUM(p.Amount)` sums up the same Amount value for every `Task` record related to a `Job` record with this `JobId`. If 6 records are related to a specific `Job`, then `SUM(p.Amount)` will calulate the amount multiplied by 6, if 7 records are related, then the amount is multiplied by 7 and so o... | Use a Sub-Select to calculate the SUM:
```
select j.JobId,
sum(t.Rate) as [TotalOwedP],
(SELECT SUM(p.Amount) FROM Payment p WHERE j.JobId=p.JobId) as [TotalReceivedP]
from Job j
left outer join JobTask jt on j.JobId=jt.JobId
left outer join Task t on jt.TaskId=t.TaskId
group by j.JobId
``` | Query SUM of value from joined table - returns multiplied result | [
"",
"sql",
"sql-server",
""
] |
I have date in column of `nchar(255)` datatype in this format
```
mm/dd/yyyy
```
Now I want to change it into
```
dd/mm/yyyy
```
I don't think that `CONVERT` help me in this as I have tried different queries like below
```
SELECT CONVERT(NCHAR(20), col1, 103) from table1
SELECT CONVERT(VARCHAR(20), col1, 103) f... | I am answering my own question.(Just in case anyone wants to know what is the solution)
There was no such problem with the query i was using. i.e.
```
select Convert(varchar(10),CONVERT(date,col1,101),103) from table1
```
The problem was with my nchar field.
It was having a special character (in my case a space) in ... | Do this in two expiicit steps. First, convert the string to a date using the 101 format (which is mm/dd/yyyy). Then explicitly convert the date back to a string using 103 (which is dd/mm/yyyy):
```
select convert(varchar(255), convert(date, datecol, 101), 103)
```
Two points. First, I don't think the result needs to ... | Selecting date in format dd/mm/yyyy from nchar column | [
"",
"sql",
"sql-server",
"t-sql",
"date",
""
] |
How can I do a constraint that will check first two values and second two values in different ranges? I have to put time in database, but i do not need a data, that's why I don't want to use DATETIME type. I need only a TIME, but as far as I know there is no TIME datatype in Oracle.
My column looks like:
```
visit_ho... | I'd probably do something like
```
CONSTRAINT check_time CHECK( to_number( substr( visit_hours, 1, 2 ) ) BETWEEN 0 AND 23 AND
to_number( substr( visit_hours, 3, 2 ) ) BETWEEN 0 AND 59 );
```
`substr( visit_hours, 1, 2 )` gives you the first two characters in the string, `substr( visit_hou... | > I have to put time in database, but i do not need a data, that's why I don't want to use DATETIME type
You don't have to worry about `date` and `time` portion separately. A `DATE` data type will have both the portions and all you need is use `to_char` with proper `format model`.
So, you can have the column as -
`v... | Oracle SQL CHECK CONSTRAINT VARCHAR | [
"",
"sql",
"oracle",
"constraints",
"varchar",
""
] |
This is probably simple, but i'm looking for the raw SQL to perform an `INNER JOIN` but only return one of the matches on the second table based on criteria.
Given two tables:
```
**TableOne**
ID Name
1 abc
2 def
**TableTwo**
ID Date
1 12/1/2014
1 12/2/2014
2 12/3/2014
2 ... | You could join the first table with an aggregate query:
```
SELECT t1.id, d
FROM TableOne t1
JOIN (SELECT id, MAX[date] AS d
FROM TableTwo
GROUP BY id) t2 ON t1.id = t2.id
``` | There are two ways to do this:
1. Using `GROUP BY` and `MAX()`:
```
SELECT one.ID,
one.Name,
MAX(two.Date)
FROM TableOne one
INNER JOIN TableTwo two on one.ID = two.ID
GROUP BY one.ID, one.Name
```
2. Using [`ROW_NUMBER()`](http://msdn.microsoft.com/en-GB/library/... | SQL: Inner Join return one row based on criteria | [
"",
"sql",
"sql-server",
"linq",
"select",
"inner-join",
""
] |
Problem statement:
There are two different methods:1-use one table and waste a column or 2-use two tables.

Method 1: one table for all information (table1), but it has the column *role* that has only one value; all other rows are empty.
Method 2: Tw... | You are talking about **`Normalization`** of course it's much better to provide a way for removing ***redundant*** and ***null*** data.
you have this existing table:
```
table1
----------------------------
role | poster_id | name
varchar(n)| int | varchar(n)
```
you can break above table into 2 **or ev... | The correct way to handle this is with a [junction table](http://www.utteraccess.com/wiki/index.php/Junction_Tables_%28Many-to-Many_Relationships%29). So the answer to your question is that neither of your proposals are the most efficient way to structure your database, you need *3* tables.
![enter image description h... | Is it more efficient to have a table with one of its columns mostly empty or make a new table and refer to it? | [
"",
"mysql",
"sql",
"database",
"optimization",
""
] |
The database has 3 tables, "items", "orders" and "orderitems" which represent an N:N relation. I need to find the orders that doesn't contain certain items. For example, I want to get all the orders that doesn't include apples, oranges, or bananas.
I've tried:
```
SELECT * FROM orders o,
LEFT JOIN orderitems oi ON o... | **UPDATED**
Please try:
```
SELECT * FROM orders o
WHERE o.order_id
NOT IN
(
SELECT oi.order_id
FROM orderitems oi
INNER JOIN items i ON oi.item_id=i.item_id
WHERE
i.name IN ('banana', 'apple', 'orange')
)
``` | Try using `group by` and `having`:
```
SELECT oi.order_id
FROM orderitems oi JOIN
items i
ON oi.item_id=i.item_id
GROUP BY oi.order_id
HAVING SUM(i.name IN ('banana', 'apple', 'orange')) = 0;
```
If you want the full order information you can can join the `orders` table back in. | sql select orders not containing certain items | [
"",
"mysql",
"sql",
""
] |
i have two table showin below
news (table name)
```
NewsId NewsDate
1 25-03-2014
2 29-03-2014
```
newsImageGal (table name)
```
newsSr newsId newsImages
1 1 images/i.jpg
2 1 images/j.jpg
3 1 images/k.jpg
4 2 images/l.jpg
5 ... | Try this.
```
SELECT a.NewsId,
a.NewsDate,
b.newsImages
FROM news a
JOIN (SELECT Row_number()OVER(partition BY newsid ORDER BY newssr) rn,
*
FROM newsImageGal) b
ON a.NewsId = b.newsId
WHERE rn = 1
```
Key here is to find the first image that got ad... | You can write as
```
;WITH CTE AS
( SELECT N.NewsId
,N.NewsDate
,NIG.newsImages
,ROW_NUMBER() OVER (PARTITION BY N.NewsId ORDER BY NIG.newsSr ASC)
AS rownum
FROM news N
JOIN newsImageGal NIG ON N.NewsId = NIG.newsId
)
SELECT NewsId,
NewsDate,
newsImages
FROM CTE
WHERE... | How to get distinct record from two tables in sql? | [
"",
"sql",
"sql-server",
""
] |
I have to set a dynamic sql query result to a variable. My sql query is :
```
DECLARE @ResultString NVARCHAR(MAX)
DECLARE @Qry NVARCHAR(MAX)
SET @Qry='SELECT Test FROM MTest22Dec WHERE ID = 1'
EXECUTE sp_executesql @Qry, N'@Result NVARCHAR(MAX) OUTPUT', @Result=@ResultString OUTPUT
PRINT @ResultString
```
Bu... | You have to set the output variable somewhere, eg.
```
SET @Qry='SELECT @Result = Test FROM MTest22Dec WHERE ID = 1'
``` | You need to assign the result of select to `variable` inside `Dynamic statement`.
Change you query like this.
```
DECLARE @Result NVARCHAR(MAX)
DECLARE @Qry NVARCHAR(MAX)
SET @Qry='SELECT @Result = Test FROM MTest22Dec WHERE ID = 1'
EXECUTE Sp_executesql @Qry, N'@Result NVARCHAR(MAX) OUTPUT', @Result OUTPUT
PRINT ... | Set EXECUTE sp_executesql result into a variable in sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
"select",
""
] |
I'm re-asking this as I'm still confused, so I've also added some edits.
With a many to many relationship, an intersection table is used to resolve this to two one-to-many relationships. My problem here is that I currently have 2 tables, "Playlist" and "song". Each song be present in many playlists, and each playlist ... | The following is what your DDL (data definition language) would look like, with some example inserts:
```
create table playlist
(
playlist_id numeric(10) not null,
playlist_name varchar(25),
constraint p_id_pk primary key (playlist_id)
);
create table songs
(
song_id numeric(10) not null,
song_name varch... | You must make make the difference between inserting songs and playlists and linking them together. First always insert the missing songs and playlists
```
INSERT INTO song (SongID, Name) VALUES (7, 'New song 1');
INSERT INTO song (SongID, Name) VALUES (8, 'New song 2');
INSERT INTO playlist (PlaylistID, Name) VALUES ... | resolution of many to many in SQL | [
"",
"sql",
"database",
"oracle",
"oracle11g",
""
] |
I am working with a program named zoho reports and trying to change names of objects in the file I uploaded. ZOHO cannot rename the example. I want to use SQL, preferably Postgres.
`phonenumber`:
```
1. 5203123333
2. 8323125547
3. 6025456564
4. 43654xxx3
```
I want them to display as:
```
1. TUCSON,AZ
2. Houston,TX... | As I understand it you want *"the same column"*, meaning the same column *name*. So use a [column alias](http://www.postgresql.org/docs/9.4/static/sql-select.html#SQL-FROM). And use a ["simple" `CASE` statement](http://www.postgresql.org/docs/current/interactive/functions-conditional.html#FUNCTIONS-CASE):
```
SELECT C... | I think it is better to have second table with "translations". First column (pattern) like `83____284` and second column (display) - the new name `Houston TX`. Then select like this:
```
SELECT t2.display FROM orig_table t1, translate_table t2 WHERE t1.phonenumber LIKE t2.pattern
```
PS: PostgreSQL is abbreviation of... | Rename items in PostgreSQL or any SQL | [
"",
"mysql",
"sql",
"postgresql",
"zoho",
""
] |
I have a table **Questions**. How can I get a count of all questions asked in a week?
More generically, how can I bucket records by the week they were created in?
```
Questions
id created_at title
----------------------------------------------------
1 2014-12-31 09:43:42 "Add things"... | In postgreSQL it's as easy as follows:
```
SELECT id, created_at, title, date_trunc('week', created_at) created_week
FROM Questions
```
If you wanted to get the # of questions per week, simply do the following:
```
SELECT date_trunc('week', created_at) created_week, COUNT(*) weekly_cnt
FROM Questions
GROUP BY d... | If the `created_at` field is already indexed, I would simply look for all rows with a `created_at` value between X and Y. That way the index can be used.
For instance, to get rows with a `created_at` value in the 3rd week of 2015, you would run:
```
select *
from questions
where created_at between '2015-01-11' and... | Get a count of records created each week in SQL | [
"",
"sql",
"ruby-on-rails",
"sqlite",
"postgresql",
"rails-activerecord",
""
] |
I have three tables Company, User , Address .
**company** has three fields
* comp\_id(PK)
* comp\_name
* user\_id(FK)
* to\_address\_id(FK)
* from\_address\_id(FK)
**Address** has fields:
* address\_id(PK)
* city
* state
User has fields
user\_id(PK),user\_name
to\_address\_id and from\_address\_id both... | Solution - you need to JOIN two times, each for every FK you're interested in:
```
SELECT s.comp_name, u.user_name, a_from.city AS city_from, a_to.city AS city_to
FROM company s
LEFT JOIN User u ON s.user_id = u.user_id
LEFT JOIN Address a_from ON s.from_address_id = a_from.address_id
LEFT JOIN Address a_to ON s.to_a... | Try the following:
```
SELECT s.comp_name
,u.user_name
,a1.city
,a2.city
FROM company s
JOIN User u ON s.user_id = u.user_id
JOIN Address a1 ON s.to_address_id = a1.address_id
JOIN Address a2 ON s.from_address_id = a2.address_id
WHERE s.user_id = 1001;
``` | How to access data from foreign key table | [
"",
"mysql",
"sql",
"database",
"select",
"join",
""
] |
I have the following two tables in mysql:
users:
```
+--------+-----------+
| userId | userName |
+--------+-----------+
| 1 | magnus |
| 2 | fabiano |
| 3 | alexander |
| 4 | veselin |
+--------+-----------+
```
games:
```
+--------+---------+---------+
| gameId | userId1 | userId2 |
+-... | You can union the two sets of data together, viz all games where Fabiano is User 1, with all games that he is in the role of User 2:
```
SELECT x.Opponent
FROM
(
SELECT u.Name AS Opponent
FROM games g
INNER JOIN users u
ON g.userId2 = u.UserId
WHERE g.UserId1 = 2 -- Fabiano
UNION
SELECT u... | Try something like:
```
SELECT `gamess`.gameId, `users`.userName
FROM users INNER JOIN
(SELECT gameId, userId2 as userId
FROM games
WHERE userId1 = 2
UNION
SELECT gameId, userId1 as userId
FROM games
WHERE userId2 = 2) AS gamess
ON `gamess`.userId = `users`.userId
``` | mysql select statement with multiple where/conditions | [
"",
"mysql",
"sql",
"select",
""
] |
Example code--SQL within SAS:
```
proc sql;
create table add_losses as
select *,
sum(bb.gross_loss) as gl format = comma15.2,
count(bb.gross_loss) as n_losses
from add_startend as aa
left join LED as bb
on (aa.process_name = bb.process_name and
aa.group_id = bb.group_code and
... | You can use Between clause for this type of condition
```
proc sql;
create table add_losses as
select aa.*, bb.gl format, bb.n_losses
from
add_startend as aa
left join
(
select aa.process_name, aa.group_id, aa.start_date, aa.end_date,
sum(bb.gross_loss) as gl format = comma15.2,
count(bb.gross_loss) as n_losses
fro... | Google for an SQL tutorial--one that covers `group by` then aggregate functions `count()` and `sum()`.
I suggest the following changes:
* When using a group by statement, explicitly list the variables you intend to to group by (instead of just using a `*`) in the SELECT statement.
* Use the between operator for date ... | Sum and count variables while executing a left join | [
"",
"sql",
"sas",
"left-join",
""
] |
```
SELECT jour
FROM reservations
WHERE id_user = 57 AND SUBSTR(jour,10) = '2014_08_14' ORDER BY jour
```
returns nothing...
I have a record in the database that matches the codition:
 | Replace `SUBSTR(jour,10)` with `SUBSTR(jour,1,10)`.
Assumption: `jour` is a `varchar` type column. If you are storing dates as `varchar`, **do not do that!**
Explanation: My solution uses the `(str,pos,len)` overload of the `SUBSTR` function. Arguments 2 and 3 are respectively, the position to start from and the leng... | [`substr`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr)'s first argument is the **position to start from**. Hence, `SUBSTR(jour,10)` returns `_AM`, and you get an empty result set. Instead, you should use the tree argument variant:
```
SELECT jour
FROM reservations
WHERE id_u... | SUBSTR returns no record (mysql) | [
"",
"mysql",
"sql",
"select",
"substr",
""
] |
I have LawfirmUser table with `FirstName`, `LastName` and `userId` columns
below is some sample data of LawfirmUser
```
FirstName LastName userId
---------- ----------- ----------
Demo test1 1
Demo test1 2
Demo test1 3
Demo test2 4... | Here is how it works
**CTE1,CTE2 etc are called Common Table Expressions in Sql Server which act as temporary tables
which will not be stored in memory and gets cleared after execution of query.**
**1.** **CTE1** - Selects the distinct values from the table. For example, if the table have same `FirstName`,`LastNam... | Use `Window Function`
```
;WITH cte
AS (SELECT *,
Row_number()OVER(PARTITION BY FirstName, LastName ORDER BY userid) rn
FROM YOURTABLE)
SELECT *
FROM cte a
WHERE EXISTS (SELECT 1
FROM cte b
WHERE a.FirstName = b.FirstName
AND a.L... | Sql Script to find similar user records | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a sql query that pulls the customers full name from the customers table based on the customer ID in the sales table and binds the info to an asp.net listview. I now want to search the records by the customers full name. I used the query below but it keeps telling me that the column "Fullname" is an invalid colum... | You cannot use the `Alias name` in the same select statement because `where` will be processed before the `select`.
Make the original query as `sub select` and use the `alias name` in `where clause`.Try this.
```
SELECT *
FROM (SELECT tbl_Sales.SaleID,
tbl_Sales.CustomerID,
(SELECT Fir... | You are not allowed to pass **ALIAS name** in **WHERE** clause instead of that you should use **JOIN**
Try this:
```
SELECT S.SaleID, S.CustomerID, (C.Firstname + ' ' + C.Lastname) AS CustomerName, S.Price
FROM tbl_Sales S
INNER JOIN tbl_Customers C ON S.CustomerID = C.CustomerID
WHERE (C.Firstname + ' ' + C.Lastnam... | Search 'AS' alias in SQL Server | [
"",
"sql",
"sql-server",
"select",
"join",
""
] |
This is using Oracle SQL.
**Edited my code, I had pasted it wrong.**
So I have two tables: class and event. Each class has a class\_id that is also present in the event table. Some classes can exist as multiple events.
* First I need to order the classes by price descending, uses only the
"class" table.
* Then I n... | perhaps you meant this:
```
SELECT x.*,
c.price,
c.class_name
FROM event x, class c
WHERE (c.price,c.class_name) IN (
SELECT price, class_name
FROM (SELECT price, class_name
FROM class
ORDER BY... | That is because it *is* ignoring the `exists`. `Exists` returns true or false (or NULL). Your clause is returning, normally, four rows. These exist. So, everything gets returned. Perhaps you want this:
```
SELECT x.*, c.price, c.class_name
FROM event x JOIN
(SELECT *
FROM (SELECT class_id, price, class_nam... | Selecting all details from Table A but only for the values that exist in Table B's top N rows | [
"",
"sql",
"oracle",
""
] |
I don't know how to title this problem. Correct me if you have better words.
I have two tables, Users and Posts.
**Users:**
```
id | username | password | ...
```
**Posts:**
```
id | author_id | title | content | ...
```
Now I want to list the "most active" users - the users who have written the most posts. And s... | This is the right solution, I think: you need the subquery to know how much post has the 10th place in your top ten. Then, you use the outer query to extract the users with almost that postcount.
```
SELECT u.username, COUNT(p.id) AS count
FROM Posts p
JOIN Users u ON u.id = p.author_id
GROUP BY p.author_id
HAVING C... | Maybe not the best solution
```
select u.username, COUNT(p.id) AS count
FROM Posts p
join Users u on u.id = p.author_id
GROUP BY p.author_id
having COUNT(p.id) in
(
SELECT COUNT(p.id)
FROM Posts p
join Users u on u.id = p.author_id
GROUP BY p.author_id
ORDER BY count DESC
LIMIT 10
)
ORD... | MySQL select top rows with same condition values | [
"",
"mysql",
"sql",
"select",
"sql-order-by",
"limit",
""
] |
I have a database that has numerous tables and I have joined two of the tables together and it is working fine but I now want to return the data that falls on half hour intervals! I have read numerous articles on this and I cant seem to get it to work. Below shows an example of my database
 function to extract the minutes from a `datetime` value:
```
SELECT
Table2.SourceID,
Table2.Value,
Table1.Name,
Table2.TimestampUTC
FROM Table2 INNER JOIN
Source ON Table1.SourceID = Table1.ID
W... | This is very easy to do with use of the [`DatePart Function`](http://msdn.microsoft.com/en-us/library/ms174420.aspx)
Add to your where clause:
```
AND DATEPART(minute, TIMESTAMP) in (0, 30)
```
To filter for a particular date add:
```
//Converting to varchar with sytle 101 strips off the time values, then we conver... | Return hourly and half hourly data | [
"",
"sql",
"sql-server-2008",
""
] |
```
deliverable_id deliverable_title deliverable_desc adviser_id passed_user deliverable_passed flag
1 SRS kogtong 1 0 0 0
2 WEBSITE Lorem ipsum... 1 0 0 0
3 system ... | You want to select all deliverables (that have a title) where no record *exists* with their deliverable\_passed ID. So use NOT EXISTS:
```
SELECT *
FROM deliverable
WHERE deliverable_title is not null
AND NOT EXISTS
(
SELECT * FROM deliverable passed
WHERE passed.deliverable_passed = deliverable.deliverable_id
)... | Does this do what you want?
```
select d.*
from deliverable d
where exists (select 1 from deliverable d2 where d2.id = d.deliverable_passed) or
exists (select 1 from deliverable d2 where d2.deliverable_passed = d.id);
``` | Comparing column to another | [
"",
"mysql",
"sql",
"select",
"join",
""
] |
I am trying to perform a count to get the total number of results in a pagination but the query is too slow **2.12s**
```
+-------+
| size |
+-------+
| 50000 |
+-------+
1 row in set (2.12 sec)
```
my count query
```
select count(appeloffre0_.ID_APPEL_OFFRE) as size
from ao.appel_offre appeloffre0_
inner joi... | Like @FuzzyTree said in his comment `exists` is faster than an inner join if it's not a 1:1 relationship because it terminates as soon as it finds 1 whereas the join will get every matching row.
But the solution is that We add `in` and not `exists` :
```
where ( appeloffre0_.ID_APPEL_OFFRE IN (select lot2_.ID_APPEL_O... | You can try:
```
select count(aa.ID_APPEL_OFFRE) as size
from (
select ID_APPEL_OFFRE, ID_ACHETEUR from ao.appel_offre appeloffre0_
inner join ao.acheteur acheteur1_
on appeloffre0_.ID_ACHETEUR=acheteur1_.ID_ACHETEUR
where appeloffre0_.DATE_OUVERTURE_PLIS>'2015-01-01'
and (appeloffre0_.CATEGORIE in ('fournitur... | Slow count query with where clause | [
"",
"mysql",
"sql",
""
] |
On posts index page I list all posts this way:
**posts\_controller.rb**
```
def index
@posts = Post.includes(:comments).paginate(:page => params[:page]).order("created_at DESC")
end
```
**index.html.erb**
```
<%= render @posts %>
```
**\_post.html.erb**
```
<%= gravatar_for post.user, size:20 %>
<%= link_to "#... | You could decrease the number of sql queries by:
* including `user` as well as `comments`, since you seem to be using that when displaying the gravatar
* changing `post.comments.count` to `post.comments.size`
While size, count, length are synonymous for arrays, for active record relations or associations they are not... | Further, you don't actually seem to be using the `comments` collection for anything other than printing the number of records. If that's indeed the case, use [counter\_cache](http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference) (`4.1.2.3`) instead of querying for the comments (the num... | optimize sql query rails | [
"",
"sql",
"ruby-on-rails",
"activerecord",
""
] |
I order the column from max repeats to min. But I only want to get the top value. The value that repeats the most.
This is code:
```
SELECT foreign_key
FROM all_person
GROUP BY foreign_key
ORDER BY COUNT(*) DESC;
```
And this is what I get:
```
foreign_key
--------------
10
9
2
... | You can do this using `ROWNUM`:
```
SELECT foreign_key FROM (
SELECT foreign_key
FROM all_person
GROUP BY foreign_key
ORDER BY COUNT(*) DESC
) WHERE rownum = 1;
```
That is the fastest way but might not work for more complex queries. | You can use ROWNUM in a where clause:
```
SELECT foreign_key
FROM
(
SELECT foreign_key
FROM all_person
GROUP BY foreign_key
ORDER BY COUNT(*) DESC
)
WHERE ROWNUM = 1;
``` | Oracle SQL Developer how to get top value | [
"",
"sql",
"oracle",
""
] |
I have question regarding sql script. I have a custom view, below is the data
```
================================================================================
ql_siteid | ql_rfqnum | ql_vendor | ql_itemnum | totalcost_option | description
============================================================================... | Assuming you have a version of Oracle 11g or later, using [ListAgg](http://docs.oracle.com/database/121/SQLRF/functions100.htm#SQLRF30030) will do the combination of the comma separated tuples for you. The rest of the string is generated by simply concatenating the components together from an intermediate table - I've ... | To get the exact output you required use the following statement: (where test\_table is your table name):
```
SELECT ql_vendor || ' = ' ||
LISTAGG( LTRIM(description||' ')||totalcost, ', ')
WITHIN GROUP (ORDER BY description)
FROM (
WITH base_cost AS (
SELECT ql_vendor, SUM(totalcost_option) sumco... | Query to Calculate totalcost based on description | [
"",
"sql",
"oracle",
""
] |
DISCLAIMER : **I Know this has been asked numerous times, but all I want is an alternative.**
The table is as below :
```
create table
Account
(Name varchar(20),
TType varchar(5),
Amount int);
insert into Account Values
('abc' ,'c', 500),
('abc', 'c', 700),
('abc', 'd', 100),
('abc', 'd', 200),
('ab' ,'c', 30... | Sure. You can use a second query with a `where` clause and a `union all`:
```
select name
, sum(Amount) balance
from Account a1
where TType when 'c'
group
by Name
union
all
select name
, sum(Amount * -1) balance
from Account a1
where TType when 'd'
group
by Name
```
Or this, using a `join` wit... | Use the ASCII code of the char and try to go from there. It is 100 for 'd' and 99 for 'c'. Untested example:
```
select Name, sum((ASCII(TType) - 100) * Amount * (-1)) + sum((ASCII(TType) - 99) * Amount * (-1)))) as balance from Account a1 group by Name.
```
I would not recommend using this method but it is a way of... | SQL query - credit , debit , balance | [
"",
"mysql",
"sql",
""
] |
Basically what I want is a working-version of the following code:
```
ALTER TABLE table_name
AUTO_INCREMENT =
(
SELECT
`AUTO_INCREMENT`
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = 'database_name'
AND TABLE_NAME = 'another_table_name'
);
```
The error:
```
1064 - You ha... | Try this:
```
SELECT `AUTO_INCREMENT` INTO @AutoInc
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'another_table_name';
SET @s:=CONCAT('ALTER TABLE `database_name`.`table_name` AUTO_INCREMENT=', @AutoInc);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
``` | Just upon quick glance, the error says it all. Syntax is incorrect
The syntax should adhere to:
```
ALTER TABLE table_name AUTO_INCREMENT=<INTEGER_VALUE>;
```
So looking at your query, remove the word "SET"
```
ALTER TABLE table_name AUTO_INCREMENT =
(
SELECT
`AUTO_INCREMENT`
FROM
INFORMATIO... | Alter AUTO_INCREMENT value by select result | [
"",
"mysql",
"sql",
"select",
"auto-increment",
"alter-table",
""
] |
I have a table like that
IVA
```
id - taxa - name - date
1 - 0.18 - normal - 1/1/2014
2 - 0 - none - 1/1/2014
3 - 0.23 - max - 1/1/2013
4 - 0.16 - normal - 1/1/2015
...
```
I have an `IVA.id` from a product and I want to know in current date what is the taxa.
So I have to query this table twice:
```... | Please try:
```
Select taxa
from IVA
where name in (Select a.name from IVA a where a.id = 1)
and date<='12/12/2015';
``` | Depends on the database engine you're using, but you may want to look up the UNION keyword for your database. | SQL join 2 queries in one from same table | [
"",
"sql",
""
] |
Parsename is working when directly using string or returning static value from the function. But when I returning select value with dot from the function. its not working. I am not able to figure out the issue.
```
CREATE TABLE [dbo].[TestTimeLine](
[UserID] [int] NOT NULL,
[Field1... | I got the Issue.
Issue is `[nchar]` datatype.
After Changing to 'Varchar' datatype. Its working fine. | Try changing the parameter 2 to 1.
```
select PARSENAME(dbo.TestFunction(),1)
```
For more details refer to:
[More Details](http://msdn.microsoft.com/en-us/library/ms188006.aspx) | parsename is not working when using string from function | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have to get horsepower field in database as integer but it contain value like below
```
330hp/@6,000
30hp/@3,000
1000hp/@6,000
```
Can Anyone suggest how can I cast this into integer?
I only need
```
330
30
1000
```
--
Cheers | ```
Select LEFT(ColumnName,CHARINDEX('h',ColumnName) - 1)
```
Read more [LEFT (Transact-SQL)](http://msdn.microsoft.com/en-GB/library/ms177601.aspx) | This will work. If there is no 'h' in the text, it will return blank. If you want to cast, go ahead. But make sure you data is validated first.
Starting from 0 is a nice trick to remove the first character 'h' instead of subtracting 1 which would give errors when no 'h' exists
```
DECLARE @t table(col varchar(20))
in... | SQL cast a string value | [
"",
"sql",
"sql-server",
"database",
""
] |
There's a poorly designed table in my database which contains some information I need to extract. Supose I have the following query:
```
SELECT
(SELECT I FROM X WHERE X.A = FOO AND X.B = KEY),
(SELECT J FROM X WHERE X.A = BAR AND X.B = KEY),
(SELECT K FROM X WHERE X.A = BAZ AND X.B = KEY)
```
I need to ex... | Use **CASE** statement to validate conditions
Try this:
```
SELECT X.B,
MAX(CASE WHEN X.A = FOO THEN I ELSE '' END) AS I,
MAX(CASE WHEN X.A = BAR THEN J ELSE '' END) AS J,
MAX(CASE WHEN X.A = BAZ THEN K ELSE '' END) AS K,
MAX(CASE WHEN X.A = QUX THEN L ELSE '' END) AS L,
MAX(CA... | This can be done in 2 ways : -
```
select i, j , k , l , m, n
from x
where i in (select i from x where x.a = 'FOO' or x.B = 'KEY') and
j in (select j from x where x.b = 'BAR' or x.B = 'KEY') and
k in (select k from x where x.c = 'BAZ' or x.B = 'KEY')
```
or the other way is :
```
select (select count(i) from x wh... | Subquery with multiple columns | [
"",
"sql",
"sql-server",
"select",
"group-by",
"where-clause",
""
] |
I have some data for example in the following format
Score data range is from 1 to 100
Following is data from table "ProductScore" for example
attaching a pic and result required format

I am a bit new to SQL
I think it's simple to write query. | You can do this with `CASE`:
```
;with cte AS (SELECT CASE WHEN Score <= 10 THEN '01: 1-10'
WHEN Score <= 20 THEN '02: 11-20'
....
ELSE '10: 91-100'
END AS Ranges
,ProductCode
FROM Produ... | As your interval are fixed width, you can use the Oracle's nice function [`WIDTH_BUCKET`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions214.htm) to achieve the desired result:
```
SELECT (wb-1)*10+1 || '-' || wb*10 "DataRange" , COUNT(*) FROM (
SELECT WIDTH_BUCKET("Score",1,100,10) wb
-- ^^^... | how to count number of rows in a data range? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
i want to select items that have minimum twu value for each tid seperately...my table name is reorganised
```
tid items times twu
1 A 7 942
1 D 5 633
1 H 2 1020
2 S 4 551
3 F 4 871
3 B 2 641
4 M 1 665
4 N ... | you can get your desired result by joining your existing subquery and the original table itself. This solution works in all rdbms.
```
SELECT a.*
FROM Reorganised a
INNER JOIN
(
select TID,min(twu)as TWU
from REORGANISED
group by tid
) b ON a.TID = b.T... | ```
WITH CTE AS (
SELECT tid,items,times,twu,
ROW_NUMBER() OVER (PARTITION BY tid ORDER BY twu DESC) rn
FROM REORGANISED
)
SELECT * FROM CTE WHERE rn=1
``` | How to select varchar column based on int min() function in SQL | [
"",
"sql",
"sql-server",
"visual-studio",
""
] |
I produce a CSV file but cannot figure out the proper date format.
I am aware of the MSDN site codes for datetime conversions:
<http://msdn.microsoft.com/en-us/library/ms187928.aspx>
It seems there is no code to convert my datetime into this format:
MM/DD/YYYY HH:MMAM
e.g.:
12/28/2014 4:33AM
How do you achieve such ... | ```
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) +
RIGHT(CONVERT(VARCHAR, GETDATE(), 100), 7)
``` | This is what you can use and is probably the most straightforward:
```
SELECT
RIGHT('0' + cast(month(dateColumn) AS NVARCHAR(2)), 2) + '/' -- generate the day
+ RIGHT('0' + cast(day(dateColumn) AS NVARCHAR(2)), 2) + '/' -- generate the month
+ cast(year(dateColumn) AS NVARCHAR(4)) + ' ' -- ... | SQL server 2008 date conversion formats | [
"",
"sql",
"sql-server-2008",
"date",
""
] |
I have two tables:
First table: **f** *(a,b,c,d are the columns)*
```
a | b | c | d
1 | 2 | 3 | 4
5 | 6 | 7 | 8
9 | 10 | 11 | 12
13 | 14 | 15 | 16
```
Second table: **s** *(a,b,c,d are the columns)*
```
a | b | c | d
5 | 6 | c | d
9 | 10 | c | d
20 | 5 | c | d... | You could use a `DELETE`/`LEFT JOIN`, which in MySQL would look like;
```
DELETE f
FROM f
LEFT JOIN s
ON f.a = s.a AND f.b = s.b
WHERE s.a IS NULL
```
If there is no row that matches between f and s, s.a will be NULL in the result and the corresponding row in f will therefore be deleted.
[An SQLfiddle to test wi... | You can do what you want without the join on the subquery:
```
DELETE FROM f
WHERE NOT EXISTS (SELECT 1 FROM s on f.a = s.a and f.b = s.b) ;
``` | DELETE if NOT EXIST | [
"",
"mysql",
"sql",
""
] |
I'm somewhat new to SQL so I hope this doesn't come off as a dumb question. I am trying to create a scheduling program where the table is as such:
```
event_id worker_id date shift_type
1 1 2014-01-01 Labour Day Shift
2 1 2014-01-02 Labour Night Shif... | You want `on duplicate key` update. But first, you need a unique index on `worker_id` and `date`:
```
create unique index idx_table_worker_date on table(worker_id, date);
insert into table(worker_id, date, shift_type)
values (@worker_id, @date, @shift_type)
on duplicate key update shift_type = values(shift_ty... | Since the worker\_id and date in combination are unique, you can rely on the INSERT to throw a duplicate error:
```
INSERT INTO table (event_id, worker_id, date, shift_type)
VALUES (1, 1, @date, @shift)
ON DUPLICATE KEY UPDATE event_id=1, shift_type=values(shift_type);
```
See [INSERT ... ON DUPLICATE KEY](... | SQL - UPDATE or INSERT by checking two columns | [
"",
"mysql",
"sql",
"database",
""
] |
I have two tables, People, and Vehicles. Vehicles belongs to people. Im trying to check if a person does not have a vehicle. I was attempting to do this by joining People and Vehicles, and displaying the persons ID that is NOT IN Vehicles.person\_id.
This is returning nothing, and has me wondering if there is somethin... | Use left join to figure out the persons with no vehicles
```
Select distinct People.id
From People
LEFT JOIN Vehicles on People.id=Vehicles.person_id
where Vehicles.person_id is NULL
``` | `NOT IN` can have [issues with `NULL` values](http://www.postgresql.org/docs/9.3/static/functions-subquery.html#FUNCTIONS-SUBQUERY-NOTIN), and should probably be avoided for [performance reasons](http://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/) if the subquery is very large.
... | Correct way to use "NOT IN" Postgres | [
"",
"sql",
"postgresql",
""
] |
I want to check if a specific View exists before querying it. I use dynamic SQL to create the query:
```
DECLARE @sqlCommand varchar(1000)
DECLARE @viewName varchar(1000)
DECLARE @otherDB varchar(1000)
SET @sqlCommand = 'IF EXISTS(SELECT 1 FROM ' + @otherDB + '.sys.views WHERE name=''' + @viewName + ''')
BEGIN
SELECT... | Check for the existence of the view *outside* the dynamic SQL. You are trying to prevent the compile-time error of the view not existing in the `select`. There is no issue with the `if`:
```
IF EXISTS(SELECT 1 FROM sys.views WHERE name = @viewName)
BEGIN
SET @sqlCommand = 'SELECT * FROM ' + @viewName
EXEC(@sql... | What version of SQL Server are you using? I only have SQL Server 2014 available to test with, but the T-SQL below works for both missing and not missing views. I wonder whether the fact that you are checking for existence of the view in otherdb.sys.views but are not qualifying otherdb when selecting from the view is to... | Check if View exists before querying it | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
\*None of other available answers solved my problem
I have a table t like this
```
id,cc,count
'1','HN','22'
'1','US','18'
'1','VN','1'
'2','DK','2'
'2','US','256'
'3','SK','1'
'3','US','66310'
'4','UA','2'
'4','US','263'
'6','FR','7'
'6','US','84'
'9','BR','3'
```
I want to get the rows for ids with maximum count,... | Remove `CC` column from `group by`. Try this.
```
SELECT t.* FROM t
JOIN (
SELECT
t.id
,max(t.count) as max_slash24_count
FROM t
group by t.id
) highest
ON t.count = highest.max_slash24_count
and t.id= highest.id
``` | Try this:
```
create table t (id varchar(10), cc varchar(10), count varchar(10))
insert into t (id,cc,count) values ('1','HN','22');
insert into t (id,cc,count) values ('1','US','18');
insert into t (id,cc,count) values ('1','VN','1');
insert into t (id,cc,count) values ('2','DK','2');
insert into t (id,cc,count) val... | How to select a row with maximum value for a column in MySQL? | [
"",
"mysql",
"sql",
"select",
"max",
""
] |
I don't know even how to start addressing this issue, any assistance will be appreciated:
My goal is to generate a table (dynamically) that return dates that are working shift.
Settings:
* I have a pattern as follow 7 days on duty 7 days off duty and it goes on...
* I can determine the start date that the shift star... | As you mentioned you need to use `Recursive CTE`. Try this.
```
DECLARE @Startdate DATE= '01/01/2015',
@enddate DATE = '01/31/2015',
@Patterndays INT=7;
WITH cte
AS (SELECT CONVERT(DATE, @Startdate) [dates],
1 AS id,
CONVER... | I would use a table of numbers.
<http://web.archive.org/web/20150411042510/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html>
<http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1>
[This article](http://sqlperformance.com/2013/01/t-sql-queries/generate-... | Generating shift pattern in SQL | [
"",
"sql",
"sql-server",
"with-statement",
""
] |
I have a table which links customer ID's to a sale ID. Multiple customers can be linked the same sale ID, however the first customer should be the Main customer with Type 'M'. All other customers should be type Other ('O').
```
Cust_ID Sale_ID Cust_Type
1 123 'M'
2 123 'O'
3 124 ... | So, the problem is that a `sales_id` can have more than one `M` value and you want to detect this. I would approach this by using a window function to count those values:
```
select t.*
from (select t.*,
sum(case when cust_type = 'M' then 1 else 0 end) over (partition by sales_id) as NumMs
from tabl... | Is this what you mean? This can be achieved using a window function.
```
CREATE TABLE temp(
Cust_ID INT,
Sale_ID INT,
Cust_Type VARCHAR(1)
)
INSERT INTO temp VALUES
(1, 123, 'M'),
(2, 123, 'M'),
(3, 124, 'M'),
(4, 125, 'M'),
(5, 125, 'O'),
(6, 125, 'O');
WITH CTE AS(
SELECT *, cc = COUNT(*) OVER(PART... | Find records that belong to the same identifier, check for multiple occurences of value in column | [
"",
"sql",
"sql-server",
""
] |
I have a PostgreSQL database that stores users in a `users` table and conversations they take part in a `conversation` table. Since each user can take part in multiple conversations and each conversation can involve multiple users, I have a `conversation_user` linking table to track which users are participating in eac... | This is a case of **relational division**. We have assembled an arsenal of techniques under this related question:
* [How to filter SQL results in a has-many-through relation](https://stackoverflow.com/questions/7364969/how-to-filter-sql-results-in-a-has-many-through-relation/7774879)
The special difficulty is to exc... | if you just want confirmation.
```
select conversation_id
from conversation_users
group by conversation_id
having bool_and ( user_id in (3,32))
and count(*) = 2;
```
if you want full details,
you can use a window function and a CTE like this:
```
with a as (
select *
,not bool_and( user_... | Find rows that have same value in one column and other values in another column? | [
"",
"sql",
"postgresql",
"relational-division",
""
] |
I'm trying to set up a pagination using SQL. I want 3 results per page and here is what I have done :
```
SELECT mot_cle.* FROM mot_cle
ORDER BY hits DESC LIMIT 3 OFFSET 0; --Page 1
SELECT mot_cle.* FROM mot_cle
ORDER BY hits DESC LIMIT 3 OFFSET 3; --Page 2
SELECT mot_cle.* FROM mot_cle
ORDER BY hits DESC LIMIT... | The problem here is that the rows all have a hit count of `1`, therefore their position when using `ORDER BY hits` is non-deterministic. And since you execute a new query each time you access a page, the rows will be "scrambled" anew.
To keep your pages consistent, you could also order by their id:
```
SELECT mot_cle... | `LIMIT` basically "aborts" the query once enough matching rows have been found. E.g. if you have `LIMIT 2`, then as soon as two rows which match the `join`/`where` clauses are found, the rest of the query goes away and you get those two rows.
But if you have an `ORDER BY` in there, then the ENTIRE matching result set ... | Strange results using order by and limit | [
"",
"mysql",
"sql",
"select",
"sql-order-by",
"sql-limit",
""
] |
I'm using an SSIS package to update my contents daily basis. There are thousands of contents which have different Moderation ID's and I want to calculate top ten categories FOR EACH Moderation ID. Before I realized that I should calculate it for each ModerationId, I used this query to get the Contents to be updated:
`... | Use `Window Function` to get the to calculate top ten `categories` for `Moderation ID`. Try this.
```
SELECT moderationid,
category,
total
FROM (SELECT Row_number() OVER (partition BY moderationid
ORDER BY Count(contentseqnum)) Rn,
moderationid,
ca... | Try this:
```
SELECT TOP(10) ModerationId, Category, COUNT(ContentSeqNum) OVER(PARTITION BY ModerationId ORDER BY ModerationId) AS Total
FROM Content
WHERE Category IS NOT NULL
ORDER BY Total DESC
``` | Calculating Top Ten Categories in SSIS | [
"",
"sql",
"sql-server",
"ssis",
""
] |
I'm using MySQL workbench and I am trying to create a table consist of foreign key using SQL Query. I am having problem with the Foreign part.
```
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int foreign key references employee_profile(eID)
)
``` | Your syntax is wrong. Try:
```
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (keyname) references employee_profile(eID)
)
```
For more information see the [mysql documentation](http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html) | ```
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (eID) references employee_profile(eID)
)
```
### [SQLFiddle demo](http://sqlfiddle.com/#!2/ab184/1) | Foreign Key Unexpected | [
"",
"mysql",
"sql",
"foreign-keys",
"create-table",
""
] |
I have a big table which has 700 millions of rows and dozens of columns. I need it to carry out a left join operation as the left table.
However, since it is so large, the time consumption is beyond affordable. So I'd like to split into few smaller tables and carry out the task in multiprocessing manner.
I know there... | Using `CTE` and `row_number()`
```
;WITH cte_tbl AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY [First Name]) AS RowNumber
FROM your_table
)
SELECT * FROM cte_tbl
WHERE RowNumber < 100
```
You can fetch records for any range. | Use [fetch-offset](http://technet.microsoft.com/en-us/library/gg699618%28v=sql.110%29.aspx) if you need certain number of rows using sql-script.
like this:
```
SELECT First Name + ' ' + Last Name FROM big_table ORDER BY First Name OFFSET 15 ROWS;
SELECT First Name + ' ' + Last Name FROM big_table ORDER BY First Name... | Get certain number of rows from a table | [
"",
"sql",
"sql-server",
""
] |
Let Suppose we have two variables in sql
```
DECLARE @str1 nvarchar(max) = 'FirstName,MiddleName,LastName'
DECLARE @str2 nvarchar(max) = 'John,,Adams'
```
Now you can see that value after first comma is empty in second variable if this case occur i want to remove the same entry from string .
```
-- Expected Result W... | Use `Replace`. Try this.
```
DECLARE @str1 NVARCHAR(max) = 'FirstName,MiddleName,LastName'
DECLARE @str2 NVARCHAR(max) = 'John,,Adams'
SELECT Parsename(Replace(Replace(@str2, ',,', ',abc,'), ',', '.'), 3)
+ ','
+ Parsename(Replace(Replace(@str2, ',,', ',abc,'), ',', '.'), 1)
SELECT Parsename(Replace(Re... | OK this works regardless the number of commas or the number of missing values. It uses a number or tally table which I've included for simplicity of this example:
```
;WITH Tally (Number) AS
(
-- 1000 rows
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0... | Remove comma if value after comma is empty in sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have three fields Category, Date, and ID. I need to retrieve data that does not belong under certain ID. Here is an example of my query:
```
SELECT Category, Date, ID
FROM table
WHERE ID NOT IN('1','2','3')
AND Date = '01/06/2015'
```
After running this query I should only get records that do not have any ID meanin... | Try this. NULL values cannot not be equated to anything else.
```
SELECT Category, Date, ID
FROM table
WHERE (ID NOT IN('1','2','3') OR ID IS NULL)
AND Date = '01/06/2015'
``` | Others have already shown how to fix this, so let me try to explain *why* this happens.
```
WHERE ID NOT IN('1','2','3')
```
is equivalent to
```
WHERE ID <> '1' AND ID <> '2' AND ID <> '3'
```
Since `NULL <> anything` yields UNKNOWN, your expression yields UNKNOWN and the record in question is not returned.
See t... | Unable to retrieve NULL data | [
"",
"sql",
"sql-server",
""
] |
How to select all data from first table and if in second table row1 == row1 in first table then I need to insert rows from second table to result with LEFT JOIN.
first\_table:
```
id row1 some_data
1 2 test
2 3 test2
```
second\_table:
```
id row1 some_data
1 4 test
2 ... | The following LEFT OUTER JOIN should give the desired result. It is important use an alias tables (t1, t2) to designate.
```
SELECT t1.id, t1.row1, t1.some_data, t2.id, t2.row1, t2.some_data
FROM first_table t1
LEFT JOIN second_table t2
ON t1.row1 = t2.row2
ORDER BY t1.id;
``` | this is how we can put left join
```
SELECT *
FROM first_table As c
LEFT JOIN second_table AS o ON c.row1 = o.row1
```
you can learn more about left join [here](http://www.mysqltutorial.org/mysql-left-join.aspx). | Select data from two tables with LEFT JOIN | [
"",
"mysql",
"sql",
""
] |
I want to return the rows in the Base table that have an inventory over a certain count.
Something like this, but having difficulties...
```
SELECT b
FROM Base b, Inventory i
WHERE COUNT(b.brand = i.brand) > 2
```
This should be returned:
```
brand | model |
----------------
ford | T |
chevy | X |
```
... | From your query, It looks like you're trying to do a join, and then a count.
Something like:
```
SELECT *
FROM Base b
INNER JOIN Inventory I
ON (b.brand = i.brand)
GROUP BY i.brand
HAVING COUNT(i.brand) > 2
```
---
An alternative (that I could think of), would be to use a nested select:
```
SELECT *
FROM Base
WHE... | Use `group by` and `having` clause to filter the `brand` having `count >2` Try this.
```
select * from base b where exists(SELECT 1
FROM Inventory i
where b.brand=i.brand
group by brand
having COUNT(1) > 2 )
``` | SQL count across two tables | [
"",
"sql",
""
] |
Here is an (simplified) example of DB I have (sorry for the ulgy format, I don't know how to write tables):
```
Name | Num
John | 1
John | 3
John | 4
Dany | 2
Andy | 5
Andy | 5
```
I want to count how many people have more at least two different Numbers.
For instance, here, only john, because he has `1`,... | Try this.
```
select count(name) from table group by name having count(distinct num)>1
``` | Try this:
```
SELECT A.Name, COUNT(DISTINCT A.Num) cnt
FROM tableA
GROUP BY A.Name
HAVING cnt >= 2;
``` | Count entries that have different values in other column | [
"",
"sql",
"select",
"count",
"group-by",
"having",
""
] |
I have a table that contains a list of datetimes.
I'd like to find the longest amount of time between consecutive datetimes ie., find the largest distance between any two datetime entries that fall next to each other on a timeline. Think about it like a "longest streak" - the longest time from one reset to the next on... | This query will compute time differences between successive rows and display the largest one -- the length of the winning streak. If you need the whole row, you'll need Gordon's query.
```
SELECT MAX(diff)
FROM (
SELECT TIMEDIFF(datetime,@prev) AS diff,
(@prev:=datetime) AS datetime
... | You can calculate the next datetime using a correlated subquery and then find the biggest by sorting:
```
select r.*
from (select r.*,
(select datetime
from resets r2
where r2.datetime > r.datetime
order by datetime
limit 1
) as next_dat... | MySQL - Find the largest time difference between consecutive datetimes | [
"",
"mysql",
"sql",
"datetime",
""
] |
I'm trying to execute next SQL statement (SQL Server 2008 Profile)
```
DECLARE @fun int;
SET @fun = 40;
select cast(@fun as varchar(10)) + 'hello'
```
and SQLFiddle gives me the error: `Must declare the scalar variable @fun`
Where I'm wrong?

<ht... | I think the semicolons are introducing the problem here.
As described here: <http://www.sql-server-helper.com/error-messages/msg-137.aspx> and here: [SQL Server - Variable declared but still says "Must declare the scalar variable"](https://stackoverflow.com/questions/13750548/sql-server-variable-declared-but-still-say... | You need to select the [Go] from last dropdown.
[](https://i.stack.imgur.com/pcMBN.png) | SQLFiddle: must declare the scalar variable error | [
"",
"sql",
"sqlfiddle",
""
] |
Not sure what functions to call, but transpose is the closest thing I can think of.
I have a table in BigQuery that is configured like this:

but I want to query a table that is configured like this:
`
See:
* <https://medium.com/@hoffa/how-to-unpivot-multiple-columns-into-tidy-pairs-with-sql-and-bigquery-d9d0e74ce675>
I created a public persistent UDF. If you have a table `a`, you can give the whole row to the UDF for it to be unpivotted:
```
SELECT geo_type, region, transpor... | **Update 2021:**
A new [UNPIVOT](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#unpivot_operator) operator has been introduced into BigQuery.
Before UNPIVOT is used to rotate Q1, Q2, Q3, Q4 into sales and quarter columns:
| product | Q1 | Q2 | Q3 | Q4 |
| --- | --- | --- | --- | --- |
| K... | How to unpivot in BigQuery? | [
"",
"sql",
"google-bigquery",
"transpose",
"unpivot",
""
] |
I want to group by 2 columns my first table is:
**Users**
```
ID Name Surname
1 joe New
2 Ala Bla
3 Cat Kra
4 Zoo Fles
5 Kat Glo
```
**Work:**
```
ID BOSSID1 BOSSID2
1 1 2
2 2 3
3 2 1
4 2 5
5 3 5
```
And I want to see all Bosses in table "Work".
for example:
```
... | Try this:
```
SELECT DISTINCT u.* FROM USERS u INNER JOIN WORK w
ON (u.id = w.bossid1 OR u.id = w.bossid2)
``` | Try this:
```
select id, concat(name, ' ', surname) from
(
select id, name, surname from users
where id in
(
select distinct bossid1 from work
) OR id in
(
select distinct bossid2 from work
)
)
``` | Oracle Db Group By Two Columns | [
"",
"mysql",
"sql",
"database",
"oracle",
""
] |
I have a query that will result in a customer bill being created on our SSRS 2008 R2 server. The SQL Server instance is also 2008 R2. The query is large and I don't want to post the entire thing for security reasons, etc.
What I need to do with the example data below, is to remove the two rows with 73.19 and -73.19 fr... | Most AR/billing systems treat "credit memos" (the negative amount) similar to cash, in which case the -73.19 would get applied to the 73.19 `LineBalance` the same as if the customer had paid that amount, resulting in a $0 balance.
**OPTION 1:**
Do you handle cash receipts and applications in this sytem? If so, you ma... | I would add a field that would contain explicit flag telling you that a certain charge was a mistake/reversal of a mistake and then it is trivial to filter out such rows. Doing it on the fly could make your reports rather slow.
But, to solve the given problem as is we can do like this. The solution assumes that `SysIn... | Remove Rows That Sum Zero For A Given Key | [
"",
"sql",
"sql-server",
""
] |
I am have a table with name Scripts which contains data of modified procedures, functions and tables.
```
CREATE TABLE #Scripts
(
ID NUMERIC (18) IDENTITY NOT NULL,
[Date] DATETIME NULL,
DatabaseName VARCHAR (50) NULL,
Name VARCHAR (100) NULL,
Type ... | try this:
```
select distinct sc.action,sc.ID from (
SELECT MAX(ID) OVER(PARTITION BY NAME ) rn,* FROM #Scripts
)d join #Scripts sc
on d.rn=sc.ID
order by sc.ID
```
**OUTPUT**
```
action ID
Deleted 3
Updated 5
Created 6
``` | ```
;WITH LatestChanges AS
(
SELECT S.[ID], S.[Date], S.[DatabaseName], S.[Name], S.[Type], S.[Action], S.[Description],
S.[ModifiedBy], S.[AddedTimestamp], S.[UpdateTimestamp],
[RowNum] = ROW_NUMBER() OVER (PARTITION BY S.[Name] ORDER BY S.[ID] DESC)
FROM [#Scripts] S
)
SELECT *
FR... | Got Error in Retrieving results using group by and order by in SQL server 2008 | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"select",
""
] |
I would like to cap VARCHAR to 255 on a few columns so that I can add an index.
```
alter table striker modify contacts varchar(255)
```
When I try to run the above command I get
```
Error Code: 1265. Data truncated for column 'contacts' at row 331 38.969 sec
```
Is there a way to force truncation of the column s... | You can manually truncate the column at 255 characters:
```
UPDATE striker
SET contacts = SUBSTR (contacts, 1, 255);
```
Now, that you know that no value is longer than 255 characters, you perform the `alter table` statement you have in the OP safely. | Why bother truncating the column? Just create the index with a length specifier for the column. Here is an example:
```
create index idx_striker_contacts on striker(contacts(255))
```
You can do this for multiple columns. | Force Truncation on VARCHAR modification? | [
"",
"mysql",
"sql",
"ddl",
"alter-table",
""
] |
I am having the following mysql table
```
id status
------------
1 available
2 hold
3 available
4 so-hold
5 so-hold
6 hold
7 hold
8 available
```
When I use `GROUP BY` on `STATUS` coloumn I got the following :
```
count(id) status
---------------------
3 available
3 hold
2 ... | You can use `CASE` statement
```
select
count(id),
case when status = 'so-hold'
then 'hold'
else status
end as status_col
from inventory_master
group by status_col
```
[`DEMO`](http://www.sqlfiddle.com/#!2/94df2/4) | Try replacing "so-" with empty string and then try your query as below:
```
SELECT newStatus, COUNT(*)
FROM
(SELECT REPLACE(status, 'so-', '') as newStatus
FROM MYTABLE) AS tab
GROUP BY newStatus
``` | count of id on status coloumn with sum of particular rows count using GROUP BY IN MYSQL | [
"",
"mysql",
"sql",
"group-by",
"aggregate-functions",
""
] |
In a MySQL table i have a field, containing this value for a given record : "1908,2315,2316"
Here is my sql Query :
```
SELECT * FROM mytable WHERE 2316 IN (myfield)
```
I got 0 results!
I tried this :
```
SELECT * FROM mytable WHERE 2315 IN (myfield)
```
Still 0 results
And then i tried this :
```
SELECT * FRO... | You appear to be storing comma delimited values in a field. This is bad, bad, bad. You should be using a junction table, with one row per value.
But, sometimes you are stuck with data in a particular structure. If so, MySQL provides the `find_in_set()` functions.
```
SELECT *
FROM mytable
WHERE find_in_set(2316, myfi... | You can't use `IN()` over comma separated list of no.s its better to normalize your structure first for now you can use `find_in_set` to find results matching with comma separated string
```
SELECT * FROM mytable WHERE find_in_set('1908',myfield) > 0
``` | MySQL In clause not giving the right result | [
"",
"mysql",
"sql",
""
] |
I have a Firebird table like this:
```
CREATE TABLE events (
event VARCHAR(6) NOT NULL
CHECK (event IN ('deploy', 'revert', 'fail')),
change_id CHAR(40) NOT NULL,
change VARCHAR(512) NOT NULL
);
```
Now I need to add another value to the `IN()` list in the CHECK constrain... | You need to drop and the re-create the check constraint.
As you didn't specify a name for your constraint, Firebird created one, so you first need to find that name:
```
select trim(cc.rdb$constraint_name), trg.rdb$trigger_source
from rdb$relation_constraints rc
join rdb$check_constraints cc on rc.rdb$constraint_n... | Here's how to do it dynamically:
```
SET AUTOddl OFF;
SET TERM ^;
EXECUTE BLOCK AS
DECLARE trig VARCHAR(64);
BEGIN
SELECT TRIM(cc.rdb$constraint_name)
FROM rdb$relation_constraints rc
JOIN rdb$check_constraints cc ON rc.rdb$constraint_name = cc.rdb$constraint_name
JOIN rdb$triggers trg ... | How do I alter a CHECK constraint on Firebird? | [
"",
"sql",
"triggers",
"constraints",
"firebird",
""
] |
I have query :
```
UPDATE SDM_KARYAWAN
SET (ID_DIVISI,ID_UNIT_KERJA,ID_JABATAN) =
(
SELECT ID_DIVISI,ID_UNIT_KERJA,ID_JABATAN FROM
(
SELECT TO_CHAR(TGL_SK,'YYYYMMDD') URUT,ID_DIVISI,ID_UNIT_KERJA,ID_JABATAN
FROM SDM_KARYAWAN_JABATAN
WHERE ID_KARYAWAN = '0081005'
ORDER BY UR... | This will work. Please check.
```
UPDATE SDM_KARYAWAN
SET (ID_DIVISI,
ID_UNIT_KERJA,
ID_JABATAN) =
(SELECT ID_DIVISI, ID_UNIT_KERJA, ID_JABATAN
FROM ( SELECT TO_CHAR (TGL_SK,'YYYYMMDD')
URUT,
ID_DIVISI,
ID_UNIT_KERJA,
... | try this:
```
UPDATE
(SELECT
Table1.Col1 as OLD1, Table2.Col1 as NEW1
Table1.Col2 as OLD2, Table2.Col2 as NEW2
FROM Table1
INNER JOIN Table2
-- ON Some Join Conditions
) t
SET t.OLD1 = t.NEW1,
SET t.OLD2 = t.NEW2
``` | update multiple columns in oracle | [
"",
"sql",
"oracle",
""
] |
I use the simple query below to output a list of partIDs based on a modelID that we get from a printout on a sheet of paper.
We've always just used one modelId at a time like this:
```
SELECT gm.partId, 343432346 as modelId
FROM dbo.systemMemberTable sm
WHERE gm.partID NOT IN (SELECT partID FROM systemsPartT... | ```
SELECT gm.partId, T.number as modelId
FROM ( values (4),(9),(16),(25)
) as T(number)
CROSS JOIN dbo.systemMemberTable sm
WHERE gm.partID NOT IN (SELECT partID FROM systemsPartTable)
```
op said getting an error but this is the test that runs for me
```
SELECT T.number as [modelID]
,[main].[name] ... | `insert` model ids into a table variable and then do the `join` with this table variable
Also use `not exists` instead of `not in` as not in doesn't work if there are `null` values in the parts table.
```
declare @modelIds table
(
model_id int
)
insert into @modelIds values (343432346) , (123456)
```
your select wo... | Query for a group of IDs | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm having some trouble building a query that will group my items into monthly ranges according to whenever they exist in a month or not. I'm using PostgreSQL.
For example I have a table with data as this:
```
Name Period(text)
Ana 2010/09
Ana 2010/10
Ana 2010/11
Ana 2010/12
Ana 2011/01
Ana ... | This is an aggregation problem, but with a twist -- you need the define the groups of adjacent months for each name.
Assuming that the month never appears more than once for a given name, you can do this by assigning a "month" number to each period and subtracting a sequential number. The values will be a constant for... | I don't know if there is an easier way (there probably is) but I can't think of one right now:
```
with parts as (
select name,
to_date(replace(period,'/',''), 'yyyymm') as period
from names
), flagged as (
select name,
period,
case
when lag(period,1, (period - interval ... | SQL query for grouping monthly period ranges | [
"",
"sql",
"postgresql",
""
] |
I have two tables and I want to find different counts of rows after join them. My tables are:


I want to select user's name and (I) the number of books that a user has (by ignoring status) and (II) ... | ```
SELECT tu.name,
Count(ts.id),
Sum(CASE
WHEN status = 1 THEN 1
ELSE 0
END)
FROM tblUsers tu
INNER JOIN tblStatus ts
ON ts.id = tu.id
WHERE tu.name LIKE '%doe%'
GROUP BY tu.id
``` | u mean like this ?
SELECT nom,count(b.id\_user),SUM(b.status) FROM user u,booking b WHERE u.id=b.id\_user GROUP BY u.id
GROUP BY is your friend ;) | Select multiple count in MySQL query with different where statements | [
"",
"mysql",
"sql",
"join",
"count",
""
] |
I currently have 2 tables, vaccination and vaccination\_type which can be joined using vaccine\_id attribute.
vaccination is basically the joining many-to-many table between vaccination\_type and patient. It has 3 attributes: vaccine\_id, registration\_no and date. Vaccination\_type has vaccine\_id, vaccine\_name.
I ... | If you want the information for one registration, then that should be your base table. Then you want to get all vaccination types for that registration. Finally join onto the vaccination table to get the date it was administered, or NULL if that person never got it:
```
SELECT
registrations.registration_no,
vaccin... | Use **LEFT JOIN** it join both tables.
Try this:
```
SELECT VT.vaccine_id, VT.vaccine_name, V.registration_no
FROM Vaccination_type VT
LEFT JOIN vaccination V ON VT.vaccine_id = V.vaccine_id;
``` | How to select all joined rows from 2 tables including null | [
"",
"mysql",
"sql",
"select",
"join",
"left-join",
""
] |
I'm building a Node.js app that needs to query a Redshift database (based on postgres 8.0.2) using CTEs. Unfortunately, the SQL query builders I've looked at thus far ([node-sql](https://github.com/brianc/node-sql), [knex.js](http://knexjs.org) and sequelize) don't seem to support common table expressions (CTEs).
I ha... | I was able to use common table expressions (CTEs) with [knex.js](http://knexjs.org/) and it was pretty easy.
Assuming you're using socket.io along with knex.js,
**knex-example.js**:
```
function knexExample (io, knex) {
io.on('connection', function (socket) {
var this_cte = knex('this_table').select('this_colu... | [knex.js](http://knexjs.org/) now supports WITH clauses:
```
knex.with('with_alias', (qb) => {
qb.select('*').from('books').where('author', 'Test')
}).select('*').from('with_alias')
```
Outputs:
```
with "with_alias" as (select * from "books" where "author" = 'Test') select * from "with_alias"
``` | Node-based SQL builder with Common Table Expression (WITH clause) support | [
"",
"sql",
"node.js",
"postgresql",
"amazon-redshift",
""
] |
I have the following schema in a mysql database
```
Field | Type | Null | Key | Default | Extra
------------+---------+----------+-------+-----------+---------
answerId int(11) NO PRI NULL
answerDate datetime YES NULL
creationDate datetime YES NU... | ```
Select questionID, count(*) as totalAnswers from qanda
group by questionID
having totalAnswers > 5
```
[Example SQL Fiddle](http://sqlfiddle.com/#!2/230ab/6) | Will it work for you ?
```
SELECT questionId
FROM question_answer
GROUP BY questionId
HAVING COUNT(*) >5
```
Side note. Some other attributes ,`url`,`creationDate`, and `description`, don't seem like they describe relationship between question and answer... | Use number of distinct values from a column as select criteria | [
"",
"mysql",
"sql",
"select",
"relational-database",
""
] |
I have a table ProdByCat
```
CatID ProductID
---------------------------
Food Beans
Food Corn
Food Peas
Drink Juice
Drink Wine
```
And another table Purchases
```
Region ProductID Cost
-----------------------------
North Beans 5
South Beans ... | Lets create the test data:
```
DECLARE @ProdByCat TABLE
(
CatID VARCHAR(10),
ProductID VARCHAR(10)
)
INSERT INTO @ProdByCat
( CatID, ProductID )
VALUES
('Food' ,'Beans'),
('Food' ,'Corn'),
('Food' ,'Peas'),
('Drink' ,'Juice'),
('Drink' ,'Wine');
DECLARE @Purchases TABLE
(
... | You're right. You are over complicating it. It can be much simpler:
```
SELECT p.Region, pbc.CatID, SUM(p.Cost) AS TotalCost
FROM Purchases p
INNER JOIN ProdByCat pbc
ON p.ProductID = pbc.ProductID
GROUP BY p.Region, pbc.CatID;
``` | SUM first table on second CATEGORY table | [
"",
"sql",
"sql-server",
"t-sql",
"sum",
""
] |
I have 8 tables:
received1, received2, received3, received4,
recovery1, recovery2, recovery3, recovery4
Each of these tables has a field named "Item".
What I want to do is to find all the records that has a match between received and recovery, however, if an item is in received3 but not in recovery3, I don't want to ... | From your example it seems an 'item' always follows the receive-recover-receive-recover pattern. If that's the case, an item can only be considered if it appears a multiple of two times. Also since you have not given any further details on table structure I am assuming an 'item' does not repeat. In such case, the below... | What you can do is left outer join the tables and in your where clause add the condition for excluding the records you don't want eg
```
SELECT ...
FROM received1 left outer join received1 on (received1.item = received1)
left outer joing on received2 etc...
WHERE received1 != null OR received2 != null ...
```
... | SQL exclude certain records in subquery | [
"",
"sql",
"sql-server",
"join",
""
] |
Here is the table schema;
```
create table campaign (
id INT NOT NULL,
custom_param1 VARCHAR(15),
custom_value1 VARCHAR(15),
custom_param2 VARCHAR(15),
custom_value2 VARCHAR(15),
custom_param3 VARCHAR(15),
custom_value3 VARCHAR(15),
PRIMARY KEY (id)
)
```
and this is the mock data I ha... | Depending on what you want to do if the value is null, you can try
```
SELECT CONCAT(
c.custom_param1, '=', IFNULL(c.custom_value1, ''), '; ',
c.custom_param2, '=', IFNULL(c.custom_value2, ''), '; ',
c.custom_param3, '=', IFNULL(c.custom_value3, ''), '; ') as 'Custom Parameters'
FROM campaign as c;
```
Will return
`... | Use ifnull <http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull>
```
select CONCAT(IFNULL(c.custom_param1, ''), '=', IFNULL(c.custom_value1, ''), '; ', IFNULL(c.custom_param2, ''), '=', IFNULL(c.custom_value2, ''), '; ', IFNULL(c.custom_param3, ''), '=', IFNULL(c.custom_value3,'')) as 'C... | mysql concatenate columns if column is not null | [
"",
"mysql",
"sql",
"concatenation",
""
] |
i'm using the following code
```
create TABLE #temp1(
[date] [varchar](500) NULL,
[time] [varchar](500) NULL,
[s-ip] [varchar](500) NULL,
[cs-method] [varchar](500) NULL,
[cs-uri-stem] [varchar](max) NULL,
[cs-uri-query] [varchar](max) NULL,
[s-port] [varchar](500) NULL... | Thanks all for your valuable answer
But again after long search in Google.
I found one solution ,that this is a Microsoft sql server bug
This bug can only be solved when we install latest service pack of sql server in our system
And when I have installed service pack in my system bulk insert works well.
For any fu... | set all varchar to max and do the bulkfiles again, and please can you paste your log file to excel and see if the total row is really 1521000?
The problem usually caused by invalid fieldterminator and rowterminator. | Bulk insert does not insert all the rows from the log file without giving any error | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to get two counts of separate columns for data in one table.
I have a database that tracks issues, and one table, Issue, has the 2 relevant columns that each contain a date. Very similar to the following.
```
DateOpened DateClosed
2015-01-08 2015-01-08
2015-01-08 2015-01-08
2015-01-06 2015-01-08
2015-0... | One way of doing this is to use `union all` to create a single column for both dates and then group according to its type:
```
SELECT `Date`,
COUNT(`open`) AS `CountDateOpened`
COUNT(`closed`) AS `CountDateClosed`
FROM (SELECT `DateOpened` AS `Date`, 1 AS `open`, NULL AS `closed`
FRO... | Try this
```
select
d.dt,(select COUNT(DateOpened) ct from ISSUE where
CAST(DateOpened as DATE)=CAST(d.dt as DATE) )
,(select COUNT(DateClosed) ct from ISSUE where
CAST(DateClosed as DATE)=CAST(d.dt as DATE) )
from (
select number,DATEADD(D,number-7,GETDATE()) dt
from master.dbo.spt_values sp
where type='P' and DAT... | Count 2 columns by the same grouping | [
"",
"mysql",
"sql",
"select",
"count",
"group-by",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.